python 2025
python 2025
E-Mail : parmeshwar.paul@mctrgit.ac.in
Introduction to Python
Translator
(Compiler / Interpreter)
Python
Features of Python:
1. Python is interpreted language vs C, C++, Java
3. Quick debugging
9. Python provides huge set of libraries (web dev, data science, data analysis, AI & ML etc.)
Comments :
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code
Multiline Comments
2. Variables/Identifier
Data/value can be stored in temporary storage spaces called variables. Variables are containers for storing data.
Identifier
myvar = "John"
Names used for variables, functions, class or objects.
my_var = "John"
Rules:
_my_var = "John"
1. Identifiers can be started with underscore (_)
myVar = "John"
2. Identifiers are case sensitive: e.g., S & s are two different variables
MYVAR = "John"
3. First letter cannot be a digit
myvar2 = "John"
4. Python does not allow punctuation characters such as @, $, and % within identifiers.
age = 25
name = "PARAM"
print(age)
print(name)
print("My age is:" , age)
print("My name is: " , name)
Data Types
❖ Every variable is associated with data type
10, 20, 500, 3.14, 17.15 True, False 3+2j, 5 -2i Hello World
Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
you can assign the same value to multiple variables in one line:
Unpack a Collection
If you have a collection of values in a list, tuple etc.
Python allows you to extract the values into variables.
This is called unpacking.
Swapping Variables
a,b = 'red','blue'
Swapping means interchanging values. a,b = b,a
print(a,b)
Deleting Variables
a=5;
print(a) Casting
del a
print(a) x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Type Conversion: The process of changing the data type of a value from one type to another.
a = 5 x = int(1) # x will be 1
b = 3.5 y = int(2.8) # y will be 2
sum = a + b z = int("3") # z will be 3
print(sum)
3. Operators:
❑ Operators are used to perform operations on variables and values
a = 7
b = 2
# addition
print ('Sum: ', a + b) Sum: 9
# subtraction
print ('Subtraction: ', a - b) Subtraction: 5
# multiplication
print ('Multiplication: ', a * b) Multiplication: 14
# division
print ('Division: ', a / b) Division: 3.5
# floor division
print ('Floor Division: ', a // b) Floor Division: 3
# modulo
print ('Modulo: ', a % b) Modulo: 1
# a to the power b
print ('Power: ', a ** b) Power: 49
# equal to operator
print('a == b =', a == b) a == b = False
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
4. Python Indentation
Indentation refers to the spaces at the beginning of a code line
The indentation in Python is very important.
Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation
The number of spaces is up to you as a programmer, but it has to be at least one. You have to use the same
number of spaces in the same block of code, otherwise Python will give you an error.
Example: Take the two numbers from user and display its addition
3. Write a Program to input two floating point numbers & print their average
3. WAP to input two integer numbers , a & b. Print True if a is greater than or
equal to b. If not print False
❖ If single quotes are used inside the string , then the string should be enclosed within double quote or
vice versa.
name = "My name is 'Pushpa'"
name = "Hello! My name is "Pushpa", what's your name?"
NOTE: single or double quotes within a string can be escaped using backslash character.
Multiline string
name = '''My name is Pushpa....
String is enclosed within triple - single or double quotes Zukega nahi Sala'''
❑ Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
[1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 3, 3]
Characteristics:
Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes the specified value from the list
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
Copy() Returns the shallow copy of the list
#NOT a tuple
tup = ("apple") <class 'str'>
print(type(tup))
tup = ()
print(type(tup)) <class 'tuple'>
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 27
Python Programming, January 2024
tup[0] = 6
tup = (1,2,3,4,5,2,2)
print(tup)
print(tup.count(2))
tup = (1)
print(type(tup))
tup = ( 1, 3, 4, 2, 5, 6 )
tup1 = (1,) res = max(tup)
print(type(tup1)) res1 = min(tup)
print('Maximum of Tuple is', res)
tup = (1,2,3,4,5) print('Minimum of Tuple is', res1)
print(tup.index(2)) print(len(tup))
❑ WAP to ask the user to enter names of their favorite movies and store them in a list.
❑ WAP to count the number of students with the “A” grade in the following tuple.
(“C” , “D” , “A” , “A” , “B” , “B” , “A”)
❑ Accessing Dictionary:
print(dict['name'])
dict['age'] = '32'
dict['surname'] = 'Mulleti'
❑ Nested Dictionary:
student = {'Name':'Mulleti Pushparaj','subjects':{'Phy':67,'Chem':55,'Math':52 }}
print(student['subjects'])
print(student['subjects']['Phy'])
❑ Dictionary Methods:
NOTE: 1. Sets are unordered, so you cannot be sure in which order the items will appear.
2. Set do not allow duplicate items
3. Once a set is created, you cannot change its items, but you can remove items and add new items.
❑ Set Methods:
❑ if statement: a = 33
b = 200
if b > a:
print("b is greater than a")
❑ elif statement: The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
❑ else statement: The else keyword catches anything which isn't caught by the preceding conditions.
Example:
a = 200
b = 200
if b > a:
print("b is greater than a")
elif a>b:
print("a is greater than b")
else:
print("a & b are equal")
❑ Nested-if-else statement:
Example 1:
# Using if-else for Authentication
if username == "admin":
if password == "password123":
print("Login successful.")
else:
print("Invalid password.")
else:
print("Invalid username.")
❑ Nested-if-else statement:
Example 2: # Password and Username Checking
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == "admin":
if password == "password":
print("Login successful! Welcome, admin.")
elif password == "12345":
print("Weak password. Please reset your password.")
else:
print("Incorrect password. Please try again.")
else:
if username == "guest":
if password == "guest":
print("Login successful! Welcome, guest.")
else:
print("Incorrect password. Please try again.")
else:
print("Unknown user. Please try again.")
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 38
Python Programming, January 2024
❑ Nested-if-else statement:
Example 2: WAP to check to check given no. is prime numbers using nested if else
num=int(input("enter a number"))
if num>1:
if num==2:
print("prime no.)")
for i in range(2,num):
if(num%i)==0:
print(num,"is not a prime number")
j=num/i
print(num,"devide by",i,"=",j)
break
else:
print(num,"is prime number")
else:
print(num,"is not a prime number")
❑ while loop:
• Repeats the piece of code until the condition becomes False
i = 1 1
while i < 6: 2
print(i) 3
i += 1 4
5
❑ continue statement: With the continue statement we can stop the current iteration, and
continue with the next:
i = 0
while i < 6: 1
i += 1 2
if i == 3: 4
continue 5
print(i) 6
numbers=[6,5,3,8,4,2,5,4]
sum=0
for val in numbers:
sum=sum+val
print("The sum is", sum)
Example 3: WAP to check to check given no. is prime numbers using nested if else
num=int(input("enter a number"))
if num>1:
if num==2:
print("prime no.)")
for i in range(2,num):
if(num%i)==0:
print(num,"is not a prime number")
j=num/i
print(num,"devide by",i,"=",j)
break
else:
print(num,"is prime number")
else:
print(num,"is not a prime number")
Function
• A function is a block of code which only runs when it is called.
• Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
Example: def sum(a, b): #Function Definition def sum(a, b): #Function Definition
s = a +b s = a +b
print(s) return s
Arguments/Parameters in function
1. Built-in function
2. User-defined function
3. Lambda functions
4. Recursive functions
1. Default Arguments
2. Keyword Arguments
3. Positional Arguments
1. Default Arguments
• During function call, default arguments becomes optional
Output: 14
14
14
2. Keyword Arguments
• Arguments that identifies the parameters by their names
3. Positional Arguments
• Maintain positions(orders) of arguments
def power(a,b):
print(a**b)
power(5,2)
power(2,5)
Output:
Output: 25
32
Output: 30
60
100
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 53
Python Programming, January 2024
Immutable objects:
int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes.
Pass by Reference:
• The actual object is passed to the called function.
• All the changes made to the object inside the function affect its original value.
• Object is mutable type, as mutable objects can be changed, the passed objects are updated.
Mutable objects:
list, dict, set, byte array
Pass by Reference:
Call by Value:
Call by Value:
Call by Reference:
list1[0] = list1[0] + 10
list1 = [10]
Call by Reference:
WAP to check number entered by the user is prime number or not using function.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num/2) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(number," is a prime number.") Output:
else: Enter a number: 17
print(number,"is not a prime number.") 17 is a prime number.
Function
In python, a file operation take place in following order
• Open
• Read/Write (perform operation)
• Close file
Open File:
We have to open a file using built-in function open()
readline() method:
• You can return one line by using the readline() method:
• By calling readline() two times, you can read the two first lines:
• By looping through the lines of the file, you can read the whole file, line by line:
file1 = open("H:\paul\File.txt","r")
print(file1.readline())
print(file1.readline())
# for x in file1:
# print(x)
Close Files: It is a good practice to always close the file when you are done with it.
file1 = open("H:\paul\File.txt","r")
print(file1.readline())
file1.close()
f = open("myfile.txt", "x")
Delete a File:
To delete a file, you must import the OS module, and run its os.remove() function: