mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat:
print(r)
m=len(mat)
n=len(mat[0])
for i in range(0,m):
print(“”)
for j in range(0,n):
print(mat[i][j],end=””)
================================================
matrix1=[]
matrix2=[]
# input matrix 1
rows = int(input(“Enter the number of rows for matrix 1:”))
columns = int(input(“Enter the number of columns for matrix 1:”))
print(“Enter elements of matrix 1:”)
for i in range(rows):
row=[]
for j in range(columns):
row.append(int(input(f”Enter element({i+1},{j+1}):”)))
matrix1.append(row)
#input matrix 2
rows = int(input(“Enter the number of rows for matrix 2:”))
columns = int(input(“Enter the number of columns for matrix 2:”))
print(“Enter elements of matrix 2:”)
for i in range(rows):
row=[]
for j in range(columns):
row.append(int(input(f”Enter element({i+1},{j+1}):”)))
matrix2.append(row)
#add matrices
result=[]
for i in range(len(matrix1)):
row=[]
for j in range(len(matrix1[0])):
row.append(matrix1[i][j]+matrix2[i][j])
result.append(row)
#display result
print(“Result of matrix addition:”)
for row in result:
print(row)
=============================================================================
#Program to multiply two matricess using nested loops
#take input for first matrix
m1_rows=int(input(“Enter the number of rows for matrix 1:”))
m1_cols=int(input(“Enter the number of columns for matrix 1:”))
print(“Enter the elements of first matrix:”)
matrix1=[]
for i in range(m1_rows):
a=[]
for j in range(m1_cols):
a.append(int(input()))
matrix1.append(a)
#take input for second matrix
m2_rows=int(input(“Enter the number of rows for matrix 2:”))
m2_cols=int(input(“Enter the number of columns for matrix 2:”))
if m1_cols!=m2_rows:
print(“The number of columns of first matrix should be equal to the number of rows of second matrix.”)
else:
print(“Enter the elements of second matrix:”)
matrix2=[]
for i in range(m2_rows):
b=[]
for j in range(m2_cols):
b.append(int(input()))
matrix2.append(b)
#initializing the result matrix
result=[[0 for j in range(m2_cols)] for i in range(m1_rows)]
#multiplying matrices using nested loops
for i in range(m1_rows):
for j in range(m2_rows):
for k in range(m2_rows):
result[i][j]+=matrix1[i][k]*matrix2[k][j]
#printing the result
print(“The result of matrix multiplication is:”)
for i in range(m1_rows):
for j in range(m2_cols):
print(result[i][j],end=”\t”)
print()
=============================================================================
Python Program to find factorial of given number
# _____________Using Recursion______________
#Method to find factorial of a given number
def factorialUsingRecursion(n):
if(n==0):
return 1;
return n* factorialUsingRecursion(n-1);
#________Using Iteration__________
#Method to find factorial of a given number
def factorialUsingIteration(n):
res=1;
for i in range(2, n+!):
res*=i;
return res;
num=5;
print(“Factorial of”, num, “Using Recursion is:”,factorialUsingRecursion(5));
print(“Factorial of”, num,”USing Iteration is:”, factorialUsingIteratio(5));
==============================================================================
#Enter number of terms needed
a=int(input(“Enter the terms:”))
f=0 #first element of series
s=1#second element of series
if a<=0:
print(“The requested series is “,f)
else:
print(f,s,end=””)
for x in range(2,a):
next=f+s
print(next,end=””)
f=s
s=next
==============================================================================
class Student:
def__init__(self, n=”,b=”):
self.name=n
self.branch=b
def display(self):
print(“Name:”, self.name)
print(“Branch:”, self.branch)
print(“This is non parametrized constructor”)
s1=Student()# Constructor-non parameterized
s1.display()
print(“__________________”)
print(“This is parametrized constructor”)
s2=Student(“Suresh”,”CSE”)# Constructor – parameterized
s2.display()
print(“__________________”)
=============================================================================
class Person:
def__init__(self, name, age):
self.name=name#instance variable
self.age=age#instance variable
def print_info(self):
print(f”Name:{self.name}, Age:{self.age}”)
#create persons
person1=Person(“Suresh”,33)
person2=Person(“Venkat”,29)
#print information of all persons
person1.print_info()
person2.print_info()
#modify information of one person
person1.name=”Raju”
person1.age=35
#print information of all persons after modification
person1.print_info()
person2.print_info()
==============================================================================
class Car:
wheels = 4#class variable
def__init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
#create cars
car1=Car(“Toyota”,”Corolla”, 2010)
car2=Car(“Honds”, “Civic”, 2015)
#print number of wheels for all cars
print(f”{car1.make}{car1.model}has{Car.wheels}wheels”)
print(f”{car2.make}{car2.model}has{Car.wheels}wheels”)
#modify number of wheels for all cars
Car.wheels=3
#print number of wheels for all cars after modification
print(f”{car1.make}{car1.model}has{Car.wheels}wheels”)
print(f”{car2.make}{car2.model}has{Car.wheels}wheels”)
==============================================================================
#Python program that demonstrates Single Inheritance
class person:
def __init__(self, name, age):
self.name=name
self.age=age
def display(self):
print(f”I am {self.name} and I am {self.age}years old”)
class Employee(person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary=salary
def display(self):
super().display()
print(f”My salary is {self.salary}”)
e=Employee(“Suresh”, 33, 55000)
e.display()
2.
#Python program that demonstrates Multiple Inheritance
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print(f”I am {self.name} and I am {self.age}year old”)
class Student:
def __init__(self, roll_no, marks):
self.roll_no = roll_no
self.marks=marks
def display(self):
print(f”My roll number is {self.roll_no}and my marks are {self.marks}”)
class Employee(Person, Student):
def __init__(self, name, age, roll_no, marks, salary):
Person.__init__(self,name, age)
Student.__init__(self, roll_no, marks)
self.salary=salary
def display(self):
super().display()
Student.display(self)
print(f”My salary is {self.salary}”)
e=Employee(“Venkat”,29, 101, 90, 55000)
e.display()
3.
#Python Program that demonstrates Multilevel Inheritance
#Define base class as ‘Student’
class Student:
def getStudent(self):
self.name=input(“Enter Name:”)
self.age=input(“Enter Age:”)
self.gender=input(“Enter Gender:”)
# Define a class as ‘Test’ and inherit base class ‘Student’
class Test(Student):
def getMarks(self):
self.stuYearSem=input(“Enter your Year and Semester:”)
print(“Enter the marks of the respective subjects”)
self.sub1=int(input(“IME:”))
self.sub2=int(input(“Java:”))
self.sub3=int(input(“Python:”))
self.sub4=int(input(“Android Programming:”))
self.sub5=int(input(“CNS:”))
#Define a class as ‘Marks’ and Inherit derived class ‘Test’
class Marks(Test):
#Method
def display(self):
print(“\n\nName:”,self.name)
print(“Age:”,self.age)
print(“Gender:”,self.gender)
print(“Study in:”,self.stuYearSem)
print(“Total Marks:”, self.sub1+self.sub2+self.sub3+self.sub4+self.sub5)
print(“Average Marks:”,(self.sub1+self.sub2+self.sub3+self.sub4+self.sub5)/5)
m1=Marks()
#Callbase class method ‘getStudent()’
m1.getStudent()
#Call first derived class method ‘getMarks()’
m1.getMarks()
#Call second derived class method ‘display()’
m1.display()
4.
#Python Program that demonstrates Hierarchical Inheritance
class First:
def __init__(self):
self.x=20
self.y=10
class Second(First):
def findsum(self):
self.z = self.x + self.y
print(“Sum is:”, self.z)
class Third(First):
def findsub(self):
self.z = self.x – self.y
print(“Subtraction is:”,self.z)
obj1=Second()
obj1.findsum()
obj2=Third()
obj2.findsub()
5.
#Python program that demonstrates Hybrid Inheritance
class Animal:
def __init__(self, name):
self.name=name
def eat(self):
print(f”{self.name} is eating”)
class Mammal(Animal):
def __init__(self, name):
super().__init__(name)
def walk(self):
print(f”{self.name} is walking”)
class Bird(Animal):
def __init__(self,name):
super().__init__(name)
def fly(self):
print(f”{self.name} is flying”)
class Bat(Mammal, Bird):
def __init__(self,name):
super().__init__(name)
b=Bat(“Batty”)
b.eat()
b.walk()
b.fly()
6.
#Another Example that demonstrates Hybrid Inheritance
class A:
def method_A(self):
print(“This is from class A.”)
class B(A):
def method_B(self):
print(“This is from class B.”)
class C(A):
def method_C(self):
print(“This is from class C.”)
class D(B,C):
def method_D(self):
print(“This is from class D.”)
# create an object of class D
d=D()
# call methods from class A, B, C, and D
d.method_A()
d.method_B()
d.method_C()
d.method_D()
==============================================================================
#Python program that demonstrates Multiple Inheritance
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print(f”I am {self.name} and I am {self.age}year old”)
class Student:
def __init__(self, roll_no, marks):
self.roll_no = roll_no
self.marks=marks
def display(self):
print(f”My roll number is {self.roll_no}and my marks are {self.marks}”)
class Employee(Person, Student):
def __init__(self, name, age, roll_no, marks, salary):
Person.__init__(self,name, age)
Student.__init__(self, roll_no, marks)
self.salary=salary
def display(self):
super().display()
Student.display(self)
print(f”My salary is {self.salary}”)
e=Employee(“Venkat”,29, 101, 90, 55000)
e.display()
==============================================================================
#Python Program that demonstrates Multilevel Inheritance
#Define base class as ‘Student’
class Student:
def getStudent(self):
self.name=input(“Enter Name:”)
self.age=input(“Enter Age:”)
self.gender=input(“Enter Gender:”)
# Define a class as ‘Test’ and inherit base class ‘Student’
class Test(Student):
def getMarks(self):
self.stuYearSem=input(“Enter your Year and Semester:”)
print(“Enter the marks of the respective subjects”)
self.sub1=int(input(“IME:”))
self.sub2=int(input(“Java:”))
self.sub3=int(input(“Python:”))
self.sub4=int(input(“Android Programming:”))
self.sub5=int(input(“CNS:”))
#Define a class as ‘Marks’ and Inherit derived class ‘Test’
class Marks(Test):
#Method
def display(self):
print(“\n\nName:”,self.name)
print(“Age:”,self.age)
print(“Gender:”,self.gender)
print(“Study in:”,self.stuYearSem)
print(“Total Marks:”, self.sub1+self.sub2+self.sub3+self.sub4+self.sub5)
print(“Average Marks:”,(self.sub1+self.sub2+self.sub3+self.sub4+self.sub5)/5)
m1=Marks()
#Callbase class method ‘getStudent()’
m1.getStudent()
#Call first derived class method ‘getMarks()’
m1.getMarks()
#Call second derived class method ‘display()’
m1.display()
============================================================================
#Python Program that demonstrates Hierarchical Inheritance
class First:
def __init__(self):
self.x=20
self.y=10
class Second(First):
def findsum(self):
self.z = self.x + self.y
print(“Sum is:”, self.z)
class Third(First):
def findsub(self):
self.z = self.x – self.y
print(“Subtraction is:”,self.z)
obj1=Second()
obj1.findsum()
obj2=Third()
obj2.findsub()
=============================================================================
#Python program that demonstrates Hybrid Inheritance
class Animal:
def __init__(self, name):
self.name=name
def eat(self):
print(f”{self.name} is eating”)
class Mammal(Animal):
def __init__(self, name):
super().__init__(name)
def walk(self):
print(f”{self.name} is walking”)
class Bird(Animal):
def __init__(self,name):
super().__init__(name)
def fly(self):
print(f”{self.name} is flying”)
class Bat(Mammal, Bird):
def __init__(self,name):
super().__init__(name)
b=Bat(“Batty”)
b.eat()
b.walk()
b.fly()
==============================================================================
#Another Example that demonstrates Hybrid Inheritance
class A:
def method_A(self):
print(“This is from class A.”)
class B(A):
def method_B(self):
print(“This is from class B.”)
class C(A):
def method_C(self):
print(“This is from class C.”)
class D(B,C):
def method_D(self):
print(“This is from class D.”)
# create an object of class D
d=D()
# call methods from class A, B, C, and D
d.method_A()
d.method_B()
d.method_C()
d.method_D()
==============================================================================
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, grade):
# Call the base class (Animal) constructor
super().__init__(name, age)
self.grade = grade
# Creating an instance of Dog
student = Student(“Shiva”, “30”, “A”)
print(student.name)
print(student.age)
print(student.grade)
==============================================================================
# super() method to call base class method example
class Animal:
def make_sound(self):
print(“Generic animal sound”)
class Dog(Animal):
def make_sound(self):
super().make_sound() #call superclass method
print(“Bark!”)
dog = Dog()
dog.make_sound()
==============================================================================
#super function with multilevel inheritance
class A:
def __init__(self):
print(‘Initializing: class A’)
def sub_method(self, b):
print(‘Printing from class A:’, b)
class B(A):
def __init__(self):
print(‘Initializing: class B’)
super().__init__()
def sub_method(self, b):
print(‘Printing from class B:’, b)
super().sub_method(b+1)
class C(B):
def __init__(self):
print(‘Initializing: class C’)
super().__init__()
def sub_method(self, b):
print(‘Printing from class C:’, b)
super().sub_method(b+1)
c=C()
c.sub_method(1)
==============================================================================
# Write a python program to access base class constructor and method in the sub class using super()
function
class Square:
def __init__(self, x=0):
self.x=x
def area(self):
print(“Area of square:”, self.x*self.x)
class Rectangle(Square):
def __init__(self, x=0, y=0):
super().__init__(x)
self.y=y
def area(self):
super().area()
print(“Area of Rectangle:”, self.x*self.y)
r=Rectangle(5,16)
r.area()
==============================================================================
a=[1,2,3]
b=[1,2,3]
c=a
print(“a’s memory locatrion is:”,id(a))
print(“b’s memory location is:”, id(b))
print(“c’s memory location is:”, id(c))
print(a is b)# False – a and b refer to different memory locations
print(a is not b) # True – a and b are not the same object
print(a is c) # True – a and c refer to the same memory location
==============================================================================
x=10
y=10
print(“x’s memory location is :”, id(x))
print(“y’s memory location is :”, id(y))
print(x is y)# True – x and y refer to the same memory location
print(x is not y) # False – x and y are the same object
==============================================================================
import math
number = int(input(“Enter number:”))
square_root = math.sqrt(number)
print(“The square root of”, number, “is”, square_root)
==============================================================================
import math
def is_prime(number):
if number < 2: # check if number is less than 2
return False
elif number ==2: # check if number is equal to 2
return True
else:
# use the sqrt() function to optimize the loop
for i in range (2, int(math.sqrt(numbr))+1):
if number % i==0: #check if number is divisible by i
return False
return True
n= int(input(“Enter number:”))
if is_prime(n):
print(n,”is prime number”)
else:
print(n,”is not prime number”)
=============================================================================
import math
def is_prime(number):
if number<2:
return False
elif number ==2:
return True
else:
# use the sqrt() function to optimize the loop
for i in range(2, int(math.sqrt(number))+1:
if number % i ==0:
return False
return True
n = int(input(“Enter number:”))
if is_prime(n):
print(n,” is prime number”)
else:
print(n,” is not prime number”)
==============================================================================
import math
def is_prime(number):
if number < 2: # check if number is less than 2
return False
elif number ==2: # check if number is equal to 2
return True
else:
# use the sqrt() function to optimize the loop
for i in range (2, int(math.sqrt(numbr))+1):
if number % i==0: #check if number is divisible by i
return False
return True
n= int(input(“Enter number:”))
if is_prime(n):
print(n,” is prime number”)
else:
print(n,” is not prime number”)
==============================================================================
#COS FUNCTION
import math
# define an angle in radians
angle = math.pi/4 #45 degrees
# claculate the cosine of the angle using the cos() function
cosine=math.cos(angle)
print(“The cosine of”, angle, “is”, cosine)
==============================================================================
# Python program showing graphical representation of cos() function
import math
import numpy as np
import matplotlib.pyplot as plt
in_array = np.linspace(-(3*np.pi), 3*np.pi,50)
out_array=[]
for i in range(len(in_array)):
out_array.appennd(math.cos(in_array[i]))
i+=1
print(“in_array:”, in_array)
print(“\nout_array :”, out_array)
plt.plot(“in_array, out_array, color = ‘red’, marker = “o”)
plt.title(“math.cos()”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
plt.show()
==============================================================================
# Python program showing graphical representation of cos() function
import math
import numpy as np
import matplotlib.pyplot as plt
in_array = np.linspace(-(3 * np.pi), 3 * np.pi, 50)
out_array = []
for i in range(len(in_array)):
out_array.append(math.cos(in_array[i]))
i += 1
print(“in_array : “, in_array)
print(“\nout_array : “, out_array)
plt.plot(in_array, out_array, color = ‘red’, marker = “o”)
plt.title(“math.cos()”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
plt.show()
==============================================================================
import math
# define an angle in radians
angle = math.pi/6 # 30 degrees
# calculate the sine of the angle using the sin function
sine = math.sin(angle)
print(“The sine of”, angle, “is”, sine)
===============================================================================
import math
# define an angle in radians
angle = math.pi/6 # 30 degrees
# calculate the sine of the angle using the sin() function
sine = math.sin(angle)
print(“The sine of”, angle, “is”, sine)
==============================================================================
import math
import matplotlib.pyplot as plt
import numpy as np
in_array = np.arange(0,10,0.1);
out_array = []
for i in range(len(in_array)):
out_array.append(math.sin(in_array[i]))
i+=1
print(“in_array : “, in_array)
print(“\nout_array : “, out_array)
# red for numpy.sin()
plt.plot(in_array, out_array, color = ‘red’, marker = “o”)
plt.title(“math.sin()”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
plt.show()
===============================================================================
import math
import matplotlib.pyplot as plt
import numpy as np
in_array = np.arange(0, 10, 0.1);
out_array = []
for i in range(len(in_array)):
out_array.append(math.sin(in_array[i]))
i += 1
print(“in_array:”, in_array)
print(“\nout_array : “, out_array)
# red for numpy.sin()
plt.plot(in_array, out_array, color = ‘red’, marker = “o”)
plt.title(“math.sin()”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
plt.show()
===============================================================================
import math
# using the pow() function to calculate 2 to the power of 3
result = math.pow(2, 3)
# print the result
print(result) #8
=============================================================================
import math
# convert an angle of pi/4 radians to degrees
angle_in_radians = math.pi/4
angle_in_degrees = math.degrees(angle_in_radians)
# print the result
print(angle_in_radians, “radians is equal to”, angle_in_degrees, “degrees.”)
==============================================================================
import math
# prints the fabs using fabs() mathod
print(“math.fabs(-13.1) : “, math.fabs(-13.1))
print(“math.fabs(101.96) : “, math.fabs(101.96))
===============================================================================
import datetime
# get the current data and time
current_datetime = datetime.datetime.now()
# print the current date and time
print(“Current date and time:”, current_datetime)
==============================================================================
import datetime
d=datetime.date(2022, 2, 17)
print(d)
==============================================================================
import datetime
d = datetime.date(2022, 2, 17)
print(d)
===============================================================================
from datetime import date
today=date.today()
print(“Current date=”, today)
==============================================================================
from datetime import date
a = date(2019, 4, 13)
print(a)
==============================================================================
from datetime import date
timestamp = date.fromtimestamp(1326244364)
print(“Date =”, timestamp)
==============================================================================
from datetime import date
timestamp=date.fromtimestamp(1326244364)
print(“Date=”, timestamp)
==============================================================================
import datetime
date_object=datetime.date.today() # create a date object for todays date
# print the date object
print(“Date object:”, date_object)
# print the year, month, day, and weekday from the date object
print(“Year:”, date_object.year)
print(“Month:”, date_object.month)
print(“Day:”, date_object.day)
print(“Weekday:”, date_object.weekday()) # Monday is 0 and Sunday is 6
===============================================================================
import datetime
date_object = datetime.date.today() # create a date object for todays date
# print the date object
print(“Date object:”, date_object)
# print the year, month, day, and weekday from the date object
print(“Year:”, date_object.year)
print(“Month:”, date_object.month)
print(“Day:”, date_object.day)
print(“Weekday:”, date_object.weekday()) # Monday is 0 and Sunday is 6
=================================================================================
import datetime
# create a time object for 9:30:45.678 using datetime.time(9, 30, 45, 678000)
time_object = datetime.datetime.now().time() # create a time object for present time
# print the time object
print(“Time object:”, time_object)
# print the hour, minute, second, and microsecond attributes
print(“Hour:”, time_object.hour)
print(“Minute:”, time_object.minute)
print(“Second:”, time_object.second)
print(“Microsecond:”, time_object.microsecond)
==================================================================================
import datetime
# create a datetime object for February 17, 2023 at 9:30:45.678
datetime_object = datetime.datetime(2023, 2, 17, 9, 30, 45, 678000)
#print the datetime object
print(“Datetime object:”, datetime_object)
# print the year, month, day, hour, minute,
# second, microsecond and timestamp attributes
print(“Year:”, datetime_object.year)
print(“Month:”, datetime_object.month)
print(“Day:”, datetime_object.day)
print(“Hour:”, datetime_object.hour)
print(“Minute:”, datetime_object.minute)
print(“Second:”, datetime_object.second)
print(“Microsecond:”, datetime_object.microsecond)
print(“timestamp:”, datetime_object.timestamp())
=================================================================================
import datetime
# create a datetime object for February 17, 2023 at 9:30:45.678
datetime_object=datetime.datetime(2023, 2, 17, 9, 30, 45, 678000)
# print the datetime object
print(“Datetime object:”, datetime_object)
# print the the year, month, day, hour, minute,
# second, microsecond and timestamp attributes
print(“Year:”, datetime_object.year)
print(“Month:”, datetime_object.month)
print(“Day:”, datetime_object.day)
print(“Hour:”, datetime_object.hour)
print(“Minute:”, datetime_object.minute)
print(“Second:”, datetime_object.second)
print(“Microsecond:”, datetime_object.microsecond)
print(“timestamp:”, datetime_object.timestamp())
==================================================================================
import datetime
# create a timedelta object representing 2 days, 3 hours, and 30 minutes
delta_object=datetime.timedelta(days=2, hours=3, minutes=30)
# create a datetime object for February 17, 2023 at 9:30:45
datetime_object=datetime.datetime(2023, 2, 17, 9, 30, 45)
# add the timetable object to the datetime object
new_datetime_object=datetime_object+delta_object
# subtract the timedelta object from the datetime object
old_datetime_object=datetime_object-delta_object
# print the results
print(“Original datetime:”, datetime_object)
print(“New datetime:”, new_datetime_object)
print(“Old datetime:”, old_datetime_object)
==================================================================================
import datetime
# create two datetime objects
start_time=datetime.datetime(2023,2,17,9,30,0)
end_time=datetime.datetime(2023,2,20,17,30,0)
# calculate the difference between the two datetime objects
time_delta=end_time-start_time
# create two timedelta objects
delta1 = datetime.timedelta(hours=1)
delta2 = datetime.timedelta(days=2, hours=3)
# calculate the difference between the two timedelta objects
delta3 = delta2 – delta1
# print the results
print(“Time difference:”, time_delta)
print(“Delta difference:”, delta3)
=====================================================================================
==
import datetime
# create two datetime objects
start_time = datetime.datetime(2023, 2, 17, 9, 30, 0)
end_time = datetime.datetime(2023, 2, 20, 17, 30, 0)
# calculate the difference between the two datetime objects
time_dalta = end_time – start_time
# create two timedelta objects
delta1 = datetime.timedelta(hours=1)
delta2 = datetime.timedelta(days=2, hours=3)
# calculate the difference between two timedelta objects
delta3 = delta2 – delta1
#print the results
print(“Time difference:”, time_delta)
print(“Delta difference:”, delta3)
=====================================================================================
====
import datetime
# create a current datetime object
dt = datetime.datetime.now()
# format the datetime object as “YYYY-MM-DD”
date_string = dt.strftime(“%Y-%m-%d”)
# format the datetime object as “DD/MM/YYYY”
date_string2 = dt.strftime(“%d/%m/%Y”)
# format the datetime object as “YYYY-MM-DD HH:MM:SS”
datetime_string = dt.strftime(“%Y-%m-%d %H:%M:%S”)
# print the results
print(date_string)
print(date_string2)
print(datetime_string)
==================================================================================
import datetime
# create a string representing the date and time
date_string = “2023-02-17 09:30:45”
# parse the string into a datetime object
dt = datetime.datetime.strptime(date_string, “%Y-%m-%d %H:%M:%S”)
# print the datetime object
print(dt)
=====================================================================================
===
%Y – 4-digit year
%m -2 -digit month (with leading zeros)
%d -2-digit day (with leadingzeros)
%H -24-hour format hour (with leading zeros)
%M – minute (with leading zeros)
%S – second (with leading zeros)
=====================================================================================
import datetime
# Enter your birthdate
birthdate = datetime.date(1989, 11, 27)
# Calculate the number of days since birthdate
days_since_birth = (datetime.date.today() – birthdate).days
# Print the result
print(“It has been {} days since your birthdaye.”.format(days_since_birth))
=====================================================================================
===
import datetime
# Define the start and end dates
start_date = datetime.date(2022, 1, 1)
end_date = datetime.date(2022, 12, 31)
# Initialize a counter variable
num_saturdays = 0
# Iterate over the days between the start and end dates
for d in range((end_date – start_date).days + 1):
date = start_date + datetime.timedelta(d)
# Check if the current day is a Saturday
if date.weekday() == 5:
num_saturdays +=1
# Print the result
print(“There are {} Saturdays between {} and {}.”. format(num_saturdays, start_date, end_date))
=====================================================================================
====
import datetime
# Enter your birthdate and the current year
birthdate = datetime.date(1989, 11, 27)
current_year = datetime.date.today().year
# Calculate the date of your next birthday
next_birthday = datetime.date(current_year, birthdate.month, birthdate.day)
if next_birthday < datetime.date.today():
next_birthday == datetime.date(current_year + 1, birthdate.month, birthdate.day)
# Calculate the number of days untill your next birthday
days_left = (next_birthday – datetime.date.today()).days
# Print the result
print(“There are {} days left untill your next birthday.”.format(days_left))
=====================================================================================
====
import datetime
bdate = datetime.date(1989, 11, 27)
td = datetime.date.today() – bdate
print(td.total_seconds())
=====================================================================================
========
import datetime
date_str = “2022-02-17”
date_obj = datetime.datetime.strptime(date_str, “%Y-%m-%d”)
formatted_date = date_obj.strftime(“%b-%d, %Y”)
print(formatted_date)
=====================================================================================
======
import datetime
# create a timedelta object representing 2 days, 3 hours, and 30 minutes
delta_object = datetime.timedelta(days=2, hours=3, minutes=30)
# create a datetime object for February 17, 2023 at 9:30:45
datetime_object = datetime.datetime(2023, 2, 17, 9, 30, 45)
# add the timedelta object to the datetime object
new_datetime_object = datetime_object + delta_object
# subtract the timedelta object from the datetime object
old_datetime_object = datetime_object – delta_object
# print the results
print(“Original datetime:”, datetime_object)
print(“New datetime:”, new_datetime_object)
print(“Old datetime:”, old_datetime_object)
=====================================================================================
=====
try:
if (3+4-5)>0:
a=3
a.append(“hello”)
print(“hello”+4)
except(AttributeError, TypeErro) as e:
print(“Error occurred:”,e)
finally:
print(“try except block successfully executed”)
=====================================================================================
=======
num1=int(input(‘Enter a number:’))
num2=int(input(‘Enter another number:’))
result=num1/num2
print(f”The result of {num1}/{num2} is {result}”)
=====================================================================================
=============
try:
print(“try block”)
num1=int(input(‘Enter a number:’))
num2=int(input(‘Enter another number:’))
result=num1/num2
print(f”The result of {num1}/{num2} is {result}”)
except ZeroDivisionError:
print(“Cannot divide by zero”)
except ValueError:
print(“Please enter a valid number”)
else:
print(“else block”)
print(“No exception was raised”)
finally:
print(“finally block”)
print(“This will always execute”)
print(“Out of try, except, else and finally block.”)
=====================================================================================
============
try:
file=open(“example.txt”,”r”)
content=file.read()
print(content)
file.close()
except IOError as e:
print(“Error: File not found.”,e.strerror)
=================================================================================
def divide(x,y):
if y==0:
raise ZeroDivisionError(“Cannot divide by zero”)
return x/y
try:
result=divide(10,0)
except ZeroDivisionError as error:
print(error)
=====================================================================================
====
try:
f=open(‘myfile.txt’,’w’)
num1=int(input(“Enter a number:”))
num2=int(input(“Enter another number:”))
result=num1/num2
print(f”The result of {num1}/{num2} is {result}”)
s=f.erite(str(result))
print(“Result is stored in file”)
except ValueError:
print(“Please enter a valid number”)
except ZeroDivisionError:
print(“Cannot divide by zero”)
except Exception as e:
print(“An error occurred:”, e)
except:
print(“Unexpected error:”)
finally:
f.close()
===================================================================================
#Input an age that raises an exception if age is less than 18
def check_age(age):
if age<18:
raise ValueError(“Age should be at least 18 years old to vote.”)
else:
print(“You are eligible for voting”)
# Testing the function with different ages
age=int(input(“Enter the age:”))
try:
check_age(age)
except ValueError as e:
print(e)
=====================================================================================
==
def get_positive_number():
num=int(input(“Enter a positive number:”))
if num<0:
raise ValueError(“Enter only positive number”)
return num
try:
positive_num=get_positive_number()
print(“The positive number is:”, positive_num)
except ValueError as e:
print(e)
=====================================================================================
=====
class MinimumBalanceError(Exception):
“””Exception raised when an account balance goes below the required minimum.”””
def __init__(self, message=”Balance is below the required minimum”):
self.message=message
super(). __init__(self.message)
# Example usage in a BankAccount class
class BankAccount:
def __init__(self, balance, min_balance):
self.balance=balance
self.min_balance=min_balance
def withdra(self, amount):
if self.balance-amount<self.min_balance:
raise MinimumBalanceError(f”Cannot withdraw {amount}. Minimum balance of
{self.min_balance} must be maintained.”)
self.balance -= amount
return self.balance
# Testing the exception
try:
account = BankAccount(500, 100)
account.withdraw (450) # This will raise the exception
except MinimumBalanceError as e:
print(f”Error: {e}”)
=====================================================================================
=======================
class MinimumBalanceError(Exception):
“””customer exception raised when the account balance falls below the minimum balance.”””
pass
class BankAccount:
def __init__(self, account_number, balance, minimum_balance):
self.account_number=account_number
self.balance=balance
self.minimum_balance=minimum_balance
def withdraw(self, amount):
if self.balance-amount<self.minimum_balance:
raise MinimumBalanceError(“Minimum balance requirement not met.”)
else:
self.balance-=amount
print(f”Withdrawal of {amount} successful. Available balance:{self.balance}.”)
# Testing the code with different withdrawal amounts
account=BankAccount(“1234567890”, 5000, 2000)
try:
account.withdraw(4000)
except MinimumBalanceError as e:
print(e)
try:
account.withdraw(1000)
except MinimumBalanceError as e:
print(e)
try:
account.withdraw(3000)
except MinimumBalanceErro as e:
print(e)
=====================================================================================
=====
class NegativeNumberErro(Exception):
“””Custom exception raised when a negative number is encountered.”””
pass
def square_root(num):
if num<0:
raise NegativeNumberError(“Cannot compute square root of negative number”)
else:
return num**0.5
# Testing the function witrh different values
num=int(input(“Enter a positive number:”))
try:
print(square_root(num))
except NegativeNumberError as e:
print(e)
=====================================================================================
=====
import time
import threading
def calc_square(numbers):
print(“Calculate suare numbers”)
for n in numbers:
time.sleep(1)
print(‘square:’, n*n)
def calc_cube(numbers):
print(“Calculate cube of numbers”)
for n in numbers:
time.sleep(1)
print(‘cube:’,n*n*n)
arr = [2,3,4,5,6,7,8,9]
t = time.time()
t1=threading.Thread(target=calc_square, args=(arr,))
t2=threading.Thread(target=calc_cube, args=(arr,))
t1.start()
t2.start()
t1.join()
t2.join()
print(“Done in : “,time.time()-t)
import threading
import time
# Define a new class that extends the Thread class
class MyThread(threading.Thread):
def __init__(self, name, delay):
threading.Thread.__init__(self)
self.name = name
self.delay = delay
# Override the run method to define the behavior of the thread
def run(self):
print(“Starting”+self.name)
count = 0
while count<=5:
time.sleep(self.delay)
print(self.name + ” count:” + str(count))
count += 1
print(“Exiting ” + self.name)
# Create two instances of the MyThread class
thread1 = MyThread(“Thread-1”, 1)
thread2 = MyThread(“Thread-2”, 2)
# Start the threads
thread1.start()
thread2.start()
# Wait for the threads to finish
thread1.join()
thread2.join()
print(“Main thread exiting…”)
=================================================================================
import time
def sqr(n):
for x in n:
time.sleep(1)
print(“Square of number”,x,”is:”,x*x)
def cube(n):
for x in n:
time.sleep(1)
print(“Cube of number”,x,”is:”, x*x*x)
n=[1,2,3,4,5,6,7,8]
start=time.time()
sqr(n)
cube(n)
end=time.time()
print(“Total time taken for execution is:”,end-start)
=====================================================================================
========
import threading
import time
def sqr(n):
for x in n:
time.sleep(1)
print(“Square of number”,x,”is:”,x*x)
def cube(n):
for x in n:
time.sleep(1)
print(“Cube of number”,x,”is:”,x*x*x)
n=[1,2,3,4,5,6,7,8]
start=time.time()
t1=threading.Thread(target=sqr, args=(n,))
t2=threading.Thread(target=sqr, args=(n,))
t1.start()
t2.start()
t1.join()
t2.join()
end=time.time()
print(“Total time taken for execution is:”,end-start)
================================================================================
from threading import *
from time import *
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
name=current_thread().name
if name==”SquareThread”:
for i in range(1,11):
print(name,”-“,(i*i))
sleep(1)
elif name==”CubeThread”:
for i in range(1,11):
print(name,”-“,(i*i*i))
sleep(1)
t1=MyThread()
t1.name=”SquareThread”
t2=MyThread()
t2.name=”CubeThread”
t1.start()
t2.start()
t1.join()
t2.join()
print(“Main Thread Ends”)
=====================================================================================
===========
import tkinter as tk
window=tk.Tk()
window.title(“My GUI Application”)
window.geometry(“300×200″)
label=tk.Label(text=”Hello, Tkinter!”, font=(“Arial”, 16))
label.pack(pady=20)
button = tk.Button(text=”Click me!”)
button.pack()
window.mainloop()
=====================================================================================
=
import tkinter as tk
# Create a window
window=tk.Tk()
# Set the window title
window.title(“Pack Geometry Manager Example”)
# Set the window size
window.geometry(“300×200″)
# Create a label and pack it into the window
label1=tk.Label(window, text=”Label 1″, bg=”red”)
label1.pack(side=”left”, padx=10, pady=10)
# Create a button and pack it into the window
button1 =tk.Button(window, text=”Button 1″, bg=”green”)
button1.pack(side=”top”, fill=”both”, expand=True, padx=10, pady=10)
# Create a label and pack it into the window
label2=tk.Label(window, text=”Label 2″, bg=”blue”)
label2.pack(side=”right”, fill=”y”, padx=10, pady=10)
# Run the event loop
window.mainloop()
=====================================================================================
====
import tkinter as tk
# create the main window
root = tk.Tk()
root.title(“Geometry Manager Grid Example”)
# create a label widget
label = tk.Label(root, text=”Hello, Grid!”, bg=”red”, fg=”white”, height=2)
# place the label using the grid geometry manager
label.grid(row=0, column=0, rowspan=2, columnspan=2, ipadx=10, ipady=10)
#create a button widget
button1=tk.Button(root, text=”Button 1″, padx=10, pady=5)
button2=tk.Button(root, text=”Button 2″, padx=10, pady=5)
# place the buttons using the grid geometry manager
button1.grid(row=0, column=3, padx=30, pady=20)
button2.grid(row=1, column=2, padx=10, pady=10)
# start the main event loop
root.mainloop()
=====================================================================================
=======
import tkinter as tk
from tkinter import messagebox
root=tk.Tk()
root.title(“Button widget Example”)
root.geometry(“300×200”)
# Define a function to be called when the button is clicked
def button_clicked():
messagebox.showinfo(“Hello”, “Button clicked”)
# Create a button widget
button=tk.Button(root, text=”Click me!”, command=button_clicked)
button.pack(pady=10)
root.mainloop()
=====================================================================================
====
import tkinter as tk
root =tk.Tk()
root.title(“Check Button Example”)
root.geometry(“300×200”)
# Define a function to be called when the check button is clicked
def checkbutton_clicked():
if var.get()==1:
print(“Check button selected!”)
else:
print(“Check button deselected.”)
# Create a variable to hold the state of the check button
var = tk.IntVar()
# Create a check button widget
checkbutton =tk.Checkbutton(root, text=”Option 1″, variable=var, command=checkbutton_clicked)
checkbutton.pack(pady=10)
root.mainloop()
=====================================================================================
from tkinter import *
from tkinter import messagebox
root=Tk()
root.title(“Select languages known”)
v1=IntVar()
v2=IntVar()
v3=IntVar()
v4=IntVar()
v5=IntVar()
l=[‘python’,’java’,’C#’,’C++’,’C’]
c1=Checkbutton(root,text=I[0],offvalue=0,onvalue=1,variable=v1)
c2=Checkbutton(root,text=I[1],offvalue=0,onvalue=1,variable=v2)
c3=Checkbutton(root,text=I[2],offvalue=0,onvalue=1,variable=v3)
c4=Checkbutton(root,text=I[3],offvalue=0,onvalue=1,variable=v4)
c5=Checkbutton(root,text=I[4],offvalue=0,onvalue=1,variable=v5)
c1.pack()
c2.pack()
c3.pack()
c4.pack()
c5.pack()
x=”
def f1():
global x
x=”
if v1.get():
x=x+’ ‘ +str(l[0])
if v2.get():
x=x+’ ‘ +str(l[1])
if v3.get():
x=x+’ ‘ +str(l[2])
if v4.get():
x=x+’ ‘ +str(l[3])
if v5.get():
x=x+’ ‘ +str(l[4])
msg=messagebox.showinfo(‘Languages selected’,’ You have selected the ‘+x+’ languages’)
b1=Button(root,text=’Click Me’,command=f1)
b1.pack()
root.mainloop()
=====================================================================================
========
from tkinter import*
root=Tk()
root.title(“Radiobutton widget Example”)
root.geometry(“300×150”)
def radiobutton_selected():
y=r_var.get()
x=lst[y]
selection = “Your favorite language is:”+x
label.config(text=selection)
lst=[‘C’,’C++’,’java’]
r_var=IntVar()
lbl = Label(text = “Choose your favorite programming language:”)
lbl=Label(text=”Choose your favorite programming language:”)
lbl.pack()
R1=Radiobutton(root, text=lst[0], variable=r_var, value=0, command=radiobutton_selected)
R1.pack(anchor=W)
R2=Radiobutton(root, text=lst[1], variable=r_var, value=1, command=radiobutton_selected)
R2.pack(anchor=W)
R3=Radiobutton(root, text=lst[2], variable=r_var, value=2, command=radiobutton_selected)
R3.pack(anchor=W)
label=Label(root)
label.pack()
root.mainloop()
=====================================================================================
=========
from tkinter import*
root=Tk()
root.title(“Listbox Example”)
root.geometry(“200×250″)
root.config(bg=’yellow’)
lbl=Label(root, text=”A list of countries…”)
def showSelected():
show_lbl.config(text=’You selected: ‘+listbox.get(ANCHOR))
items=[“India”, “USA”, “Japan”,”Australia”,”China”]
listbox=Listbox(root)
# Insert each item from the list into the listbox
for item in items:
listbox.insert(END, item)
#this button will delete the selected item from the list
btn1 = Button(root, text = “delete”, command = lambda
listbox=listbox:listbox.delete(ANCHOR))
# Any item that is selected can be referred to as ‘ANCHOR’.
btn2=Button(root, text=”select”, command=showSelected)
show_lbl=Label(root, text=””)
show_lbl.place(x=100,y=250)
lbl.pack()
listbox.pack()
btn1.pack()
btn2.pack()
root.mainloop()
====================================================================================
import tkinter as tk
root=tk.Tk()
root.title(“Canvas Example”)
# Create a canvas(root, width=400, height=400)
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# Draw a rectangle on the canvas
rect = canvas.create_rectangle(50, 50, 250, 150, fill=”red”)
# Draw an oval on the canvas
oval = canvas.create_oval(100, 100, 30, 200, fill=”green”)
root.mainloop()
=====================================================================================
=
from tkinter import*
root=Tk()
root.title(“Canvas widget Example”)
c=Canvas(root, background=’yellow’, height=400, width=300)
c.pack()
def draw_shapes():
a=(140, 130, 200, 250)
c.create_arc(a,start=0,extent=90,fill=’blue’)
c.create_line(2,3,40,100,180,120)
c.create_rectangle(50, 300, 150, 170, fill=”pink”)
c.create_oval(20,20,100,100,fill=’red’)
c.create_polygon(10,20,15,20,100,50,10,50,fill=’cyan’)
b1=Button(root,text=’Click Me’,command=draw_shapes)
b1.pack()
root.mainloop()
=================================================================================
from tkinter import*
root=Tk()
root.title(“Scale widget Example”)
root.geometry(“200×100″)
def get_scale_value():
sel=”Scale Value=”+str(scale_var.get())
label.config(text=sel)
scale_var=DoubleVar()
#Create a Scale widget
scale=Scale(root, variable=scale_var, from_=1, to=100, orient=HORIZONTAL, length=120)
scale.pack()
btn=Button(root, text=”GetScale”, command=get_scale_value)
btn.pack(anchor=CENTER)
label=Label(root)
label.pack()
root.mainloop()
=====================================================================================
===
from tkinter import*
root=Tk()
root.title(“Scrollbar widget Example”)
scroll_bar=Scrollbar(root)
scroll_bar.pack(side=’right’, fill=’y’)
mylist=Listbox(root, yscrollcommand=scroll_bar.set)
for line in range(50):
mylist.insert(END, “Number:” + str(line))
mylist.pack(side=’left’)
scroll_bar.config(command=mylist.yview)
mainloop()
=====================================================================================
====
import tkinter as tk
# Create the root window
root=tk.Tk()
root.title(“Frame widget Example”)
root.geometry(“300×200”)
#Create a Frame widget and pack it to the root window
frame = tk.Frame(root, bg=’yellow’, bd=5, relief=’groove’)
frame.pack(side=’top’,fill=’x’, padx=50, pady=50)
# Create some widgets and pack them to the Frame widget
label1=tk.Label(frame, text=’Label1′,bg=’white’, fg=’black’)
label1.pack(side=’left’, padx=10, pady=10)
label2=tk.Label(frame, text=’Label 2′, bg=’while’, fg=’black’)
label2.pack(side=’left’, padx=10, pady=10)
button=tk.Button(frame, text=’Click me’, bg=’blue’, fg=’white’)
button.pack(side=’right’, padx=10, pady=10)
#Start the main loop
root.mainloop()
=====================================================================================
import tkinter as tk
# Create the root window
root=tk.Tk()
root.title(“LabelFrame Example”)
root.geometry(“300×200”)
# Create a LabelFrame widget and pack it to the root window
label_frame=tk.LabelFrame(root, text=’Personal Information’, padx=10, pady=10)
label_frame.pack(padx=10, pady=10)
# Create some widgets and pack them to the LabelFrame widget
name_label=tk.Label(label_frame, text=’Name:’)
name_label.grid(row=0, column=0, padx=10, pady=10)
name_entry=tk.Entry(label_frame)
name_entry.grid(row=0, column=1, padx=10, pady=10)
age_label=tk.Label(label_frame, text=’Age:’)
age_label.grid(row=1, column=0, padx=10, pady=10)
age_entry=tk.Entry(label_frame)
age_entry.grid(row=1, column=1, padx=10, pady=10)
#Create a Button widget and pack it to the root window
button=tk.Button(root, text=’Submit’, bg=’blue’, fg=’white’)
button.pack(padx=10, pady=10)
#Start the main loop
root.mainloop()
=====================================================================================
==========
import tkinter as tk
# Create the root window
root=tk.Tk()
root.title(“Menu widget Example”)
root.geometry(‘500×300′)
root.config(bg=’pink’)
# Create a Menu widget and attach it to the root window
menu_bar=tk.Menu(root) #top-level menu
root.config(menu=menu_bar)
# Create a ‘File’ menu and add some options to it
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label=’New’)
file_menu.add_command(label=’Open’)
file_menu.add_separator()
file_menu.add_command(label=’Save’)
file_menu.add_command(label=’Save As’)
file_menu.add_separator()
file_menu.add_command(label=’Print’)
file_menu.add_command(label=’Exit’, command=root.destroy)
menu_bar.add_cascade(label=’File’, menu=file_menu)
# Create an ‘Edit’ menu and add some options to it
edit_menu=tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label=’Undo’)
edit_menu.add_separator()
edit_menu.add_command(label=”Cut”)
edit_menu.add_command(label=”Copy”)
edit_menu.add_command(label=”Paste”)
edit_menu.add_separator()
edit_menu.add_command(label=”Delete”)
edit_menu.add_command(label=”Find”)
edit_menu.add_command(label=”Replace”)
edit_menu.add_command(label=”Select All”)
menu_bar.add_cascade(label=’Edit’, menu=edit_menu)
help_menu=tk.Menu(menu_bar, tearoff=0) #Help menu widget
help_menu.add_command(label=”View Help”)
help_menu.add_separator()
help_menu.add_command(label=”About”)
menu_bar.add_cascade(label=’Help’, menu=help_menu)
# Start the main loop
root.mainloop()
=====================================================================================
======
import tkinter as tk
# Create the root window
root=tk.Tk()
root.title(“Menubutton widget Example”)
root.geometry(“200×250”)
# Create a Menubutton widget and add some options to it
menu_button=tk.Menubutton(root, text=’Languages known’, relief=’raised’)
menu_button.pack(padx=10, pady=10)
options_menu=tk.Menu(menu_button, tearoff=0)
options_menu.add_command(label=’Hindi’)
options_menu.add_command(label=’English’)
options_menu.add_command(label=’Telugu’)
options_menu.add_separator()
options_menu.add_command(label=’Exit’, command=root.destroy)
menu_button.config(menu=options_menu)
# Start the main loop
root.mainloop()
=====================================================================================
==========
from tkinter import*
root=Tk()
root.title(“Message widget Example”)
root.geometry(“300×200”)
lbl=Label(root, text=’Label widget’, font=(“Arial Bold”, 20), fg=”red”)
lbl.pack()
var=StringVar()
var.set(“Welcome to Message widget”)
# Create a Message widget
msg=Message(root, width=100, textvariable=var, font=(” Arial Bold”, 16), relief=RAISED, fg=”white”,
bg=”blue”, justify=”center”)
msg.pack(pady=20)
root.mainloop()
=====================================================================================
==============
from tkinter import*
root=Tk()
root.title(“OptionMenu widget Example”)
root.geometry(“300×200”)
# Define a list of colors
options = [“Yellow”, “Pink”, “Red”,”Brown”, “Blue”]
# Create a variable to store the selected option
selected_option=StringVar()
# Set the initial value of the variable to the first option
selected_option.set(options[0])
# Create an OptionMenu widget
option_menu=OptionMenu(root, selected_option, *options)
option_menu.pack()
def my_function():
print(“Selected color is:”, selected_option.get())
root.configure(bg=selected_option.get())
button=Button(root, text=”Click”, command=my_function)
button.pack(pady=20)
root.mainloop()
=====================================================================================
=====
import tkinter as tk
root=tk.Tk()
root.title(“PanedWindow widget Example”)
root.geometry(“400×300″)
# Create a vertical PanedWindow
paned_window=tk.PanedWindow(root, orient=tk.VERTICAL, sashwidth=100)
pane1=tk.Frame(paned_window, bg=”orange”, width=200, height=100)
pane2=tk.Frame(paned_window, bg=”green”, width=200, height=100)
paned_window.add(pane1)
paned_window.add(pane2)
# Pack the PanedWindow into the window
paned_window.pack(fill=tk.BOTH, expand=True)
root.mainloop()
=====================================================================================
=====
from tkinter import*
root=Tk()
root.title(“Spinbox widget Example”)
root.geometry(“200×100″)
# Create Spinbox widgets
spin_box1=Spinbox(root, from_=0, to=50, width=10)
spin_box2=Spinbox(root, from_=0, to=10, increment=0.5, width=5, format=”%.2f”)
# Pack the Spinbox widgets into the window
spin_box1.pack(pady=10)
spin_box2.pack(pady=20)
root.mainloop()
===============================================================================
import tkinter as tk
root=tk.Tk()
root.title(“Top level Example”)
root.geometry(“200×100”)
# Create a button that opens a new window when clicked
def open_window():
new_window=tk.Toplevel(root)
new_window.title(“Toplevel window”)
new_window.geometry(“150×100″)
label=tk.Label(new_window, text=”Hello, World!”)
label.pack(pady=10)
button=tk.Button(root, text=”OPen Window”, command=open_window)
button.pack(pady=10)
root.mainloop()
=====================================================================================
=====
import numpy as numpy
arr = np.array([1,2,3,4,5])
print(arr)
=====================================================================================
========
import matplotlib.pyplot as plt
import numpy as np
t=[0,30,45,60,90]
x=[i*(np.pi/180) for i in t]
plt.plot(t,np.sin(x) ,marker=”+”)
plt.plot(t,np.sin(x) ,marker=”^”)
plt.xticks(t)
plt.show()
====================================================================================
#Write a Python Program for method overloading
class Calculator:
# Method with one argument
def add(self, a, b=0):
return a + b
# Create an object of Calculator
calc = Calculator()
# Calling with one argument (acts like method overloading)
print(“Result with one argument:”, calc.add(5))
# Calling with two arguments (acts like method overloading)
print(“Result with two arguments:”, calc.add(5, 3))
=====================================================================================
=======
# var1.py
# Assigning values to variables
x = 10
# Integer value
y = 3.14 # Float value
name = “John” # String value
is_valid = True # Boolean value
# Printing the values to check
print(“x =”, x)
print(“y =”, y)
print(“name =”, name)
print(“is_valid =”, is_valid)
=====================================================================================
===
# 14 Write a Python Program for method overloading
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
# Creating an object of Calculator
calc = Calculator()
# Calling the add method with two arguments
result1 = calc.add(5, 10)
print(“Sum of 5 and 10:”, result1)
# Calling the add method with three arguments
result2 = calc.add(5, 10, 15)
print(“Sum of 5, 10, and 15:”, result2)
=====================================================================================
=========
# 16 Write a Python Program for multiple inheritance
class Animal:
def speak(self):
print(“Animal makes a sound”)
class Mammal(Animal):
def walk(self):
print(“Mammal can walk”)
class Bird(Animal):
def fly(self):
print(“Bird can fly”)
# Child class inheriting from both Mammal and Bird
class Bat(Mammal, Bird):
def sound(self):
print(“Bat makes a sound”)
# Create an object of Bat
bat = Bat()
# Calling methods from both Mammal and Bird classes
bat.speak() # From Animal class
bat.walk() # From Mammal class
bat.fly() # From Bird class
bat.sound() # From Bat class
=====================================================================================
=
#17 Write a Python Program for hybrid inheritance
# Base class (Parent)
class Animal:
def speak(self):
print(“Animal speaks”)
# Class A (Child of Animal, Multilevel inheritance)
class Mammal(Animal):
def walk(self):
print(“Mammal walks”)
# Class B (Another child of Animal, Multiple inheritance)
class Bird(Animal):
def fly(self):
print(“Bird flies”)
# Class C (Hybrid inheritance: Inheriting from both Mammal and Bird)
class Bat(Mammal, Bird):
def sound(self):
print(“Bat makes a sound”)
# Create an object of Bat
bat = Bat()
# Calling methods from both Mammal and Bird classes
bat.speak() # From Animal class
bat.walk() # From Mammal class
bat.fly()
# From Bird class
bat.sound() # From Bat class
=====================================================================================
==================
# 18 Write a Python Program to perform operations on strings
# Define some example strings
string1 = “Hello”
string2 = “World”
string3 = “Python Programming”
# 1. String Concatenation
concatenated_string = string1 + ” ” + string2
print(“Concatenated String:”, concatenated_string)
# 2. String Repetition
repeated_string = string1 * 3
print(“Repeated String:”, repeated_string)
# 3. String Length
length_of_string = len(string3)
print(“Length of String ‘Python Programming’:”, length_of_string)
# 4. String Slicing (Extracting substrings)
substring = string3[0:6] # Extracting from index 0 to 5 (6 is exclusive)
print(“Substring from index 0 to 5:”, substring)
# 5. String Case Conversion
upper_case_string = string1.upper()
print(“String in Upper Case:”, upper_case_string)
lower_case_string = string2.lower()
print(“String in Lower Case:”, lower_case_string)
# 6. String Find (Finding a substring in a string)
position = string3.find(“Python”)
if position != -1:
print(“Substring ‘Python’ found at index:”, position)
else:
print(“Substring ‘Python’ not found.”)
# 7. Checking if a String Contains a Substring (Using ‘in’)
is_present = “Programming” in string3
print(“‘Programming’ is in ‘Python Programming’:”, is_present)
# 8. String Replacement
replaced_string = string3.replace(“Python”, “Java”)
print(“Replaced String:”, replaced_string)
# 9. Stripping Whitespace (Removing leading and trailing whitespaces)
string_with_spaces = ” Hello World ”
stripped_string = string_with_spaces.strip()
print(“Stripped String:”, stripped_string)
# 10. String Split
words = string3.split() # Splits the string by spaces by default
print(“List of words in the string:”, words)
# 11. String Joining
joined_string = “-“.join(words) # Join the words with hyphen (-)
print(“Joined String:”, joined_string)
# 12. Checking if String is a Digit
string_digit = “12345”
is_digit = string_digit.isdigit()
print(“‘12345’ is a digit:”, is_digit)
# 13. String Case Checking (isalpha, islower, isupper)
is_alpha = string1.isalpha() # True if all characters are alphabets
print(“‘Hello’ is alphabetic:”, is_alpha)
is_lower = string2.islower() # True if all characters are lowercase
print(“‘World’ is lowercase:”, is_lower)
is_upper = string1.isupper() # True if all characters are uppercase
print(“‘HELLO’ is uppercase:”, is_upper)
=====================================================================================
=========
# 19 Write a Python Program to slice a list
# Create a sample list
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 1. Basic slicing: Get elements from index 2 to 5 (index 5 is exclusive)
sliced_list_1 = sample_list[2:6]
print(“Sliced List (index 2 to 5):”, sliced_list_1)
# 2. Slicing with step: Get elements from index 0 to 9 with a step of 2
sliced_list_2 = sample_list[0:10:2]
print(“Sliced List (step 2):”, sliced_list_2)
# 3. Slicing without specifying start and end: Get the entire list
sliced_list_3 = sample_list[:]
print(“Entire List (from start to end):”, sliced_list_3)
# 4. Slicing with negative indices: Get the last 3 elements of the list
sliced_list_4 = sample_list[-3:]
print(“Last 3 elements:”, sliced_list_4)
# 5. Slicing with negative indices and step: Get elements from index -1 to -8 with a step of -2
sliced_list_5 = sample_list[-1:-9:-2]
print(“Sliced List with negative indices and step -2:”, sliced_list_5)
# 6. Slicing with negative indices but no end: Get elements from index -5 to the start
sliced_list_6 = sample_list[-5:]
print(“Elements from index -5 to the end:”, sliced_list_6)
=====================================================================================
=====================
# 20 Write a Python Program to display multiplication tables
# Function to display the multiplication table
def display_multiplication_table(number):
print(f”\nMultiplication Table for {number}:\n”)
for i in range(1, 11):
print(f”{number} x {i} = {number * i}”)
# Input from the user
number = int(input(“Enter a number to display its multiplication table: “))
# Display the multiplication table for the entered number
display_multiplication_table(number)
=====================================================================================
=============================
# 15 Write a Python Program for method overriding
class Animal:
# Method in the parent class (superclass)
def sound(self):
print(“Some generic animal sound”)
class Dog(Animal):
# Method in the child class (subclass) overriding the parent class method
def sound(self):
print(“Woof! Woof!”)
class Cat(Animal):
# Method in the child class (subclass) overriding the parent class method
def sound(self):
print(“Meow! Meow!”)
# Create objects of the child classes
dog = Dog()
cat = Cat()
# Calling overridden methods
dog.sound() # Output: Woof! Woof!
cat.sound() # Output: Meow! Meow!
# Calling method from parent class (Animal)
animal = Animal()
animal.sound() # Output: Some generic animal sound
=====================================================================================
=============
import os
path = “dic.txt”
print
(os.path.isfile(path))====================================================================
=======
import RPi.GPIO as GPIO
import time
# Set the GPIO mode
GPIO.setmode(GPIO.BCM)
# Set GPIO pin 17 as output (where the LED is connected)
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
# Turn LED on
GPIO.output(LED_PIN, GPIO.HIGH)
print(“LED is ON”)
time.sleep(2) # Keep the LED on for 2 seconds
# Turn LED off
GPIO.output(LED_PIN, GPIO.LOW)
print(“LED is OFF”)
# Cleanup GPIO settings
GPIO.cleanup()
=====================================================================================
=====
import matplotlib.pyplot as plt
import numpy as np
t=[0,30,45,60,90]
x=[i*(np.pi/180)for i in t]
plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))
plt.show()
=====================================================================================
====
import tkinter as tk
window=tk.Tk()
window.title(“My GUI Application”)
window.geometry(“300×200″)
label=tk.Label(text=”Hello tkinter”, font(“Arial”,16))
label.pack(pady=20)
button=tk.Button(text=”Click me!”)
button.pack()
window.mainloop()
=====================================================================================
========
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, grade):
# Call the base class (Animal) constructor
super().__init__(name, age)
self.grade = grade
# Creating an instance of Dog
student = Student(“Shiva”, “30”, “A”)
print(student.name)
print(student.age)
print(student.grade)
FAQ’s: