Python 1
Python 1
SIMPLE EXAMPLE
Input
Print(“Sara”)
Output
Sara
VARIABLE
SIMPLE EXAMPLE
Input
A = 10
B=5
Print(A+B)
Output
15
EXAMPLE
Input
a=12
Print (type (a))
Output
<Class ‘int’>
Sequence Types:
EXAMPLE
Input
b = ‘Hello’
Print(type (b))
Output
<Class ‘str’>
● Data Science
● Web/Backend Development
● Database Work
● Automation/Testing
● AI/ML
Example: CSV file-la all data string format-la irukkum. But we need to
convert salary or age to int or float to do analysis or graph.
Simple Example
a =int( ‘10’)
b =int(‘20’)
c = a+b
Print(c)
Output
30
List
A list in Python is a versatile and mutable data structure used to store an
ordered sequence of items. These items can be of different data types,
including numbers, strings, and even other lists (nested lists). Lists are
defined by enclosing comma-separated values within square brackets [].
Example
Input
X = [14,24,28]
X[2]=30
Print(X)
Output
[14,24,30]
Output:
Changing an Item
fruits[1] = "mango"
print(fruits)
Output
['apple', 'mango', 'orange']
Adding Items
fruits.append("grapes")
print(fruits)
Output
['apple', 'mango', 'orange', 'grapes']
Removing Items
fruits.remove("orange")
print(fruits)
Output
['apple', 'mango', 'grapes']
1. Create a List
Create a list named colors with these items: "red", "blue", "green”
2. Access an Item
3.Change a Value
4. Add an Item
5.Remove an Item
Solution:
Color_list[2] ="yellow"
print(Color_list)
Color_list.append("purple")
print(Color_list)
For loop:
A for loop in Python is used to repeat a block of code for each item in a sequence
like a list, string, tuple, dictionary, or range.
Syntax:
Use range() when you want to repeat something a specific number of times or when
you need to loop through a sequence of numbers.
for i in range(5):
print("Welcome!")
● Data entry checks: Loop through rows 1 to 100 and validate entries.
A nested for loop means one for loop inside another for loop. It is used when we
want to repeat a task inside another repeating task.
Output
Seat 1-1
Seat 1-2
Seat 1-3
Seat 1-4
Seat 2-1
Seat 2-2
Seat 2-3
Seat 2-4
Seat 3-1
Seat 3-2
Seat 3-3
Seat 3-4
[Program finished]
A while loop is used when you want to repeat a task many times as long as a
condition is true.
(Syntax):
while condition:
# do something
i=1
while i <= 5:
print(i)
i=i+1
Output:
1
2
3
4
5
water_in_bottle = 5
while water_in_bottle > 0:
print("Take a sip")
water_in_bottle = water_in_bottle - 1
Output:
Take a sip
Take a sip
Take a sip
Take a sip
Take a sip
The bottle is empty
● You must change the value inside the loop (or it will run forever!)
● It’s good for tasks where you don’t know how many times the loop should run
List:
example:
A= [3,4,8,sara]
B=[“ hello I hate everyone”, “i also love everything”]
A.insert(0,1)
A.append(6)
A pop()
A extend(B)
Print (a)
Tuple:
Syntax:
● Allows duplicate
● Any type of data can be stored
● We cannot modify the tuple item. We cannot add or remove
● It use the () parentheses while list use [] square brackets.
● Ex. a=(1,2,3,4)
● If we want to do add or remove elements from the tuple we can convert that
tuple into list and we can modify elements easily.
Example
a=(1,2,3,4,5)
b=list(a)
print(a)
print (b)
Immutable: You cannot change, add, or remove items after the tuple is created.
Allow duplicates: Tuples can contain duplicate values.
1. Creating a tuple:
2. Accessing items:
5. Tuple unpacking:
Set {}:
my_set = {1, 2, 3, 4, 4, 5}
print(my_set)
Output:
a = {1, 2, 3}
b = {3, 4, 5}
Examples
Output:
Output:
---
Output:
{'apple', 'mango'}
Note: If you try fruits.remove("orange"), it will give an error if "orange" is not in the
set.
---
Output (random):
Removed: apple
Remaining: {'banana', 'mango'}
Example
1. Dictionary na enna?
Structure:
my_dict = {
"name": "Anbu",
"age": 25,
"city": "Madurai"
}
Example
employee = {
"emp_id": 1001,
"name": "Karthik",
"role": "Data Analyst",
"salary": 50000
}
# Delete a key
del employee["role"]
employee.update({
"salary": 60000,
"city": "Chennai"
})
This will:
Python functions
def greet():
print("Hello! Have a nice day!")
def = keyword to define a function
greet()
Output:
Hello! Have a nice day!
Simple example.
def add():
a= int(input(“enter a:”))
b= int(input(“enter b:”))
print(a+b)
add()
Output
enter a:10
enter b:20
30
[Program finished]
Definition:
● The return statement in Python is used inside a function to send back the
result to the place where the function was called.
● It also stops the function from running any more lines after the return(After
return statement anything within the function will not work)
Example:
result = add(2, 3)
print(result) # Output: 5
Here, the function add() returns the sum of a and b, and that result is stored in the
variable result.
Example
def add(a,b):
return a+b
a=int(input("enter a number:"))
b=int(input("enter a number:"))
c=int(input("enter a number:"))
sum=add(a,b)
total= sum*c
print(total)
What is OOPs?
● Objects are like real-life things – they have properties (data) and actions
(methods/functions).
Class:
It tells what properties (variables) and actions (functions) something will have.
Object:
Definition:
● Widely used in real-world applications like websites, apps, games, and data
processing.
Example
class Student:
def display_info(self):
print("Name: ",self.name)
print("Age:",self.age)
student1.display_info()
student2.display_info()
“Inheritance means one class can use the variables and functions of another class.
The class that gives its features is called the parent class, and the class that
receives them is called the child class.”
Example:
Single inheritance
# Parent class
class Animal:
def __init__(self):
self.name = "Animal"
def eat(self):
print(self.name + " is eating.")
# Child class
class Dog(Animal):
def bark(self):
print("Dog is barking.")
Multiple inheritance means one class object can access other class, In this pulla
class can able to access the other two amma appa class with the object deena
class appa():
def phone(self):
print("appa oda phone")
class amma():
def sweet(self):
print("amma oda sweet")
class pulla(appa,amma):
def laptop(self):
print("paiyan oda laptop")
deena=pulla()
deena.laptop()
deena.phone()
deena.sweet()
Output
[Program finished]
Multilevel inheritance means a class is inheriting from a class that already inherited
from another class. It creates a chain of inheritance.
Example
class ayya():
def chcolate(self):
print("ayya's chcolate")
class amma(ayya):
def curdrice(self):
print("amma's curd rice")
class ponu(amma):
def pizza(self):
print("ponu oda pizza")
sara=ponu()
sara.pizza()
sara.curdrice()
mom=amma()
mom.chcolate()
sara.chcolate()
Output
[Program finished]
Definition: Hierarchical inheritance means one parent class has many child classes.
Oru common base class irukkum. Athula irundhu multiple classes inherit pannum.
Hybrid inheritance
Hybrid inheritance means using more than one type of inheritance (like single,
multiple, or multilevel) together in the same program.
Example:
When one class inherits from two classes, and those two classes inherit from a
common base class, it forms a hybrid pattern.
Polymorphism na enna?
Polymorphism na oru same name vaachu multiple types of work panna mudiyum.
Poly = many, Morph = forms
So, same function or method name, but it acts differently based on the object or
class.
Polymorphism in Python means the ability of different classes to respond to the
same method name in their own way. It allows the same function or method to work
with different types of objects.
Example-style definition:
> Polymorphism allows us to write one function (like make_payment()) that can
work with different objects (like CardPayment, WalletPayment, etc.), as long as they
all have a method with the same name (like pay()).
Example
class vehicle():
def start(self):
print("vehicle started")
class car(vehicle):
def start(self):
print("car started")
c1=car()
c1.start()
car started
[Program finished]
Python Example:
class Dog:
def sound(self):
return "Bark"
class Cat:
def sound(self):
return "Meow"
# Create objects
dog = Dog()
cat = Cat()
# Call function
make_sound(dog) # Output: Bark
make_sound(cat) # Output: Meow
Explanation:
Rendu class la sound() nu same method name iruku, aana different output.
Encapsulation na enna?
Simple-a solla:
Encapsulation is the process of hiding the internal data of a class and only allowing
access to it through methods (functions).
> Encapsulation means wrapping data and functions together in a class and hiding
the data from direct access.
1. Public:
● No restriction.
Example:
class Sample:
def __init__(self):
self.name = "Arun" # public
obj = Sample()
print(obj.name) # Direct-a access pannalam
2. Private:
Example:
class Sample:
def __init__(self):
self.__age = 20 # private
def show_age(self):
print(self.__age)
obj = Sample()
obj.show_age() # OK – method use pannalam
print(obj.__age) # Error – private ah direct-a access panna mudiyadhu
3. Protected:
● Protected na classum athoda child class (subclass) kulla use panna mudiyum.
class Sample:
def __init__(self):
self._city = "Chennai" # protected
class SubSample(Sample):
def print_city(self):
print(self._city) # OK – subclass kulla access panna mudiyum
obj = SubSample()
obj.print_city()
print(obj._city) # This works, but not recommended (protected)
Exception handling
Python-la program run panna, edhavadhu mistake irundha (like divide by zero, file
not found, etc.), appo program stop agidum. Ithu error or exception nu solvom.
Exception Handling na, error varum pothu program stop aagala, instead namma
handle panna mudiyum using:
● try
● except
● else (optional)
● finally (optional)
Example
try:
a = input()
b = input()
print(a / b)
except Exception as e:
print("wrong", e)
You use except Exception as e: when you don’t know what kind of error might
happen, or if you want to catch all errors in one place.
Use Exception as e when:
try:
a=5
b=0
print(a / b)
except ZeroDivisionError:
print("You can't divide by zero.")
Output:
You can't divide by zero.
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("Can't divide by zero.")
except ValueError:
print("Please enter only numbers.")
try:
x = 10
y=2
result = x / y
except ZeroDivisionError:
print("Division error.")
else:
print("Division is:", result)
finally:
print("This block runs always.")
Output:
Common Exceptions:
File Handling means reading from and writing to files in your computer using
Python.
● We can do these:
● Create a file
‘w’ Write
Mode(erase open("file.txt","w")
old data)
f = open("myfile.txt", "r")
data = f.read()
print(data)
f.close()
Output:
f = open("myfile.txt", "r")
print(f.read())
f.close()
Output:
Code:
Explanation:
with open(...) as f: is used to open a file safely (auto-closes the file).
Example
Apple
Banana
Orange
Line 1: Apple
Line 2: Banana
Output:
Output
Apple
Banana
Orange
When we open a file, Python keeps a cursor (like a pointer) to track where to read or
write next. We can move or check this using:
tell() — Shows current position of the index
When working with files in Python, you must open them in a specific mode to tell
Python what action you want to perform.