Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Python Lab Codes (1-36)

The document contains 36 code snippets demonstrating various Python programming concepts like variables, data types, conditional statements, loops, functions, OOP concepts, classes and objects. Some key snippets include: 1. Functions to add numbers, find maximum/minimum, calculate area of circle, etc. 2. Demonstrating operators, range function, while and for loops. 3. Creating and manipulating lists, tuples, dictionaries and sets. 4. Defining functions with parameters, default arguments, variable arguments. 5. Creating classes, initializing objects, defining methods. 6. Implementing concepts like constructors, destructors, static and instance variables in classes.

Uploaded by

Sahil Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python Lab Codes (1-36)

The document contains 36 code snippets demonstrating various Python programming concepts like variables, data types, conditional statements, loops, functions, OOP concepts, classes and objects. Some key snippets include: 1. Functions to add numbers, find maximum/minimum, calculate area of circle, etc. 2. Demonstrating operators, range function, while and for loops. 3. Creating and manipulating lists, tuples, dictionaries and sets. 4. Defining functions with parameters, default arguments, variable arguments. 5. Creating classes, initializing objects, defining methods. 6. Implementing concepts like constructors, destructors, static and instance variables in classes.

Uploaded by

Sahil Soni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

1. WRITE A PYTHON SCRIPT TO ADD 3 REAL NUMBERS.

Code:
a=int(input('Enter the value of a: '))
b=int(input('Enter the value of b: '))
c=int(input('Enter the value of c: '))
sum=a+b+c
print('Sum of three numbers is: ',sum)

Output:
2. WRITE A PYTHON SCRIPT TO DEMONSTRATE VARIOUS OPERATORS.

Code:
a=int(input('Enter the value of a: '))
b=int(input('Enter the value of b: '))
add=a+b
sub=a-b
mul=a*b
rem=a%b
div=a/b
lessthan=a<b
greaterthan=a>b
c=a//b
print('sum is: ',add)
print('sub is: ',sub)
print('mul is: ',mul)
print('remainder is: ',rem)
print('division is: ',div)
print('a<b: ',lessthan)
print('a>b: ',greaterthan)
print('a//b: ',c)

Output:
3. WRITE A PYTHON SCRIPT TO PRINT MINIMUM AND MAXIMUM OF 3
NUMBERS.

Code:
a=int(input('Enter the value of a: '))
b=int(input('Enter the value of b: '))
c=int(input('Enter the value of c: '))
print('Minimum is: ')
if a<b and a<c:
print(a)
if b<a and b<c:
print(b)
if c<a and c<b:
print(c)
print('Maximum is: ')
if a>b and a>c:
print(a)
if b>a and b>c:
print(b)
if c>a and c>b:
print(c)

Output:
4. WRITE A PYTHON SCRIPT TO SUM NUMBERS OF ANY SEQUENCE USING
RANGE FUNCTION.

Code:
sum=0.0
for i in range(1,51):
sum=sum+i
print('sum of 50 natural numbers is: ',sum)

Output:
5. WRITE A PYTHON SCRIPT TO PRINT A TABLE OF 6.

Code:
n=int(input('Enter the value: '))
i=1
while(i<=10):
print(n,'X',i,'=',n*i)
i=i+1

Output:
6. WRITE A PYTHON SCRIPT TO CALCULATE THE AREA OF A CIRCLE.

Code:
r=float(input('Enter the value of radius: '))
area=3.14*r*r
print('Area of the circle is: ',area)

Output:
7. WRITE A PYTHON SCRIPT TO PRINT A TABLE OF 5 USING FOR LOOP.

Code:
n=int(input('Enter the value: '))
for i in range (1,11):
print(n,'X',i,'=',n*i)

Output:
8. CREATE AN EMPTY LIST AND ASSIGN IT TO A VARIABLE NAME CALLED
FRUITS AND THEN PERFORM THE FOLLOWING:

insert(),remove(),append(),len(),pop(),clear().
9. WRITE A PYTHON SCRIPT THAT IDENTIFIES AND PRINTS ALL THE VOWELS
USED IN A WORD.

Code:
vowels=['a','e','i','o','u']
word=input('Enter the word: ')
for letter in word:
if letter in vowels:
print(letter)

Output:
10. WRITE A PYTHON SCRIPT TO CREATE A LIST AND PRINT ITS ELEMENTS.

Code:
List=[12,7,20,34,2,9]
for i in List:
print(i)

Output:
11. WRITE A PYTHON SCRIPT TO SORT THE LIST.
12. WRITE A PYTHON SCRIPT TO PRINT THE ELEMENTS OF A LIST WHILE
DEMONSTRATING THE USE OF BREAK STATEMENT.

Code:
fruits=['apple','banana','orange','kiwi','pear']
for fruit in fruits:
if fruit=='kiwi':
break
print(fruit)

Output:
13. WRITE A PYTHON SCRIPT TO PRINT THE ELEMENTS OF A LIST WHILE
DEMONSTRATING THE USE OF CONTINUE STATEMENT.

Code:
fruits=['apple','banana','orange','kiwi','pear']
for fruit in fruits:
if fruit=='kiwi':
continue
print(fruit)

Output:
14. WRITE A PYTHON SCRIPT TO FIND THE LARGEST AMONG 3 NUMBERS.

Code:
a=int(input('Enter the value of a: '))
b=int(input('Enter the value of b: '))
c=int(input('Enter the value of c: '))
print('Largest is: ')
if a>b and a>c:
print(a)
if b>a and b>c:
print(b)
if c>a and c>b:
print(c)

Output:
15. CREATE A TUPLE AND PERFORM THE FOLLOWING FUNCTIONS:
count(), index(), len(), slicing.
16. WRITE A PYTHON SCRIPT TO PRINT ALL THE ELEMENTS OF A TUPLE USING
FOR LOOP.

Code:
t1=(1,2,3)
for t in t1:
print(t)

Output:
17. CREATE A TUPLE AND PRINT ITS FIRST ELEMENT.
18. CREATE A LIST AND CHANGE ANY ONE ELEMENT.
19. WRITE A PYTHON SCRIPT TO CREATE A TUPLE AND APPEND IT.
20. WRITE A PYTHON SCRIPT TO ADD ELEMENTS TO A LIST INPUTTING VALUES
FROM THE USER FOR FIVE TIMES.

Code:
l1=[]
a=int(input('enter list values: '))
for i in range(0,a):
element=int(input('enter the value: '))
l1.append(element)
print(l1)

Output:
21. WRITE A PYTHON SCRIPT TO CREATE A DICTIONARY AND PERFORM
MULTIPLE IN-BUILT OPERATIONS ON IT.
22. WRITE A PYTHON SCRIPT TO CREATE A SET AND PERFORM MULTIPLE
IN-BUILT OPERATIONS ON IT.

Code:
M={0,2,4,6,8}
S={1,3,2,4,9}
print('Union of M and S is: ',M|S)
print('Intersection of M and S is: ',M & S)
print('Difference of M and S is: ',M-S)
print('Symmetric difference of M and S is: ',M ^ S)

Output:
23. WRITE A PYTHON SCRIPT TO CREATE A FUNCTION TO COMPARE TWO
NUMBERS.

Code:
def compare(a,b):
if a>b:
return a
else:
return b
c=int(input('enter a number: '))
d=int(input('enter another number: '))
print('largest is: ')
print(compare(c,d))

Output:
24. WRITE A PYTHON SCRIPT TO CREATE A FUNCTION TO ADD THREE NUMBERS.

Code:
def add(a,b,c):
return a+b+c
d=int(input('enter first number: '))
e=int(input('enter second number: '))
f=int(input('enter third number: '))
print('sum is: ')
print(add(d,e,f))

Output:
25. WRITE A PYTHON SCRIPT TO CREATE A FUNCTION TO FIND THE AREA OF A
CIRCLE.

Code:
def area(a):
return a*3.14*a
b=int(input('enter radius: '))
print('area is: ')
print(area(b))

Output:
26. WRITE A PYTHON SCRIPT TO CREATE A FUNCTION TO ADD ARBITRARY
NUMBER OF ELEMENTS.

Code:
def add_num(*args):
sum=0
for num in args:
sum+=num
return sum
result=add_num(1,3,4)
print('sum is:',result)
result=add_num(16,9,27,10)
print('sum is:',result)
22
result=add_num(1,2,5,6,7)
print('sum is:',result)

Output:
27. WRITE A PYTHON SCRIPT TO DEMONSTRATE THE USE DEFAULT
PARAMETERS PROPERTY OF FUNCTION.

Code:
def ar(a=16,b=9,c=37):
return a+b+c
total=ar(13,7)
print(total)

Output:
28. WRITE A PYTHON SCRIPT TO DEMONSTRATE EVAL AND EXEC WITH
MULTIPLE STATEMENTS.

Code:
a = "5 + 3"
result = eval(a)
print(result)

s = """
a = 10
b = 20
sum = a + b
print(sum)
"""

exec(s)

Output:
29. WRITE A PYTHON SCRIPT TO FIND FACTORIAL OF A NUMBER WHILE
CHECKING FOR THE VALIDATION OF INPUT WITH THE HELP OF NESTED
FUNCTIONS.

Code:
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact

num = int(input('Enter a number:'))


print('Factorial of',num,'is',factorial(num))

Output:
30. DEMONSTRATE THE DEFAULT CONSTRUCTOR AND DESTRUCTOR IN OOP
USING PYTHON.

Code:
class Student:
def __init__(self):
print("inside constructor")
def __del__(self):
print("inside destructor")
st1=Student()

Output:
31. CREATE A CLASS USER AND INSTANTIATE ITS MULTIPLE OBJECTS AND
DISPLAY A GREETING MESSAGE FOR EACH USER.

Code:
class User:
def __init__(self,Username,email):
self.Username=Username
self.email=email
def greet(self):
return f"hello,{self.Username}."
User1=User("shreya","shreya@gmail.com")
User2=User("swati","swati@gmail.com")
User3=User("Aarushi","Aarushi@gmail.com")
print(User1.greet())
print(User2.greet())
print(User3.greet())

Output:
32. USING PARAMETERIZED CONSTRUCTOR ASSIGN VARIOUS PROPERTIES TO
AN OBJECT AND DISPLAY THOSE PROPERTIES.

Code:
class Student:
def __init__(self, name, age, roll_number, grade):
self.name = name
self.age = age
self.roll_number = roll_number
self.grade = grade
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Roll Number: {self.roll_number}")
print(f"Grade: {self.grade}")
student1 = Student("Shreya", "20", "220216", "A+")
print("Student Information:")
student1.display_info()

Output:
33. CREATE A CLASS THAT KEEPS AN INTERNAL COUNT OF THE INSTANCES
THAT YOU HAVE CREATED USING CLASS.

Code:
class ObjectCounter:
count = 0
def __init__(self):
ObjectCounter.count += 1

Output:
34. CREATE A CLASS THAT KEEPS AN INTERNAL COUNT OF THE INSTANCES
THAT YOU HAVE CREATED USING OBJECT.

Code:
class ObjectCounter:
count = 0
def __init__(self):
self.count += 1

Output:
35. CREATE AN EMPTY CLASS AND DISPLAY THE OBJECT PROPERTIES
CREATING IT OUTSIDE THE EMPTY CLASS.

Code:
class User:
pass
def __init__(self,name,age,project):
self.name=name
self.age=age
self.project=project
User.__init__=__init__
U1=User('shreya','19','python')
print(U1.name)
print(U1.age)
print(U1.project)

Output:
36. CREATE A CLASS CAR WITH THE INSTANCE ATTRIBUTE MAKE,MODEL,YEAR
AND COLOUR. NOW ADD THE FOLLOWING FUNCTIONS:
START, STOP, ACCELERATE AND BRAKE THE CAR.
THE START AND STOP METHODS WILL SIMPLY TAKE THE COLOUR INSTANCE
AS THEIR FIRST ARGUMENT AND INSIDE THESE METHODS MENTION THE
STATE BY THE PROPERTY STARTED BY SETTING IT'S VALUE TRUE IN THE
CASE OF START METHOD AND FALSE IN THE CASE OF STOP METHOD. THEN
THE ACCELERATE METHOD WILL TAKE AN ARGUMENT WHICH WILL
REPRESENT THE INCREMENT OF THE SPEED WHICH OCCURS WHEN YOU
CALL THE METHOD AND FOR THE VALIDATION WE WILL FIRST CHECK IF
THE CAR ENGINE IS STARTED AND RETURN IMMEDIATELY IF NOT. ALSO
CHECK THE SPEED SHOULD NOT BE NEGATIVE. AND FOR THE BRAKE
METHOD THE PROPERTY WOULD BE AGAIN VALUE THAT WE NEED TO MINUS
FROM THE SPEED AND IN BOTH THE METHODS THEY SHOULD DISPLAY THE
MESSAGE AT ZERO STOPPING THE CAR, AT BREAK BREAKING TO THIS
SPEED.

Code:
class Car:
def _init_(self, make, model, year, colour):
self.make = make
self.model = model
self.year = year
self.colour = colour
self.started = False
self.speed = 0
self.max_speed = 200

def start(self, colour):


if self.started:
return f"The car is already running in {self.colour} color."
self.started = True
return f"The car has been started in {self.colour} color."

def stop(self, colour):


if not self.started:
return f"The car is already stopped in {self.colour} color."
self.started = False
self.speed = 0
return f"The car has been stopped in {self.colour} color."

def accelerate(self, increment):


if not self.started:
return "The car is not running, so you can't accelerate."
if increment < 0:
return "Invalid acceleration value. Acceleration should be non-negative."
self.speed = min(self.speed + increment, self.max_speed)
return f"The car's speed is now {self.speed}."

def brake(self, decrement):


if not self.started:
return "The car is not running, so you can't brake."
if decrement < 0:
return "Invalid braking value. Braking should be non-negative."
self.speed = max(self.speed - decrement, 0)
return f"The car's speed is now {self.speed}."

my_car = Car("Toyota", "Camry", 2022, "Blue")


print(my_car.start("Blue"))
print(my_car.accelerate(50))
print(my_car.brake(20))
print(my_car.stop("Blue"))

Output:

You might also like