Class Notes Till 5th March
Class Notes Till 5th March
PYTHON PROGRAMMING
by
Dr. Sashi Bhusan Nayak
12 19/02/2025 Function 15 – 16
13 21/02/2025 Function 16 – 17
14 22/02/2025 Function 17 – 19
15 24/02/2025 Function 19 – 21
16 28/02/2025 Tuple 21 – 23
17 05/03/2025 Dictionary 24 – 25
❖ LANGUAGE:
Language are of 3 types:
i. Man to Man
ii. Man to Machine
iii. Machine to Machine
❖ COMPUTER:
Computer is an electronic data processing and calculating device.
Source/Socket ⟶ UPS ⟶ (supplies 230V AC) ⟶ SMPS (converts AC to DC) ⟶ 12V DC ⟶ CPU
❖ PROGRAMME:
A set of instruction written in a sequential order to solve any problem is called as
programme.
❖ PROGRAMMING:
• Definition: The way of writing a programme is called programming.
• Python is a programming developed by Guido Van Rossum in the year of 1989, but it
came to market in 1991. He was inspired by the British comedy series named Monte
Python's Flying Circus and wanted the language Python during a holiday break which
was fun and approachable.
• This programme is an object oriented programming used in Web Applications designing as
well as stand alone application.
1
▪ Debugging: Process of finding and fixing errors
▪ Trouble Shooting: Process of identifying and fixing problem
❖ VARIABLE:
It is the name given to the memory location in computer memory where we can store
value.
x = 5
y = 10
z = ‘Ram’
k = 3.2
m = “Ravenshaw”
t = “““RUC”””
❖ Print( ):
It is a function or method in Python used to print content of a variable or any message.
• Example: print(“Welcome to Python World”)
• Example: x=5
print(“The value of x is”,x)
Ex: x1 ✓
_x ✓
32x ✘
❖ DATA TYPE:
These are used to present what type of data we are going to use in our programme. So,
in Python basically the following data types are used.
i. Integers: positive and negative numbers including zero
ii. Float: decimal numbers
iii. String: A string is a sequence of characters that can include letters, numbers,
symbols and spaces. Written inside single or double or triple quote
iv. Boolean: True or False
v. None
• Example:
a=5
b=3.2
2
c=“Ram”
d=True
e=None
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
Output
<class ‘int’>
<class ‘float’>
<class ‘str’>
<class ‘bool’>
<class ‘NoneType’>
• Example:
a=5
b=2
c=a/b
d=a%b
e=a**b
Print(c) # This will print the Quotient
Print(d) # This will print the Remainder
Print(e) # This will Answer print a to the power b
Output
2.5
1
25
3
II. In Type Casting, the programmer converts the data type as per their requirement manually.
Example: x=input(“Enter your name: ”)
y=int(input(“Enter your age: ”))
print(“Welcome”,x) – <class ‘str’>
print(“Your age is”,y) – <class ‘int’>
❖ STRING:
• It is a special datatype.
• A sequence of character is called as String.
• Example – 1:
a=“My divine life”
print(a)
o In this string, space is also considered as a character.
o A string always indexed from 0 to (n-1).
• Example – 2:
s=“India”
print(s)
a S[4]
i S[3]
d S[2]
n S[1]
I S[0]
o We can access string from its index. But we can’t modify it’s index.
o So, String is immutable.
❖ SLICING OF STRING:
• Definition: Breaking a string into small parts is called slicing of string.
• Syntax: string[start_index:End_index:Step]
• Example – 1:
str=“india” 0 1 2 3 4
print(str[1:3]) – Output: nd i n d i a
print(str[:2]) – Output: in -5 -4 -3 -2 -1
print(str[2:]) – Output: dia
Last Index = (n-1)
print(str[-4:-1]) – Output: ndi Start index missing = print from beginning
print(str[-3:]) – Output: dia Last index missing = print till end
print(str[:-2]) – Output: ind
print(str[0:5:1]) – Output: india
print(str[0:5:2]) – Output: ida
print(str[1:5:2]) – Output: ni
print(str[::-1]) – Output: aidni
print(str[::-2]) – Output: adi
print(len(str)) – Output: 5
print(str.endswith(“ia”) – Output: True
4
print(lstr.endswith(“u”) – Output: False
print(str.capitalize()) – Output: India
print(str.find(“n”) – Output: 1
print(str.count(“i”) – Output: 2
print(str.replace(“i”,”k”) – Output: kndka
• Example – 2:
str=input("Enter a name with dollar sign: ")
print(str.count("$"))
print(str.replace("$","h”)
Output
Enter a name with dollar sign: S$ub$am
2
Shubham
• Example – 3:
str=”ABCDE”
print(str[:])
print(str[:5])
print(str[:5:1])
print(str[:5:-1])
print(str[2:5])
Output
ABCDE
ABCDE
ABCDE
EDCBA
CDE
• Example – 4:
x="India is my country"
y=x.split()
print(y)
print(len(y))
Output
['India', 'is', 'my', 'country']
4
❖ LIST:
• List is a built-in datatype which is mutable.
• It allow duplicate elements and ordered (indexed) in which we can store multiple values of
different datatypes.
• List elements are enclosed between square bractet [ ] and separated by comma (,).
• Example – 1:
l=[1,3,4,9,"Ram"] # Creates a list with 5 elements
print(l) # This prints the original list
5
print(type(l)) # type(l) returns the datatype of the list
print(l[0]) # Index 0 refers to the first element of the list, which is “1”
print(l[4]) # Index 4 refers to the last element of the list, which is “Ram”
print(l[2:]) # Extracts elements from index 2 to the end
l[4]=2 # The last element “Ram” is replaced by 2
print(l)
l.append(7) # Appends 7 at the end
print(l)
l.pop() # Removes the last element
print(l)
l.pop() # Removes the last element
print(l)
l.pop(2) # Removes the element at index 2
print(l)
l.clear() # Clears all elements from the list, making it an empty list
print(l)
Output
[1, 3, 4, 9,
• Example – 2:
l=["Ram","Sita"] # Creates a list with two string elements
print(l) # This prints the list “l"
print(type(l)) # This will return the datatype of the list “l”
li=list(("Laxman","Hanuman")) # list ((“Laxman",“Hanuman")) converts a tuple
(“Laxman",“Hanuman”) into a list
print(type(li)) # type(li) confirms that li is of type list
l.extend(li) # This adds all elements of li to l
print(l) # This prints the final list of l
k=[1,2,3,4,5] # Creates another list
li.extend(k) # This adds all elements of k to li
print(li) # This prints the final list of li
Output
['Ram', 'Sita']
<class 'list'>
<class 'list'>
['Ram', 'Sita', 'Laxman', 'Hanuman']
['Ram', 'Sita', 'Laxman', 'Hanuman',1,2,3,4,5]
• Example – 3:
l=["Ram","Laxman","Sita"] # Creates a list with three elements
l.insert(3,"Hanuman") # This adds “Hanuman” at index 3
print(l)
l.pop(1) # This removes the element at index 1
print(l)
l.remove("Hanuman") # This removes “Hanuman" from the list
6
print(l)
Output
['Ram', 'Laxman', 'Sita', 'Hanuman']
['Ram', 'Sita', 'Hanuman']
['Ram', 'Sita']
• Example – 2:
a=5
if (a>5):
print("It is a positive number")
Output
(No output) # The code assigns a = 5 and checks if a > 5. Since the condition is False,
so no output is printed
• Example – 3: Programme to input 2 numbers from the keyboard and finding the
largest between them
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
if(a>b):
print("a is greater")
else:
print("b is greater")
Output - I
Enter first number: 60
Enter second number: 50
a is greater
Output – II
Enter first number: 50
7
Enter second number: 60
b is greater
• Example – 4: Programme to enter marks (out of 100) in 3 subjects to find the average.
If average is more than 80 then the student will get scholarship otherwise not.
a=int(input("Marks in Physics: "))
b=int(input("Marks in Chemistry: "))
c=int(input("Marks in Mathematics: "))
avg=(a+b+c)/3
if (avg>80):
print("Congratulations you got scholarship")
else:
print("Better luck next time")
Output - I
Marks in Physics: 95
Marks in Chemistry: 92
Marks in Mathematics: 94
Congratulations you got scholarship
Output – II
Marks in Physics: 78
Marks in Chemistry: 80
Marks in Mathematics: 74
Better luck next time
• Example – 5: Programme to enter a year and check whether it is a leap year or not.
a=int(input("Enter any year: "))
b=a%4
if (b==0):
print(a,"is a leap year")
else:
print(a,"is not a leap year")
Output - I
Enter any year: 2024
2024 is a leap year
Output – II
Enter any year: 2025
2025 is not a leap year
❖ LOOP:
• When we want to execute a single statement or group pf statements repeatedly in a
programme then we use loop.
• Basicall 3 types of loop are used:
i. while
ii. for
iii. do while
8
➢ while loop:
• It is a pre-test loop.
• It executes only when the condition is true.
• Syntax: initialization of loop counter
while(condition)
body of the loop
updation of loop counter
• Example – 1:
i=1
while i<10:
print(i)
i=i+1
Output
1
2
3
4
5
6
7
8
9
• Example – 2:
i=1
while i<5:
print("Ravenshaw University")
i=i+1
Output
Ravenshaw University
Ravenshaw University
Ravenshaw University
Ravenshaw University
• Example – 3:
i=1
while i<=10:
print("3","×",i,"=",3*i)
i=i+1
Output
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
3 × 4 = 12
3 × 5 = 15
3 × 6 = 18
3 × 7 = 21
9
3 × 8 = 24
3 × 9 = 27
3 × 10 = 30
• Example – 4:
num=int(input("Enter a number: "))
i=1
while i<=10:
print(num,"×",i,"=",num*i)
i=i+1
Output
Enter a number: 5
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50
• Note:
o in is a membership operator
o It's result always yield as True or False
• Example – 6:
x=["Ram","Laxman","Hanuman"]
print(type(x))
print("Ram" in x) # Checks if “Ram” is present in the list x. Since it present it will print
True
i=0
while i<len(x): # len(x) will return 3, so the loop runs from i = 0 to 2
print(x[i]) # It will print all elements of the list
10
i=i+1
Output:
<class 'list'>
True
Ram
Laxman
Hanuman
• Example – 7:
n=int(input("Enter a number: "))
f=1
while f<=n:
f=f*n
f=f+1
print(f)
Output:
Enter a number: 9
10
11
6
24
24
➢ for loop:
• Syntax: for variable in range (start_index, last_index,
incremented/decremented)
• Example – 1:
for i in range (1,10,2):
print(i)
Output
1
3
5
7
9
• Example – 2:
for i in range (10,0,-1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
• Example – 3:
x=["Ram","Kiwi","Apple"]
for i in range(0,len(x)):
print(x[i])
Output
Ram
Kiwi
Apple
• Example – 4:
x=int(input("Enter a Number: "))
i=1
for i in range(i,x):
if x%i==0:
print(i)
Output
Enter a Number: 6
12
1
2
3
13
6
7
8
9
❖ TERNARY OPERATOR:
• A ternary operator (also called a conditional expression) is a one-liner that replaces an
if-else statement to assign values based on a condition.
• It is a compact way to write simple conditional statements.
• Syntax: <variable> = <true value> if <condition> else <false value>
• Example – 1:
a=5
b=10
max=a if a>b else b
print(max)
Output:
10
• Example – 2:
a=5
b=10
14
c=15
max=a if a>b and a>c else b if b>c else c
print(max)
Output
15
❖ FUNCTION:
• Definition: A self contained block of statements which proceed independently is called as
function.
• Function is of 2 types:
i. Built-in or Pre-defined function
Ex: input()
print()
len()
ii. User defined function
Ex: Created by user using a keyword
• Function executes only when it is called.
• Why Function?
o It reduces the code.
o It helps in code reusability.
• Syntax: def name_of_function(): # Function definition
Body of Programme
name_of_function # Function call
• The name of the function is called as function definition.
• We can define a function using a keyword ‘def’.
• Function definition contains the actual calculation and the body of the programme.
• A function definition executes only when it is called.
• A function call has the same name as the function definition.
• At the time of function call, the function definition is executed.
• Example – 2:
def f(name):
15
print("Welcome to Python World",name)
print("How do you do?")
f("Shubham")
Output
Welcome to Python World Shubham
How do you do?
• Example – 3:
def add():
x=5
y=10
z=x+y
print(z)
a=21
b=23
c=a+b
print(c)
add()
add()
Output
15
44
15
44
• Example – 4(a): Programme to calculate the sum and difference of two numbers
using function (without parameters)
def add():
a=5
b=10
c=a+b
print(c)
add() # Calling the add() function
def sub():
a=5
b=10
d=a-b
print(d)
sub() # Calling the sub() function
Output
15
-5
• Example – 4(b): Programme to calculate the sum and difference of two numbers
using function (with parameters)
def add(a,b): # Function definition with two parameters
c=a+b # Adds a and b
16
print(c) # Prints the result
a=5 # Assigns 5 to variable a
b=10 # Assigns 10 to variable b
add(a,b) # Calls the add() function with arguments (5,10)
def sub(a,b): # Function definition with two parameters
d=a-b # Subtracts b from a
print(d) # Prints the result
a=5 # Assigns 5 to variable a
b=10 # Assigns 10 to variable b
sub(a, b) # Calls the sub() function with arguments (5,10)
Output
15
-5
• Example – 5(a): Programme to calculate the area of a circle using function (without
parameters)
def area_of_circle():
r=2
area=3.14*r**2
print("The area of circle is",area)
area_of_circle()
Output
The area of circle is 12.56
17
b=1 # Second term of the Fibonacci series
c=0 # Variable to store the next term
print("a =", a, "b =", b) # Printing the first two terms (0 and 1)
for i in range(2, n): # Loop starts from index 2 (as 0 and 1 are already printed)
c=a+b # The next term is the sum of the previous two terms
print(c) # Printing the next term
a=b # Updating 'a' to the previous 'b'
b=c # Updating 'b' to the newly calculated 'c'
Output
Enter the series up to which you want: 6
a = 0 b = 1
1
2
3
5
19
• Example – 9: Programme to Swap two integers, floats and strings
def swap(a,b):
a,b=b,a
print("After Swapping: a =",a, "b =",b)
# Swapping Integers
x,y=5,10
print("Before Swapping: x =",x, "y =",y)
swap(x,y)
# Swapping Floats
p,q=3.5,7.8
print("Before Swapping: p =",p,"q =",q)
swap(p,q)
# Swapping Strings
str1,str2="Ram","Sita"
print("Before Swapping: str1 =",str1,"str2 =",str2)
swap(str1,str2)
Output
Before Swapping: x = 5 y = 10
After Swapping: a = 10 b = 5
Before Swapping: p = 3.5 q = 7.8
After Swapping: a = 7.8 b = 3.5
Before Swapping: str1 = Ram str2 = Sita
After Swapping: a = Sita b = Ram
Example – 2:
def area(l,b):
ar=l*b
return ar
a=area(5,2)
print(a)
Output
10
• Note:
o The return statement immediately exits the function.
o Anything written after return will not execute.
20
o Example:
def f(n):
print("Welcome to Python World",n)
return
print("How do you do?",n)
f("Shubham")
Output
Welcome to Python World Shubham
➢ Lambda Function:
• It is an anonymous function.
• As it has no name, it is called as anonymous function.
• Basically this function is used to do some small calculations with single line.
• It reduces the code.
• Limitation: In lambda function, any numbers of arguments can be passed but it must
contain atmost one expression only.
• Example – 1:
f=lambda a:a*a
r=f(5)
print(r)
Output
25
• Example – 2:
f=lambda a,b:a+b
k=f(10,20)
print(k)
Output
30
❖ TUPLE:
• Definition: It is a built-in datatype which is immutable, ordered and allow duplicate
elements.
• Example – 1:
x=(1,13,3,4,15,6)
y=("Ram",1,"Shyam",5)
print(x)
print(y)
print(type(x))
print(type(y))
Output
(1, 13, 3, 4, 15, 6)
('Ram', 1, 'Shyam', 5)
<class 'tuple'>
<class 'tuple'>
21
• Packing: Assigning values to tuple variables is called as packing.
• Unpacking: Retriving back values to variables is calles as unpacking.
• Example – 2(a):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,Yellow,*Green)=x # Unpacking the tuple into variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # 'Yellow' gets the second element "Banana"
print(Green) # '*Green' stores the remaining elements as a list ["Kiwi", "Mango",
"Coconut"]
Output
Apple
Banana
['Kiwi', 'Mango', 'Coconut']
• Example – 2(b):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,Yellow,Green,Orange,White)=x # Unpacking all elements of the tuple into
separate variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # 'Yellow' gets the second element "Banana"
print(White) # 'White' gets the last element "Coconut"
Output
Apple
Banana
Coconut
• Example – 2(c):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,*Yellow,White)=x # Unpacking the tuple into variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # '*Yellow' stores the middle elements as a list ["Banana", "Kiwi",
"Mango"]
print(White) # 'White' gets the last element "Coconut"
Output
Apple
['Banana', 'Kiwi', 'Mango']
Coconut
22
Output
('Apple',)
<class 'tuple'>
• Note:
o The comma (,) is necessary when defining a single-element tuple; otherwise, Python
treats it as a string or normal variable.
o ("Apple",) is a tuple, but ("Apple") is just a string
o Example:
x=("Apple",)
y=("Apple")
print(x)
print(type(x))
print(y)
print(type(y))
Output
('Apple',)
<class 'tuple'>
Apple
<class 'str'>
Note: Since tuples are immutable, they can be modified indirectly by converting them into a
list, making changes and then converting them back into a tuple.
Note: Since tuples are immutable, they can be modified indirectly by converting them into a
list, adding elements using .append(), and then converting them back into a tuple.
23
❖ DICTIONARY:
• Definition: It is a built-in datatype which is mutable, unordered and don’t allow duplicate
elements.
• In dictionary a pair of key and its value are stored.
• Example – 1:
d={"Name":"Ram","Age":21,"Address":"India"} # Creating a dictionary d with
key-value pairs
print(d) # printing the dictionary d
print(type(d)) # Printing the type of the variable 'd'
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'India'}
<class 'dict'>
Note: Dictionaries do not allow duplicate keys; if a key is repeated, the latest value
overwrites the previous one.
24
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'Odisha', 'Salary': 21000}
{'Name': 'Ram', 'Age': 21, 'Address': 'Odisha', 'Salary': '3
Lakhs'}
25