0% found this document useful (0 votes)
2 views

Python Lab Record 2024

The document provides a comprehensive guide on installing Python on Windows, including steps for adding Python to environment variables. It also includes various Python programming exercises covering input/output, conditional constructs, loops, functions, classes, and user-defined exceptions. Each section contains code examples demonstrating the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Lab Record 2024

The document provides a comprehensive guide on installing Python on Windows, including steps for adding Python to environment variables. It also includes various Python programming exercises covering input/output, conditional constructs, loops, functions, classes, and user-defined exceptions. Each section contains code examples demonstrating the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Q1.

Installing and Setting up the Python


 There are many ways you can get started with setup and installation: you can download
official Python distributions from www. python.org.

Install Python in Windows

Step 1 : Open a browser to the Python website and download the Windows installer.

Step 2 : Double click on the downloaded file and install Python for all users, and ensure that
Step 3 : Python is added to your path. Click on Install now to begin.
Step 4 : After the installation is complete, click Disable path length limit and then Close. Disabling
the path length limit means we can use more than 260 characters in a file path.

Step 5 : Click Close to end the installation.

Running Python in Windows


Step 1 : Open a Command Prompt and type “python” then press Enter.

Open the Python interpreter.

Adding Python to the Environment Variables (optional)


 Skip this step if you selected Add Python to environment variables during installation.
 If you want to access Python through the command line but you didn’t add Python to your
environment variables during installation, then you can still do it manually.
 Before you start, locate the Python installation directory on your system. The following
directories are examples of the default directory paths:
i. C:\Users\user-16\AppData\Local\Programs\Python\Python310-32\
ii. C:\Users\user-16\AppData\Local\Programs\Python\Python310-32\Scripts :
if you didn’t select Install for all users during installation, then the directory will
be in the Windows user path

Q2. Simple programs using input and output.


print("Q1. WAP in Python to input a student rollno, name and mark and display the output")
name = input("\nEnter Your Name Here :")
roll = input("\nEnter your ROll No Here :")
mark= input("\nEnter your mark Here :");
print ("\nRoll No is : "+ roll)
print ("\nMy Name is : " , name)
print ("\nTotal Mark is : " , mark)

print("\n\nQ2. WAP in Python to input numbers by the keyboad")


a = input('\nEnter first number:')
b = input("\nEnter second number:")
sum = float(a) + float(b)
print('\nThe sum of {0} and {1} is {2}'.format(a, b, sum))

print("\n\nQ3. WAP in Python to swap two variables values")


a = input('\nEnter the value of a: ')
b = input('\nEnter the value of b: ')
c=a
a=b
b=c
print('\nThe value of x after swapping: {}'.format(a))
print('\nThe value of y after swapping: {}'.format(b))
OUTPUT LAYOUT

Q3. Programs based on Conditional constructs, if statements, while loop, for


loop, infinite loop, Nested loop.
print("\nQ1. WAP in python to check odd or even number using if condition")
x = int(input("Enter a number: "))
if (x%2==0):
print("\n This number is Even")

print("\nQ2. WAP in python to check out even number using if-else condition")
no =int(input("Enter a number: "))
if (no%2==0): print("\n Even Number")
else: print("\nOdd Number")

print("\nQ3. WAP in python to check passwrd using if-else condition")


password = input("\n\nEnter the password (ist@23) : ")
if password == "ist@23":
print("\nCorrect password")
else:
print("\nIncorrect Password")
print("\nQ4. WAP in python to positive or negative or zero using if…elif else statement")
x = int(input('\nEnter a number : '))

if x > 0:
print("\nPositive number")
elif x == 0:
print("\nZero")
else:
print("\nNegative number")

print("\nQ5. WAP in python to demonstrate nested if statement")


num1 = int(input('\nEnter first number : '))
num2 = int(input('Enter second number: '))

if num1 >= num2:


if num1 == num2:
print('\n',num1, 'and', num2, 'are equal')
else:
print('\n',num1, 'is greater than', num2)
else:
print('\n',num1, 'is smaller than', num2)

print("\nQ6. WAP in Python to find the largest number among the three numbers")
x = input("Enter first number: ")
y = input("Enter second number: ")
z = input("Enter third number: ")
if (x >= y) and (x >= z):
largest = x
elif (y >= x) and (y >= z):
largest = y
else:
largest = z
print("\nThe largest number is : ", largest)

print("\nQ7. WAP in python to find the factorial using while loop")


num = int(input("Enter a number : "))
fact = 1
i=1
while i <= num:
fact = fact * i
i=i+1
print("\nFactorial of ", num, " is ", fact)
print("\nQ8. WAP in python to count the number of even integers in the list using for
loop")
x = [18, 33, 17, 24, 16, 21, 19,28,36]
count = 0
for i in x:
if i % 2 == 0:
count += 1
print("\nTotal count of even numbers is =", count)

print("\nQ9. WAP in python to nested for loop to print multiplication table")


for i in range(1, 11):
# to iterate from 1 to 10
for j in range(1, 11):
# print multiplication
print(i * j, end=' ')
print()

#The infinite loop using while statement: If the condition of while loop is always True, we
get an infinite loop. # press Ctrl + c to exit from the loop

print("\nQ10. WAP in python to demonstrate while infinite loop ")


while True:
num = int(input("Enter an integer number: "))
print("\nThe Multiplication of ",num," is ",20 * num)

OUTPUT LAYOUT

Q4. Programs using break and continue statements


for x in "Anvi Anwesha":
if x== "w":
break
print(x)
print("End break statement ")
# continue statement
for y in "Anvi Anwesha":
if y== "w":
continue
print(y)
print("End Continue statement")

OUTPUT LAYOUT

Q5. Programs using arrays and Strings.


names = ['Kim', 'Sim', 'Bim', 'Rim', 'Jim', 'Anvi']
print("Accessing array of strings in index")
print(names[4])
print(names[0])
print(names[2])
print("Looping in the array of strings ")
for i in names:
print(i)
print("Len of array of strings ")
print(len(names))
print("Append values in the array of strings")
names.append('mamuni')
print(names)

OUTPUT LAYOUT

Q6. Programs using functions pass by object reference


student = {'Bim': 42, 'Anu': 31, 'Anvi': 2}
def test_func(student):
new = {'Chinky':29, 'Chinku':33}
student.update(new)
print("Inside the function: ", student)
return
test_func(student)
print("Outside the function:", student)

OUTPUT LAYOUT
Q7. Programs using default arguments, recursions
# 1. Without parameters, without return statement
def fun():
print("\n\nWelcome to python function ")
fun()
# 2. With Parameters, without return statement
def hello(name):
print("\n Hello " + name)
hello("Anvi")
# 3. Without parameters, with the return statement
def isEven(x):
if (x % 2 == 0):
return "\n This number id Even"
else:
return "\n Not Even number"
even10 = isEven(10)
print(even10)
# 4. With parameters, with return statement
def sum(a, b):
return a + b
total=sum(10,20)
print("\nsum of a and b = ",total)

def multiply(a:int, b:int):


print ("\n Multiplay =" ,a*b)
multiply(5,10)
def inc(n): # Accept an argument, return a value.
return n+1
x = 10
x = inc(x) #reassign the value
print("\nThe value of x =",x)

# Python code to demonstrate call by value


string = "Good Evening."
def sms(string):
string = "Good Morning"
print("\nInside Function:", string)
sms(string)
print("\nOutside Function:", string)

# Python code to demonstrate call by reference


def add_list(a):
a.append(55)
print("\n \nInside Function: ", a)

x = [5,10,15,20,25,30,40,50]
add_list(x)
print("\nOutside Function: ", x)
#Recursive Functions
def rec_sum(n):
if n<=1:
return n
else:
return n + rec_sum(n-1)
y = rec_sum(10)
print("sum of 1 to 10 =",y)
print("To find the factorial of an integer using recursions")
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num = 5
# check if the number is negative
if num < 0:
print("factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is",factorial(num))
OUTPUT LAYOUT

Q8. Simple class programs, constructors, and Inheritance


print("\nExp-1 Program Concept for creating class and object ")

class Employee:
# class variables
dept = 'Marketing'

# constructor to initialize the object

def __init__(self, name, salary):


# instance variables
self.name = name
self.salary = salary

# instance method
def show(self):
print('\nEmployee:', self.name, self.salary, self.dept)

# create first object


emp1 = Employee("Anvi", 9000)
emp1.show()
# create 2nd object
emp2 = Employee("Rinky", 3000)
emp2.show()

# create 3rd object


emp3 = Employee("Chinky", 4000)
emp3.show()

print("\nExp-2 Program Concept for constructor ")


class Student:

def __init__(self, name):


print('Inside Constructor')
self.name = name
print('All variables initialized')

# instance Method
def show(self):
print('Welcome, my name is', self.name)
# create object using constructor
s1 = Student('Anvi Anwesha')
s1.show()

print("\n\nExp-3 Program Concept for Inheritance ")

class Parent:
def __init__(self , name, roll):
self.fname = name
self.rollno = roll
def view(self):
print(self.fname , self.rollno)

class Child(Parent):
def __init__(self , name , roll):
Parent.__init__(self, name, roll)
self.lname = "Ray"
def view(self):
print("\nRoll No:", self.rollno ,"\n Name : " , self.fname , "\n Last Name: " , self.lname, "
\nDept of IST, \nRavenshaw University\nCuttack")
ob = Child("Anvi Anwesha" , '2023')
ob.view()

print("\nExp-4 Program Concept for Class Inheritance")

#Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle
is seating
#capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a
maintenance charge.
#So total fare for bus instance will become the final amount = total fare + 10% of the total fare.

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 30)


print("\nTotal Bus fare is:", School_bus.fare())

OUTPUT LAYOUT
Q9. Programs of Method Overriding, operator overloading, the super() method,
MRO, interfaces.

print("\nExp-1 Program Concept for Method Overriding")


class IST:
def show(self):
print("\nWelcome to You , I am in Department of IST")

class ITM(IST):
def show(self):
print("\nHello, I am in Department of ITM")
print("\nMethod overriding in Python is when you have two methods with the same name that
each perform different tasks.")
r =ITM()
r.show()
r = IST()
r.show()

print("\nExp-2 Program Concept for Operator Overloading")


class anvi:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
p1 = anvi(250, 430)
print("\nThe operator overloading Value: ", p1)

print("\nExp-3 Program Concept for super() method")

class Computer():
def __init__(self, computer, ram, storage):
self.computer = computer
self.ram = ram
self.storage = storage

class Mobile(Computer):
def __init__(self, computer, ram, storage, model):
super().__init__(computer, ram, storage)
self.model = model

Apple = Mobile('Apple', 16, 512, 'iPhone')


print("\nThe mobile is:", Apple.computer)
print("The RAM is:", Apple.ram)
print("The Storage is:", Apple.storage)
print("The Model is:", Apple.model)

print("\nExp-4 Program Method Resolution Order(MRO) is a concept used in inheritance. ")


class A:
def method(self):
print("\n WELCOME TO YOU IN MRO Concept")

class B:
pass

class C(B, A):


pass

c = C()
c.method()

print("\nExp-5 Program Concept for Interface ")

import abc
class Myi_face( abc.ABC ):
def disp( ):
pass

class Mydemo(Myi_face):
def disp(s):
print("\nThis is the Interface programming example. ")
o1=Mydemo()
o1.disp()

OUTPUT LAYOUT

Q10. Define Python user-defined exceptions

print("\n\nExample-1 : User-defined exception class")

class VotingPerson(Exception):

def __inti__(self, name, id, age):


self.name = name
self.id = id
self.age = age
try:
name = input("Enter the Name : ")
id = int(input("Enter the Id_No : "))
age = int(input("Enter the Age : "))
if age<18 :
raise VotingPerson
vote1 = VotingPerson(name,id,age)
print("\nThank you for Voting")
except Exception as e:
print("\n\nSorry you are not eligible for voting",e)

print("\n\nExample-2 : Deriving Error from Super Class Exception (Multiple Inheritance)")


# base class
class PasswordError(Exception):
pass

# If an invalid character is entered by the user


class CharacterError(PasswordError):
def __init__(self, e):
# merge the character to the message
temp = "Password cannot have "+e
# send it to superclass
super().__init__(temp);

# confirm password does not match password


class DifferentPasswordsError(PasswordError):
def __init__(self):
super().__init__("Please enter same password")

# take username and passwords


user_name = input("Enter Username : ")
password = input("Enter Password : ")
for i in range(0, len(password)):
e = password[i]
# returns int value of character
t = ord(password[i])
if t in range(48, 58):
pass
elif t in range(65, 91):
pass
elif t in range(97, 123):
pass
else:
raise CharacterError(e)

confirm_password = input("\nEnter password again for confirmation : ")


if(confirm_password != password):
raise DifferentPasswordsError
else:
print("\nSign Up Successfully Done")

You might also like