First program
print("Anshum")
check it out:
a = True
print(a)
name = input("What is your name? ")
colour = input("What is your fav colour? ")
print(name + " likes " + colour)
birth_year = input("What is birth year? ")
print(type(birth_year))
age = 2024 - int(birth_year)
print(type(age))
print(age)
email = '''
Hi, I am Anshum.
Thanks and regards,
Anshum
'''
print(email)
name = 'Anshum Achyut Bansode'
print(len(name))
import math
print(math.pow(2,3))
i = 1
while i<=5:
print("*" * i)
i = i + 1
name = ['Anshum','Achyut', 'Bansode']
print(name)
#Matrix declaration
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a[1][1])
numbers = [1, 2, 3, 4]
x, y, z, w = numbers
print(z)
New way of indexing in python:
a = 'Anshum Achyut Bansode'
print(a[-2])
print(a[0:5])
print(a[1:-1])
a = 'Anshum Achyut Bansode'
print(a[-2])
print(a[0:5])
print(a[1:-1])
formatted string:
first = 'Anshum'
last = 'Bansode'
a = f"{first}'s surname is {last}"
print(a)
else if === elif
grade = float(input("Enter the student's grade (0-100): "))
attendance = float(input("Enter the student's attendance percentage (0-100): "))
if grade < 0 or attendance < 0 or not (0 <= grade <= 100 and 0 <= attendance <= 100):
print("Invalid input provided.")
elif grade >= 50 and attendance >= 75:
print("The student passes the course.")
elif grade < 50 or attendance < 75:
print("The student fails the course.")
Use of for loop
for i in "Anshum Achyut Bansode":
print(i, end = '')
print()
for i in ["Anshum", "Achyut", "Bansode"]:
print(i)
5 to 9
for i in range(5, 10):
print(i, end=" ")
Array of 5, 6, 7, 8, 9
print()
for i in range(1, 20, 3):
print(i)
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in a:
print(row)
for row in a:
for i in row:
print(i)
Different methods used for string:
name = 'Anshum Achyut Bansode'
print(name.upper())
print(name.lower())
print(name.find('A'))
#these are methods used for string only (not the integer array)
print(name.replace('Anshum', 'Anuja'))
print(name.split('ns'))
#This will return String array splitting it by passed string
print(name.split(" "))
print(name)
Different methods used for array
number = [10, 20, 30, 40, 50]
number.append(200)
number.insert(2, 500)
number.remove(10)
print(number.index(20))
print(number)
number.sort()
number.reverse()
print(number)
#Append element to the last of the array
#Pass index and element
#Return index of given element
#Sort array in ascending order
Tuple:
It is just like array; but here we can not modify or change any value of any index.
Declared in parenthesis instead of curly brackets.
numbers = (1, 2, 3, 4)
Dictionary:
Student = {
"name": "Anshum",
"Roll_no": 19,
"Marks": 100
}
print(f'Student {Student["name"]} with roll number {Student["Roll_no"]} has scored {Student['Marks']} marks')
If you try to print a key which is not present in the dictionary, it will generate an error. We can use dictionary.get()
to avoid error. It will not generate an error, (it will return ‘None’), Try running below program.
Student = {
"name": "Anshum",
"Roll_no": 19,
}
Student["Marks"] = 100
print(f'Name: {Student.get("name")}')
print(f'Roll no: {Student.get("Roll_no")}')
print(f'Marks: {Student.get("Marks")}')
print(f'Birth date: {Student.get("BirthDate")}')
print(f'Birth date: {Student.get("BirthDate", "9 Feb 2007")}')
print(Student)
#BirthDate will not be added to dictionary; but Marks will be added
Functions:
def Welcome(first_name, last_name):
print(f'Hi! {first_name} {last_name}')
print("How are You?")
name = input("Enter your name with surname> ")
first_name = name.split(' ')[0]
last_name = name.split(' ')[1]
Welcome(first_name, last_name)
In python, We can pass arguments in random ways:
def Welcome(first_name, last_name):
print(f'Hi! {first_name} {last_name}')
print("How are You?")
name = input("Enter your name with surname> ")
first_name = name.split(' ')[0]
last_name = name.split(' ')[1]
Welcome(last_name = last_name, first_name = first_name)
Exceptions:
age = int(input("Enter your age: "))
print(f'you are {age} years old')
In the above code, if user enter characters instead of integer, then it will generate an ValueError.
try:
age = int(input("Enter your age: "))
print(f'you are {age} years old')
except ValueError:
print('Invalid input')
Class
Object: Object is an instance of a class
name = "Anshum" # Creates a string object
numbers = [1, 2, 3] # Creates a list object
age = 25 # Creates an integer object
Object can have attribute(storing data related to object (eg name, age, model)) and method(perform action using object’s data).
Attribute: Stores data for each object. There are two types of attributes: instance attribute, class attribute
Instance attribute: Usually defined inside __init__ method
class Car:
def __init__(self, make, model):
self.make = make # Instance attribute
self.model = model # Instance attribute
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Accord")
print(car1.make)
print(car2.make)
here, whenever we declare object of ‘car’ class, __init__ method will execute every time to store passed values of ‘make’ and
‘model’. car1 and car2 are objects while .make and .model are instance attribute
Class attribute: They are declared directly inside class body. Each object of same class has same value of class attribute.
class Dog:
species = "Animal"
# Class attribute
dog1 = Dog()
dog2 = Dog()
print(dog1.species)
print(dog2.species)
What is __init__?
•
•
•
__init__ is called a constructor (a constructor is a special method that is automatically called when an object is created).
It is used to initialize the object with default values.
self.name = name assigns the value passed as the name parameter to an attribute called name that belongs to the object.
Methods: perform action using object’s data. If a function is inside a class and operates on instances or the
class itself, it is called a method. If a function is outside of a class, it is just a normal function, not a method.
Function is not accessed by . operator as a method. Three types of methods: instance, class and static methods.
Instance method: e.g. .upper() is built-in method (not a function) in python that capitalize all letters.
class Dog:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
def bark(self): # Instance method
print(f"{self.name} says woof!")
dog1 = Dog("Tommy", 5)
dog1.bark() # Calling an instance method
Class method: Operates on class itself. Defined using @classmethod. First parameter is cls (representing class)
class Dog:
number_of_legs = 4 # Class attribute
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def describe_legs(cls): # Class method
print(f"A dog has {cls.number_of_legs} legs.")
Dog1 = Dog('Tommy', 5)
Dog1.describe_legs()
It allows access to class-level attributes (like number_of_legs) and methods. Not Instance level attributes (like self.name) and
method.
If you want to access instance level attribute pass dog1 as argument inside class method as shown (We can do it with static
method also):
class Dog:
number_of_legs = 4 # Class attribute
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def describe_legs(cls, dog_instance): # Pass the instance as a parameter
print(f"{dog_instance.name} is a dog and has {cls.number_of_legs} legs.")
dog1 = Dog('Tommy', 5)
dog1.describe_legs(dog1)
Static method: Doesn’t take self or cls as first parameter. Defined using @staticmethod.
class Dog:
@staticmethod
def make_sound(): # Static method
print("Woof!")
dog1 = Dog()
dog1.make_sound()
Try this:
class Example:
def __init__(self, name, age=None):
self.name = name
self.age = age # Will be None if not provided
obj1 = Example("Alice")
obj2 = Example("Bob", 25)
print(f'Name = {obj1.name}, age = {obj1.age}')
print(f'Name = {obj2.name}, age = {obj2.age}')
One can create an attribute for an object outside class body if it does not exist class body; because python is
dynamic.
class Point:
def move(self):
print("move")
point1 = Point()
point1.move()
point1.x = 12
print(point1.x)
we can modify predefined attributes.
Inheritance:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
def run(self):
print(f'{self.name} is running.')
class Cat(Animal):
pass
#we simply write pass if there is blank class inherited from another class
class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")
#Program run this speak method instead of Animal speak
#It simply means all is written in Animal is written in Dog
animal = Animal("abcd")
dog = Dog("Chintu")
cat = Cat("Tom")
animal.speak()
dog.speak()
dog.run()
cat.speak()
Modules (file):
File.py file
Main.py file
import File
from File import add
def add(x, y):
return x+y;
a = int(input())
b = int(input())
print(add(a, b))
print(File.multiply(a, b))
def multiply(x, y):
return x*y
Package (folder):
They are directories(folder) containing many modules(file)
Creating a package: Create directory, create a python file(.py) with name “__init__” in that folder. Done!!
Or we can simply click on new >> python package >> and create.
Main.py file
MathCalculations >> Calculation.py
import MathCalculations.Calculation
from MathCalculations.Calculation import Multiply
def Add(x, y):
return x+y
print(MathCalculations.Calculation.Add(2, 4))
print(Multiply(2, 4))
def Multiply(x, y):
return x*y
We can also use another method to avoid writing package name while accessing it again and again:
import MathCalculations.Calculation as anshum
from MathCalculations.Calculation import Multiply
print(anshum.Add(2, 4))
print(Multiply(2, 4))
Built-in modules: There are so many modules already built in python (one of them are math, random, etc)
There are many functions in random module to generate a random value.
import random
random.random()
random.choice(list)
random.randint(num1, num2)
#Returns a random value between 0 and 1
#Returns random element from the list
#Returns Random integer between num1 and num2
Q.1) write a program to print values on two dice when rolled (program run).
Solution: import random
print(f'({random.randint(1, 6)},{random.randint(1, 6)})')