[go: up one dir, main page]

0% found this document useful (0 votes)
7 views54 pages

Python

Uploaded by

Adith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views54 pages

Python

Uploaded by

Adith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Python

# - for commenting

Naming variable

1.start with letter or underscore

2.cannot start with number

3.in a variable , we can use only alphanumeric (A-Z),(a,z),(0-9),_

4. case sensitive

In python there is no need to declare what data type the variable value is

Suppose we want to know the data type of the variable,


for eg.
name = “john” #when we store a string in a variable, we have to use “”, but we don’t want to use “”
in the case of numbers

Print(type(name))

Output- <class ‘str’>

There is large data types in python

1.string

2.int

3.float

4.Boolean – to store truth or false value

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 –

7.Floor Divider (//)

When we divide two numbers, suppose 10/3c ,we get 3.333


but when we use floor divider operator , we can divide the numbers , but we don’t get the numbers
after the decimal

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

Python Comparison Operators

1.Equal to ==

We can check whether the two variables are equal or not

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

3.Greater than >

7
4.Less than <

5.Greater than or Equal to >=

6.Leass than or Equal to <=

Python logical Operators

1. AND Operator

1.

Eg code –

a = 10

print(a == 10 and a > 8)

Out –

True

2.

Eg code –

a = 10

print(a == 11 and a > 8)

Out –

Flase

When we use ‘and’ operators , only we get ‘True’ as the result when both of them are true, else we
get ‘false’

True : Both statements are true

2.OR Operator

True : One of the statement is true

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 –

text = "learn python" #we can put double quotes


print(text)

Out – learn python

Code 1 –

text = 'learn python' # we can put single quotes as well to write the texts
print(text)

Out – learn python

Code 3 –

Suppose we want to write multi lines , we can use 3 double quotes

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

 Like in the other lang, Python also have ‘string’ concept,


It works like an array. when we enter texts, it works like elements of an array.
Elements of an array starts with index number zero, then onwards it will continue

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

How can we find the length of the string?


code –

text = "Hello"
print(len(text))

Out –

Usually when we run this program under below,

text = " Hello world "


print(text)

Out –

11
Hello world

We have a keyword in python to fix that, known as ‘strip’

Code –

text = " Hello world "


print(text.strip())

Out –

Hello world

To lower case the text, we can use ‘Lower’

Code –

text = "Hello world"


print(text.lower())

Out –

Hello world

Also there is ‘Upper’ for capitalize the text

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 –

text = "Hello world"


print(text)

Out –

Hello world

Finally ,

text = "Hello world"


print(text.replace("Hello","Hai"))

12
Out –

Hai world

We have three variables and each of them have different datas,

For example

a = Learn

b = Python

now we want to display ‘Learn Python’

Example Code –

a = 'Learn '
b = 'Python'
c=a+b
print(c)

Out –

Learn Python

Initial Code :-

text = "My name is Anil, I am 50 years old"


print(text)

Out –

My name is Anil, I am 50 years old

Now we want to put different names on each Run

We can put a place holder

Then we can use ‘Holder’ Keyword

Example codes :-

text = "My name is {}, I am 50 years old"


print(text.format("Anil"))

13
Out put –

My name is Anil, I am 50 years old

Code –

text = "My name is {}, I am 50 years old"


print(text.format("Ajith"))

Output –

My name is Ajith, I am 50 years old

Or

We can done this same code by using another method

Code :-

name = "Parthiv"
text = "My name is {}, I am 50 years old"
print(text.format(name))

Output –

My name is Parthiv, I am 50 years old

What we do , when we want to use 2 place holders

Code :-

name = "Parthiv"
age = "25"
text = "My name is {}, I am {} years old"
print(text.format(name,age))

Output :-

My name is Parthiv, I am 25 years old

14
Python Collections or Python Data types

1. List
2. Tuple
3. Set
4. Dictionary

All of these are working like the working of an array.

List

We have a list for example,

list1 = ["onion" , "Tomato" , "Carrot"] #here we can store different values or datas in a single variable

we can print this list ,

Code –

list1 = ["onion" , "Tomato" , "Carrot"]


print(list1)

Out put –

['onion', 'Tomato', 'Carrot']

To find the length of the list


Code –

list1 = ["onion" , "Tomato" , "Carrot"]


print(len(list1))

Out put –

In a list , each element have a specific index number starts form 0 to onwards

We can access each of the elements by using the index number

Code –

15
list1 = ["onion" , "Tomato" , "Carrot"]
print(list1[0])

Out put –

Onion

Can we do Mathematical Operation between elements of a list?

Yes , We can

Code –

list1 = [10,20,30,40,50]
sum = list1[0] + list1[1]
print(sum)

Out put –

30

Also we can perform Operation in between different lists elements also

Code –

list1 = [10,20,30,40,50]
list2 = [10,20,30,40,50]
sum = list1[0] + list2[4]
print(sum)

Out put –

60

How can we change the values in a list

Assume that we have a list ,


list1 = [“onion” , “cabbage” , “Tomato”]

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 –

['potato', 'cabbage', 'Tomato']

Okay, now how can we display list elements one by one by using the for loop?
Code –

list1 = ["onion" , "cabbage" , "Tomato"]

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"]

We want to add , brinjal , How can we do that?

We can use the term Append

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 –

['onion', 'cabbage', 'Tomato', 'Brinjal']

How can we add the element in the string, in the position that we want in the string?

Code –

17
list1 = ["onion" , "cabbage" , "Tomato"]

list1.insert(0 ,"Brinjal") #Brinjal insert as the 0th element in the string


print(list1)

Out –

['Brinjal', 'onion', 'cabbage', 'Tomato']

How to remove the element in the string,


Code –

list1 = ["Brinjal","onion" , "cabbage" , "Tomato"]

list1.remove("Brinjal")
print(list1)

Out –

['onion', 'cabbage', 'Tomato']

How to clear all the elements in the string?


Code –

list1 = ["Brinjal","onion" , "cabbage" , "Tomato"]

list1.clear()
print(list1)

Out –

[] #Empty sring

We can delete the string entirely by using the term del

Code –

list1 = ["Brinjal","onion" , "cabbage" , "Tomato"]

del list1
print(list1)

Out –

'list1' is not defined

18
Python Tuple

Its like an array in the python , it works like an array.

It is created inside the Round bracket.

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.

Example code of Tuple –

tuple1=("Tomato", "Carrot", "Potato")


print(tuple1)

Out –

('Tomato', 'Carrot', 'Potato')

How to access the tuple element?

Code –

tuple1=("Tomato", "Carrot", "Potato")


print(tuple1[2])

Out –

Potato

How to print all elements in the tuple one by one by using for loop?

Code –

tuple1=("Tomato", "Carrot", "Potato")


for x in tuple1:
print(x)

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 –

tuple1=("Tomato", "Carrot", "Potato")


del tuple1

Out –

We can combine two or more tuples

Code –

tuple1=("Tomato", "Carrot", "Potato")


tuple2 = ("1" , "2" , "3" , "4")
print(tuple1+tuple2)

Out –

('Tomato', 'Carrot', 'Potato', '1', '2', '3', '4')

20
Set

It is also a collection data type in python

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 –

set1 = {"Tomato" , "Potato" , "Onion"}


print(set1)

Out1 –

{'Onion', 'Tomato', 'Potato'}

Out2 –

{'Potato', 'Tomato', 'Onion'}

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 –

set1 = {"Tomato" , "Potato" , "Onion"}


print("Tomato" in set1)

Out put -
True

Code2 –

set1 = {"Tomato" , "Potato" , "Onion"}


print("brinjal" in set1)

Out –

21
False

In set we can add elements by using the Add element


Code –

set1 = {"Tomato", "Onion", "Carrot"}


set1.add("Brinjal")
print(set1)

Out –

{'Brinjal', 'Tomato', 'Carrot', 'Onion'}

If we want to add more than one elements


We can use Update elements

Code –

set1 = {"Tomato", "Onion", "Carrot"}


set1.update(["Brinjal", "Pineapple"])
print(set1)

Out –

{'Carrot', 'Brinjal', 'Onion', 'Tomato', 'Pineapple'}

If we want to remove an element from the Set, We can use Remove

Code –

set1 = {"Tomato", "Onion", "Carrot"}


set1.remove("Tomato")
print(set1)

Out –

{'Onion', 'Carrot'}

We can use Keyword Discrd as well to remove an element.


Code –

set1 = {"Tomato", "Onion", "Carrot"}


set1.discard("Tomato")
print(set1)

22
Out –

{'Onion', 'Carrot'}

But there is different for Discard and Remove

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 ,

If we want to combine two of the sets, Use Union Keyword


Code –

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 is also a collection data type

Assume that we have a dictionary

It have

Word = Meaning

In python we have

Key = Value

We are making a dictionary ,


dict1 = {

“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

We can call the values in another way

Code –

24
dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890

}
a = dict1.get("phone")
print(a)

Out put –

1234567890

If we want to change an alternate keys value ,

Code –

dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890

}
dict1["name"] = "smith"
print(dict1)

Out –

{'name': 'smith', 'email': 'john@gmail.com', 'phone': 1234567890}

To print all keys in a dictionary,


Code –

dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890

}
for x in dict1:
print(x)

Out –

name

25
email

phone

To print all the values in a dictionary ‘

Code –

dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890

}
for x in dict1:
print(dict1[x])

Out –

john

john@gmail.com

1234567890

To display keys and values in a dictionary together,

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 –

{'name': 'john', 'email': 'John00@gmail.com', 'phone': 1234567890}

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 –

{'email': 'john@gmail.com', 'phone': 1234567890}

27
To clear all keys and their values , use Clear keyword

Out –

{} #empty

Also , can use del keyword

Code –

dict1 ={
"name" : "john" ,
"email" : "john@gmail.com" ,
"phone" : 1234567890

}
del dict1
print(dict1)

Out –

'dict1' is not defined.’

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’,

we can click tab switch for the right indentation

Out –

its a positive number

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 –

its a zero number

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

Also we can apply logical operators in the condition,

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 –

Suppose we have list, then how to do it?

Code –

a = ["Tomato","Banana","Carrot"]
for i in a:
print(i)

Out –

Tomato

Banana

Carrot

There is a keyword called Range ,

Code –

32
for i in range(10):
print(i)

Out –

Suppose we want to print from 2 to 9

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 .

We can create a function by using the def

Eg code –

def message():
print("Hello World")

message() # here we call the function here

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 –

Code for finding the sum of nth number

def recursion(n) :
if n <= 1 :
return n
else :
return n + recursion (n-1)
s = recursion(3)
print(s)

Out –

36
Lambda

It is known as anonymous function because it doesn’t have a name when it is defined.

It have two parts, Arguments and expressions

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.

Also we can use the Lamba inside a function

Filter function

🔹 How it works

filter(function, iterable)

1. It takes each element of the iterable (like a list).

2. Passes it to the function.

o If the function returns True, the element is kept.

o If it returns False, the element is discarded.

3. Finally, filter() gives you an object with only the "kept" values.

(Usually, we convert that object into a list to see the result.)

37
numbers = [10, 15, 20, 25, 30]

# Keep only numbers divisible by 10

result = list(filter(lambda x: x % 10 == 0, numbers))

print(result) # [10, 20, 30]

🔹 Purpose in one line:

filter() helps us to pick out only the elements that match a condition without writing long
loops.

38
Object Oriented Programming

Class and Objects

Everything in Python is an object

 Numbers, strings, lists, functions, even classes → all are objects.

 An object is basically something stored in memory that has:

1. Data (attributes/state)

2. Behavior (methods/functions it can do)

🔹 Example 1: Integer object

x=5

Here:

 5 is not just a number — it’s an object of class int.

 It has attributes (internal data like its value).

 It has methods (like bit_length(), to_bytes()).

Try:

print(type(x)) # <class 'int'>

print(x.bit_length()) # 3 (since 5 in binary is 101 → 3 bits)

🔹 Example 2: String object

s = "hello"

 "hello" is an object of class str.

 It has methods like .upper(), .lower(), .replace().

print(type(s)) # <class 'str'>

39
print(s.upper()) # HELLO

🔹 Example 3: List object

mylist = [1, 2, 3]

 [1, 2, 3] is an object of class list.

 It has methods like .append(), .pop(), .sort().

print(type(mylist)) # <class 'list'>

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]

 The whole thing [1, 2, 3] is one object of class list.

 Inside that list object, there are three separate objects:

o 1 → an object of class int

o 2 → an object of class int

o 3 → an object of class int

So:

 [1, 2, 3] → list object

 1, 2, 3 → integer objects stored inside the list

40
📌 Visual Picture

mylist ───▶ [ 1 2 3 ]

│ │ │

│ │ └── int object (3)

│ └────── int object (2)

└────────── int object (1)

🔹 Think of class as a blueprint / frame

 A class is like a design or template.

 Example: class int is the blueprint for integers.

 Example: class list is the blueprint for lists.

🔹 An object is an actual thing created from the blueprint

 When you write 5 → Python creates an object of class int.

 When you write [1, 2, 3] → Python creates an object of class list.

🔹 Inside Objects (composition)

 A list object can hold other objects.

 Example: [1, 2, 3] →

o [1, 2, 3] → object of class list

o 1 → object of class int

o 2 → object of class int

o 3 → object of class int

So yes, you can think like this:

41
 Class = frame/blueprint

 Object = actual instance (created from class)

 Sub-objects = objects stored inside another object

✅ Example in code:

mylist = [1, 2, 3]

print(type(mylist)) # <class 'list'>

print(type(mylist[0])) # <class 'int'>

⚡ In short:

 Python has many built-in frames (classes): int, float, str, list, set, etc.

 When you use them with values, objects are created.

 These objects can even contain other objects inside.

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()

🔹 Part 1: The Blueprint (class & constructor)

 Here you are making a blueprint (class) called student.

 __init__ is the constructor — it runs automatically whenever you create a new student.

 self.name = name → saves the given name into that object.

 Same for age and gender.

👉 Think of this like: “When I make a student, store their details inside.”

🔹 Part 2: A Method (what the object can do)

 This is a method (like a function inside the class).


 disp1() will display the details of that student.

🔹 Part 3: Making Objects (real students)

 Now you’re creating objects (real students) using the blueprint.

 student1 has details → "Parthiv", 23, "Male"

 student2 has details → "Sam", 25, "Male"

👉 Think of this like: “I am creating real students from the student blueprint.”

43
🔹 Part 4: Using the Objects

 You’re calling the method disp1() for each student.

 That prints their saved details.

👉 Think of this like: “Ask the student to introduce themselves.”

💡 In short:

 Part 1 → Make blueprint

 Part 2 → Add actions (methods)

 Part 3 → Create real objects

 Part 4 → Use the objects

44
Inbuild Mathematical Functions in Python

1.min -

Code

a = min(10,5,8,25)
print(a)

Out –

2.max

Its like min, but it is used to find the maximum

3.pow

Code –

a = pow(2,3) # 2 ** 3 or 2^3
print(a)

45
Out –

We have an inbuild module named as math , it contain large functions

Have to import math before we using it.

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

How to create a Module ?

1st create a python file as a module, with the file name we required with .py extension

Then create a function on that module , we created

Then we can access that module by simply “import module_name” on that file.

Ex code –

My_module.py #file name

def message(name):
print("Hello" , name)

46
test_module.py #file name

import my_module
my_module.message("parthiv")

Out –

Hello World Parthiv

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)

When we use this , we get both quotient and reminder .

We can access those by ,

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))

3.Leap Year Concept

To check if a year is a leap year, you must perform these checks in a specific order:

1. Check if the year is divisible by 4.

o If No, it is not a leap year. You can stop here.

48
o If Yes, proceed to the next step.

2. Check if the year is also divisible by 100.

o If No, it is a leap year. You can stop here.

o If Yes, proceed to the final step.

3. Check if the year is also divisible by 400.

o If Yes, it is a leap year.

o If No, it is not a leap year.

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.

The Correct Leap Year Conditions

A year is a leap year if it meets either of the following two rules:

Rule 1: The year is evenly divisible by 4 but not evenly divisible by 100.

OR

Rule 2: The year is evenly divisible by 400.

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 –

year = int(input("enter the year you want to check "))

if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) :


print("the year ",year, "is a leap year")
else :
print("the year ", year, "is not a leap year")

4.Paliandrome

We can done the reversal of a string

Code –

num1 = 12345

num2 = num1[::-1]

49
5.Concept of prime number

Conditions for a Number to be Prime

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

for divisor in range(2, 6):

result = number / divisor

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

In Python, the line

if a:

is checking whether the variable a is truthy.

51
What does "truthy" mean?

 Python automatically decides whether a value should be treated as True or False when used
in conditions.

 Non-empty strings (like "hello") are considered True.

 An empty string ("") is considered False.

7.

.split() - It allows the user to enter both numbers on a single line, separated by a space.

Eg.

num1, num2 = input("Enter two numbers separated by a space: ").split()

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 positive, abs() returns the number itself.

 If the number is negative, abs() returns the positive version of that number.

 If the number is zero, abs() returns zero.

9.max and min

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()

The max() function returns the largest item in an iterable.

 max([10, 5, 25, 8]) returns 25.

 max("apple", "banana", "cherry") returns "cherry" (it's the last word alphabetically).

min()

The min() function returns the smallest item in an iterable.

 min([10, 5, 25, 8]) returns 5.

 min("apple", "banana", "cherry") returns "apple".

10. Truthiness and Falsiness

 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

Example: Finding the GCD of 48 and 18

1. 48÷18=2 with a remainder of 12. The new pair is (18, 12).

2. 18÷12=1 with a remainder of 6. The new pair is (12, 6).

3. 12÷6=2 with a remainder of 0. The remainder is now 0

Here are the steps for the division method, which is the most common implementation:

1. Divide the larger number by the smaller number.

2. Get the remainder.

3. Replace the larger number with the smaller number, and the smaller number with the
remainder.

4. Repeat steps 1-3 until the remainder is 0.

5. The GCD is the last non-zero remainder.

12.SORTING

 Use sorted() if you want a new sorted list.

 Use .sort() if you want to sort the existing list.

54

You might also like