Python
Python
# - for commenting
Naming variable
4. case sensitive
In python there is no need to declare what data type the variable value is
Print(type(name))
1.string
2.int
3.float
Eg.code
a = True
b = False
print(type(a))
print(a)
print(b)
out –
<class 'bool'>
True
False
1
We have 2 ways to srtore values in variables
Eg.code
1st way
a = "Tomato"
b = "Cabbage"
c = "onion"
print(a)
print(b)
print(c)
out-
Tomato
Cabbage
Onion
2nd way
a, b, c= "Tomato", "Cabbage","onion"
print(a)
print(b)
print(c)
out –
Tomato
Cabbage
Onion
Python operators
1.Addition
2.Substraction
3.Multiplication
4.Division
1.Addition
Eg.code
2
a, b = 10, 20
c=a+b
print(c)
out –
30
2.Substraction
a, b = 10, 20
c=a-b
print(c)
out –
-10
3.Multiplication
a, b = 10, 20
c=a*b
print(c)
out-
200
4.Division
a, b = 10, 20
c=a/b
print(c)
out –
0.5
5.Modulus
When we divide two numbers , we get a reminder on last, that is known as modulas
3
a, b = 10, 3
c=a%b
print(c)
out –
6.Exponentiation **
square of a number
eg.code –
a=2
c = 2 ** 2
print(c)
out –
Cube of a number
a=2
c = 2 ** 3
print (c)
out –
Eg.code –
a , b= 10 , 3
c = a // b
print(c)
4
out –
Assignment Operators
1.Equal Operator
2. +=
Eg.code-
x = 10
x +=4 #ie, x = x + 4
print(x)
out –
14
3. -=
Eg.code-
x = 10
x -= 4 #ie, x = x - 4
print(x)
out –
4. *=
Eg.code-
x = 10
x *= 4 #ie, x = x * 4
print(x)
out –
40
5. /=
Eg.code-
5
x = 10
x /= 2 #ie, x = x / 2
print(x)
out –
6. %=
Eg.code-
x = 10
x %= 4 #ie, x = x % 4
print(x)
out –
7. //=
Eg.code-
x = 10
x //= 3 #ie, x = x // 3
print(x)
out –
8. **=
Eg.code-
x = 10
x **= 3 #ie, x = x ** 3
print(x)
out –
1000
1.Equal to ==
Eg code –
6
1.
a = 10
b = 20
print(a == b)
out –
False
2.
a = 10
b = 10
print(a == b)
Out –
True
1.Equal to !=
1.
a = 10
b = 10
print(a != b)
Out –
False
2.
a = 15
b = 10
print(a != b)
Out –
True
7
4.Less than <
1. AND Operator
1.
Eg code –
a = 10
Out –
True
2.
Eg code –
a = 10
Out –
Flase
When we use ‘and’ operators , only we get ‘True’ as the result when both of them are true, else we
get ‘false’
2.OR Operator
Eg code –
8
1.
a = 10
print(a == 10 or a > 1)
Out –
True
2.
a = 10
print(a == 11 or a > 1)
Out –
True
3. NOT Operators
Oposite result
Eg code –
1.
a = 10
print(not (a == 11))
Out –
True
2.
a = 10
print(not (a == 10))
Out –
9
False
Python Strings
Code 1 –
Code 1 –
text = 'learn python' # we can put single quotes as well to write the texts
print(text)
Code 3 –
text = """
Learn python
python is an open source lang
it is easy to study
"""
print(text)
Out –
Learn python
python is an open source lang
it is easy to study
Eg code –
text = "Hello"
print(text[0])
10
print(text[1])
print(text[2])
print(text[3])
print(text[4])
Out –
Suppose we want to print mixed alphabets or elements in a string, then we can do like in the
program below
text = "Hello"
print(text[0:5])
Out –
Hello
text = "Hello"
print(len(text))
Out –
Out –
11
Hello world
Code –
Out –
Hello world
Code –
Out –
Hello world
Replace Method
Suppose we are entered a text , and print it , now we want to replace an alphabet or a word, then we
can use ‘Replace’ .
Initially
Code –
Out –
Hello world
Finally ,
12
Out –
Hai world
For example
a = Learn
b = Python
Example Code –
a = 'Learn '
b = 'Python'
c=a+b
print(c)
Out –
Learn Python
Initial Code :-
Out –
Example codes :-
13
Out put –
Code –
Output –
Or
Code :-
name = "Parthiv"
text = "My name is {}, I am 50 years old"
print(text.format(name))
Output –
Code :-
name = "Parthiv"
age = "25"
text = "My name is {}, I am {} years old"
print(text.format(name,age))
Output :-
14
Python Collections or Python Data types
1. List
2. Tuple
3. Set
4. Dictionary
List
list1 = ["onion" , "Tomato" , "Carrot"] #here we can store different values or datas in a single variable
Code –
Out put –
Out put –
In a list , each element have a specific index number starts form 0 to onwards
Code –
15
list1 = ["onion" , "Tomato" , "Carrot"]
print(list1[0])
Out put –
Onion
Yes , We can
Code –
list1 = [10,20,30,40,50]
sum = list1[0] + list1[1]
print(sum)
Out put –
30
Code –
list1 = [10,20,30,40,50]
list2 = [10,20,30,40,50]
sum = list1[0] + list2[4]
print(sum)
Out put –
60
Suppose we want to change the ‘Onion’ and replace ‘potato’ there, what we do?
Code –
16
list1 = ["onion" , "cabbage" , "Tomato"]
list1[0]="potato" #here is the term that changes the list element
print(list1)
Out –
Okay, now how can we display list elements one by one by using the for loop?
Code –
for x in list1:
print(x)
Out –
onion
cabbage
Tomato
How can we add just extra element to the current list we created?
list1 = ["onion" , "cabbage" , "Tomato"]
Code –
list1 = ["onion" , "cabbage" , "Tomato"] #when we use the append , the added one appear as the last
of the string. Also in append method, just one extra elements can be added, not replaced.
list1.append("Brinjal")
print(list1)
Out –
How can we add the element in the string, in the position that we want in the string?
Code –
17
list1 = ["onion" , "cabbage" , "Tomato"]
Out –
list1.remove("Brinjal")
print(list1)
Out –
list1.clear()
print(list1)
Out –
[] #Empty sring
Code –
del list1
print(list1)
Out –
18
Python Tuple
What is the difference of tuple from list? :- in a list we can remove or edit the element in the list,
while the elements in the tuple cant be edited once it is created.
Out –
Code –
Out –
Potato
How to print all elements in the tuple one by one by using for loop?
Code –
Tomato
Carrot
Potato
19
We can use len for finding the length of the tuple
Even though we cant edit or change the elements in the tuple, we can delete the entire elements in a
tuple by using the term del
Code –
Out –
Code –
Out –
20
Set
Set is
Un ordered
Un indexed
It means in each times we print the set , we get the elements in different order
For example
Code –
Out1 –
Out2 –
Because of un ordered and un indexed, we cant access the elements of the set by using index
number
We can check or search a particular element , in the set by using the in element.
Code –
Out put -
True
Code2 –
Out –
21
False
Out –
Code –
Out –
Code –
Out –
{'Onion', 'Carrot'}
22
Out –
{'Onion', 'Carrot'}
If we use Remove we can only remove only the items in the set, if the item is not there in the set, it
shows error message when we use Remove to remove the element.
While in the case of Discard , it can use for remove the element in the Set ,also the elements that not
occupied in the set.
means, it doesn’t shows error message , when the element is not there ,
Set1 = {1,2,3,4,5,6,7,8,9}
Set2 = {10,11,12,13,14,15,16,17,18,19}
Set3=Set1.union(Set2)
print(Set3)
Out –
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
For removing all the elements in a set , we can use Clear keyword.
Code –
Set1 = {1,2,3,4,5,6,7,8,9}
Set1.clear()
Out –
23
Dictionary
It have
Word = Meaning
In python we have
Key = Value
“name” : “John” ,
“email” : “john@gmail.com”
“phone” : 1234567890
If we want to access a particular value in the dictionary we can call it and print it on the screen.
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
a = dict1["phone"]
print(a)
Out put –
1234567890
Or
Code –
24
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
a = dict1.get("phone")
print(a)
Out put –
1234567890
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
dict1["name"] = "smith"
print(dict1)
Out –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
for x in dict1:
print(x)
Out –
name
25
email
phone
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
for x in dict1:
print(dict1[x])
Out –
john
john@gmail.com
1234567890
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
for x , y in dict1.items():
print( x , y )
Out –
name john
email john@gmail.com
phone 1234567890
26
To add new value in the keyword,
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
dict1["email"] = "John00@gmail.com"
print(dict1)
Out –
Can delete a key and its value entirely by using pop and del
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
dict1.pop("name")
print(dict1)
Or
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
del dict1["name"]
print(dict1)
Out –
27
To clear all keys and their values , use Clear keyword
Out –
{} #empty
Code –
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890
}
del dict1
print(dict1)
Out –
28
IF Statements
Eg Code1 –
a=5
if a > 0 :
print("its a positive number") #it is mandatory that there should be an indentation after the ‘if’,
Out –
Eg Code2 –
a=0
if a > 0 :
print("its a positive number")
elif a < 0 :
print("its a negative number")
else :
print("its a zero number")
Out –
Nested IF
Eg Code –
a=0
if a >= 0 :
if a > 0 :
print("it is a positive number")
else :
print("it is a zero")
else :
print("it is a negative number")
Out –
29
it is a zero
Eg Code –
a=6
if a > 5 and a < 25 :
print("Hello World")
Out –
Hello World
30
Loop Statement
Eg Code –
i=1
while i < 6 :
print(i)
i += 1 # i= i + 1
Out –
31
5
For Loop
It is mainly used for printing characters in a string or collection data types like list, tuple , sets
Eg Code –
We have a string ‘Hello’ , now How to print each letters in the string?
a = "HELLO"
for i in a:
print(i)
Out –
Code –
a = ["Tomato","Banana","Carrot"]
for i in a:
print(i)
Out –
Tomato
Banana
Carrot
Code –
32
for i in range(10):
print(i)
Out –
Code –
for i in range(2,10):
print(i)
Out –
33
Python Functions
We define something called functions (it contain a particular job) , then we write the codes inside it,
we call it in the main code , when we want the function .
Eg code –
def message():
print("Hello World")
Out –
Hello World
Eg Code2-
def message(name):
print("Hello " + name)
message("Anil") # here we call the function here
Out –
Hello Anil
Eg Code 3 –
def message(name):
print("Hello " + name)
message("Anil") # here we call the function here
message("John")
Out –
Hello Anil
Hello John
34
Eg Code4 –
def find_sum(num1,num2):
print(num1+num2)
find_sum(1,2)
Out –
Eg Code5 –
def find_sum():
return 10 + 20; # after adding 10 and 20 , it will be returned to the function
print(find_sum())
Out –
30
Eg Code6 –
def find_square(num) :
return num*num
print(find_square(5))
Out –
25
35
Recursion
It is a function, but we call the function in the same function when we want it.
Ex Code –
def recursion(n) :
if n <= 1 :
return n
else :
return n + recursion (n-1)
s = recursion(3)
print(s)
Out –
36
Lambda
For example:
def Lambda x : x * x
Argument Expression
“Lamba” is a keyword.
We can use more arguments, but can be use only one expression.
Filter function
🔹 How it works
filter(function, iterable)
3. Finally, filter() gives you an object with only the "kept" values.
37
numbers = [10, 15, 20, 25, 30]
filter() helps us to pick out only the elements that match a condition without writing long
loops.
38
Object Oriented Programming
1. Data (attributes/state)
x=5
Here:
Try:
s = "hello"
39
print(s.upper()) # HELLO
mylist = [1, 2, 3]
mylist.append(4)
print(mylist) # [1, 2, 3, 4]
🔹 Simple definition
👉 An object is like a "thing" in Python that stores data and knows how to work with that data
(through its methods).
📌 mylist = [1, 2, 3]
So:
40
📌 Visual Picture
mylist ───▶ [ 1 2 3 ]
│ │ │
Example: [1, 2, 3] →
41
Class = frame/blueprint
✅ Example in code:
mylist = [1, 2, 3]
⚡ In short:
Python has many built-in frames (classes): int, float, str, list, set, etc.
OOPS Concept
class student():
def __init__(self,name,age,gender):
self.name=name 1st Part
self.age=age
self.gender=gender
def disp1(self):
print(f"Name:{self.name}\nAge:{self.age}\nGender:{self.gender}") 2nd Part
42
student1=student("Parthiv",23,"Male")
3rd Part
student2=student("Sam",25,"Male")
student1.disp1()
4th part
student2.disp1()
__init__ is the constructor — it runs automatically whenever you create a new student.
👉 Think of this like: “When I make a student, store their details inside.”
👉 Think of this like: “I am creating real students from the student blueprint.”
43
🔹 Part 4: Using the Objects
💡 In short:
44
Inbuild Mathematical Functions in Python
1.min -
Code
a = min(10,5,8,25)
print(a)
Out –
2.max
3.pow
Code –
a = pow(2,3) # 2 ** 3 or 2^3
print(a)
45
Out –
Eg Code1 –
import math
a= math.pi
print(a)
Out –
3.141592653589793
Eg Code2 –
import math
a = math.sqrt(9)
print(a)
Out –
3.0
1st create a python file as a module, with the file name we required with .py extension
Then we can access that module by simply “import module_name” on that file.
Ex code –
def message(name):
print("Hello" , name)
46
test_module.py #file name
import my_module
my_module.message("parthiv")
Out –
Python-File handling
f = open("C:/Users/Parthiv/Downloads/Makbig/sample.txt" , "w")
f.write("Learn Python Programming")
f. close()
47
Practical Sessions
1.Divmode(num1,num2)
A = Divmode(num1,num2)
A[0] = quotient
A[1] = reminder
2.How can find the length of a variable , that is stored with a number
A = 12345
Length = len(str(A))
To check if a year is a leap year, you must perform these checks in a specific order:
48
o If Yes, proceed to the next step.
For a year to be a leap year, it doesn't have to satisfy all the conditions simultaneously. It needs to
satisfy a specific combination of conditions, as outlined below.
Rule 1: The year is evenly divisible by 4 but not evenly divisible by 100.
OR
This means if a year satisfies Rule 1, you don't need to check Rule 2. If it fails Rule 1, you then check if
it satisfies Rule 2.
Code –
4.Paliandrome
Code –
num1 = 12345
num2 = num1[::-1]
49
5.Concept of prime number
1. The number must be greater than 1. Any number less than or equal to 1 is not a prime
number.
2. The number should not be divisible by any integer from 2 up to its square root. If you find
even one number that divides it evenly (with a remainder of 0) in this range, the number is
not a prime.
Code – for dividing the number with more than one divisors
number = 100
6.Patterns
Code –
for i in range(5):
for j in range(i+1):
print("*",end='')
print()
Out –
**
***
****
*****
print('*', end=''): The end='' part is crucial. It tells Python to print the star without moving to
a new line, so all the stars for that row stay on the same line.
50
Print() – in default it have /n command
print(): This empty print() statement is executed after the inner loop finishes. It adds a new
line, so the next row of stars starts on a fresh line.
Code –
for i in range(5):
for j in range(5-i-1):
print(" ",end='')
for k in range(2*i+1):
print(i+1,end='')
print()
Out –
222
33333
4444444
555555555
if a:
51
What does "truthy" mean?
Python automatically decides whether a value should be treated as True or False when used
in conditions.
7.
.split() - It allows the user to enter both numbers on a single line, separated by a space.
Eg.
here we can enter the two numbers on the line separated by a space
52
8.
abs() - built-in Python function that returns the absolute value of a number
In simple terms:
If the number is negative, abs() returns the positive version of that number.
max() and min() are simple, built-in functions in Python that find the largest and smallest items in a
sequence of data, like a list.
max()
max("apple", "banana", "cherry") returns "cherry" (it's the last word alphabetically).
min()
Truthy Values: Any non-zero number (positive or negative) is considered True. Non-empty
strings, lists, and other data structures are also True.
Falsy Values: The number zero (0) is considered False. An empty string ('') or an empty list
([]) is also False.
53
11.Concept of finding GCD
Here are the steps for the division method, which is the most common implementation:
3. Replace the larger number with the smaller number, and the smaller number with the
remainder.
12.SORTING
54