Uploaded by rebeena6988

Python Lab Manual 2023

advertisement
LIST OF EXPERIMENTS
1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same. (Electricity Billing, Retail shop billing, Sin series,
weight of a motorbike, Weight of a steel bar, compute Electrical Current in Three Phase
AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of
two variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns, pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library / Materials required for construction of a building -operations of list and tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc, operations of Sets and
Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of
shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas,
numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to
another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero
error, voters age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
1|P a ge
EX:NO:1A) Identification and solving of simple real life or scientific or Technical
problems and developing flow chart for Electricity billing
Aim:
To develop the Flow chart to solve electricity billing
Algorithm:
1.
2.
3.
4.
5.
6.
start
Declare variables unit and usage.
Process the following,
When the unit is less than or equal to 100 units,calculate usage=unit*5
When the unit is between 100 to 200 units.calculate usage=(100*5)+((unit-100)*7)
When the unit is between 200 to 300 units,calculate usage=(100*5)+(100*7)+((unit200*10)
7. When the unit is above 300 unit,calculate usage=(100*5)+(100*7)+(100*10)=((unit300)*15)
8. For further,no additional change will be calculated
9. Display the amount”usage”to the user.
10. Stop.
2|P a ge
Result:
Thus the Flow chart for electricity billing was developed successfully.
3|P a ge
EX:NO:1B) Identification and solving of simple real life or scientific or Technical problems
and developing flow chart for Retail Shop Billing.
Aim:
To develop the flow chart for Retail Shop Billing.
Algorithm:
1.
2.
3.
4.
5.
6.
start
Declare the variable unit and usage.
Process Assign the values for a1,a2 and a3,a1=15,a2=120,a3=85.
Process the following amount=(item 1*a1)+(item 2*a2)+(item 3*a3)>
Display the values of “amount”.
Stop
4|P a ge
RESULT:
Thus the flow chart for Retail Shop Billing was developed successfully.
5|P a ge
EX:NO:1C) Identification and solving of simple real life or scientific or Technical problems
and developing flow chart for Sin Series.
Aim:
To develop the flow chart for Sin Series.
Algorithm :
1. Start
2. Declare the variables which are required to process.
3. Read the input like the value of x in radians and n where n is a number up to which want
to print the sun of series.
4. For first item,
Sum=x;
P=1(variable P is used for denominator)
num=x(variable num is used for numerator)
Power=1
5. For next item,
Num=num *(-*2);
Power=Power+2;
6|P a ge
Result:
Thus the flow chart for Sin Series was developed successfully.
7|P a ge
EX:NO:1D) Identification and solving of simple real life or scientific or technical
problems and developing flow charts for weight of a Motorbike
AIM:
To develop the flowchart to solve weight of a motarbike.
Algorithm:
1. start
2. Declare variables weight motar,pr ,eoff and weight
3. Read the values of weightmotar,pr and eoff.
4. Process the following:
(a)weight=weightmotar +pr +eoff.
5. Display “motorbike weight result is weight”.
6. Stop
Result:
Thus the flowchart for weight of a motorbike was developed successfully.
8|P a ge
EX:NO:1E) Identification and solving of simple real life or scientific or technical
problems and developing flow charts for weight of a Weight of a Steel bar
AIM:
To develop the flow chart for weight of a steel bar.
Algorithm:
1.
2.
3.
4.
5.
6.
start
declare the variables d, length and weight.
weight=(d2/162)*length
Read the value d and length.
Display the value of weight
stop
9|P a ge
Result:
Thus the flowchart for weight of a steel bar was developed successfully.
10 | P a g e
EX:NO:1F) Identification and solving of simple real life or scientific or technical
problems and developing flow charts for weight of a compute electrical current in three –
phase AC circuit
AIM:
To develop the flowchart to solve compute electrical in Three-phase AC circuit.
Algorithm:
1.
2.
3.
4.
5.
6.
start
Declare variables pf,I ,v and p.
Read the values of pf I and v.
p=v3*pf*I*v
Display “The result is p”.
stop
11 | P a g e
Result:
Thus the Flowchart for compute electrical current in three-phase AC circuit was
developed successfully.
12 | P a g e
EX:NO:2A) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Exchange two variables)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Get X and Y from console using input() function
2. Assign temp =x
3. Copy the value from y to x by x=y
4. Copy the value from temp to y by y=temp
5. Print the values
PROGRAM/SOURCE CODE:
x = input('Enter value of x: ')
y = input('Enter value of y: ')
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
OUTPUT:
Enter value of x: 10
Enter value of y: 5
The value of x after swapping: 5
The value of y after swapping: 10
RESULT:
Thus the python program for distance between two points was written and executed
successfully.
13 | P a g e
EX:NO:2B) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Distance Between Two Points)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Get x1 from console using input() function
2. Get x2
3. Get y1
4. Get y2
5. Calculate result using ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
6. Print the result inside print() function
PROGRAM/SOURCE CODE:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
OUTPUT:
enter x1 : 4
enter x2 : 0
enter y1 : 6
enter y2 : 6
distance between (4, 0) and (6, 6) is : 4.0
RESULT:
Thus the python program for distance between two points was written and executed
successfully.
14 | P a g e
EX:NO:2C) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Circulate the values of n variables)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Start.
2. Initialize list as 1,2,3,4,5.
3. Deque the element from list and stored in list1.
4. Rotate the first three values in list1.
5. Print list1.
6. Stop.
PROGRAM/SOURCE CODE:
no_of_terms = int(input("Enter number of values : "))
#Read values
list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values : 3
Enter integer : 10
Enter integer : 20
Enter integer : 30
Circulating the elements of list [10, 20, 30]
[20, 30, 10]
[30, 10, 20]
[10, 20, 30]
RESULT:
Thus the program for circulating n variables was written and executed successfully.
15 | P a g e
EX:NO:2D) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Different number data types in python)
AIM
Write a program to demonstrate different number data types in python
ALGORITHM:
1.
2.
3.
4.
5.
6.
Start.
Initialize list as a,b,c
Print type of variable a
Print type of variable b
Print type of variable c
Stop.
PROGRAM:
a=10; #Integer Datatype
b=11.5; #Float Datatype
c=2.05j; #Complex Number
print("a is Type of",type(a)); #prints type of variable a
print("b is Type of",type(b)); #prints type of variable b
print("c is Type of",type(c)); #prints type of variable c
OUTPUT
RESULT:
Thus the program was runs successfully executed
16 | P a g e
EX:NO:2E) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (To Perform different arithmetic operations on numbers in python).
AIM:
Write a program to perform different arithmetic operations on numbers in python.
ALGORITHM:
1.
2.
3.
4.
5.
6.
7.
8.
Start.
Get a,b
Print the Addition of a+b
Print the Addition of a-b
Print the Addition of a*b
Print the Addition of a/b
Print the Addition of a%b
Stop
PROGRAM:
a=int(input("Enter a value")); #input() takes data from console at runtime as string.
b=int(input("Enter b value")); #typecast the input string to int.
print("Addition of a and b ",a+b);
print("Subtraction of a and b ",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b ",a/b);
print("Remainder of a and b ",a%b);
print("Exponent of a and b ",a**b); #exponent operator (a^b)
print("Floar division of a and b ",a//b); # floar division
OUTPUT:
RESULT:
Thus the program was runs successfully executed
17 | P a g e
EX:NO:2F) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (To create, concatenate and print a string and accessing substring from a
given string)
AIM :
Write a program to create, concatenate and print a string and accessing substring from a
given string
ALGORITHM:
1.
2.
3.
4.
5.
6.
Start.
Get s1,s2
Print the first string s1
Print the second string s2
Print the concatenations of two strings
Print the substring of given string
PROGRAM:
s1=input("Enter first String : ");
s2=input("Enter second String : ");
print("First string is : ",s1);
print("Second string is : ",s2);
print("concatenations of two strings :",s1+s2);
print("Substring of given string :",s1[1:4]);
OUTPUT:
RESULT:
Thus the program was runs successfully executed
18 | P a g e
EX:NO:2F) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Write a python script to print the current date in following format “Sun May
29 02:26:23 IST 2017”
AIM:
Write a python script to print the current date in following format “Sun May 29 02:26:23
IST 2017”
ALGORITHM:
1.
2.
3.
4.
Start.
Get ltime
Import the local time using localtimefunction()
Print the local time
PROGRAM:
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime));
OUTPUT:
RESULT:
Thus the program was runs successfully executed
19 | P a g e
EX:NO:3A) Scientific Problems Using Conditional And Iterative Loops
(Pyramid Number Pattern)
AIM:
To write a python program for pyramid number pattern using conditional and iterative
loops.
ALGORITHM:
1. Start
2. Initialize n=5
3. For i in range upto n
4. In another loop upto n-i-1
5. Inside print leave spaces
6. For k in range upto 2*i+1
7. Print the k+1 and space
PROGRAM/SOURCE CODE:
n=5
for i in range(n):
for j in range(n-i-1):
print(' ',end=' ')
for k in range(2*i+1):
print(k+1,end=' ')
print()
OUTPUT:
1
123
12345
1234567
123456789
RESULT:
Thus the program for pyramid number pattern using conditional and iterative loops was
written and executed successfully.
20 | P a g e
EX:NO:3B) Scientific Problems Using Conditional And Iterative Loops
(Simple star Pattern)
AIM:
To write a python program for simple number pattern using conditional and iterative
loops.
ALGORITHM:
1. Start
2. define the function name as pattern with the parameter n.
3. a) Initialize x with 0.
b) for i in range 0 to n.
c) x increased by 1.
d) for j in range 0 to i+1.
e) print(x,and=' ')
f) print(“\n)
4. call the parameter of the function pattern with parameter 5.
5. stop.
PROGRAM/SOURCE CODE:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('*', end="")
print('')
OUTPUT:
21 | P a g e
EX:NO:4A)
Implementing Real Time Application Using List
AIM:
To write a python program for insert remove from the list
ALGORITHM:
1. Define a list
2. Append the values in the list
3. Inserting elements in the given index using insert function
4. Remove the given element from list using remove
5. Pop the element from the list
6. Delete the list.
Program/Source Code:
pets = ['cat', 'dog', 'rat', 'pig', 'tiger']
snakes=['python','anaconda','fish','cobra','mamba']
print("Pets are :",pets)
print("Snakes are :",snakes)
animals=pets+snakes
print("Animals are :",animals)
snakes.remove("fish")
print("updated Snakes are :",snakes)
OUTPUT:
RESULT:
Thus the python program for list was successfully executed.
22 | P a g e
EX:NO:4B)
Implementing Real Time Application Using Tuples (To demonstrate
working with tuples in python).
AIM:
Write a program to demonstrate working with tuples in python.
ALGORITHM:
1. Define Tuples using tuple function or using ()
2. Accessing tuple elements using its index position
3. Getting length of a tuple using len function
4. Printing items present in tuples using for loop
5. Append the element in list using append function
6. Delete the tuple using del function
PROGRAM/SOURCE CODE:
T = ("apple", "banana", "cherry","mango","grape","orange")
print("\n Created tuple is :",T)
print("\n Second fruit is :",T[1])
print("\n From 3-6 fruits are :",T[3:6])
print("\n List of all items in Tuple :")
for x in T:
print(x)
if "apple" in T:
print("\n Yes, 'apple' is in the fruits tuple")
print("\n Length of Tuple is :",len(T))
23 | P a g e
OUTPUT
RESULT:
Thus the program for tuples was written and executed successfully.
EX:NO:4C) Implementing Real Time/Technical Application Using Dictionaries(To
demonstrate working with dictionaries in python)
24 | P a g e
AIM:
Write a program to demonstrate working with dictionaries in python
ALGORITHM:
1. Define dictionaries by giving key and value pairs
2. Copy elements from one dictionary to another using copy command
3. Update values using update function
4. Access elements from dictionary using items() function
5. Getting length of dictionary from len function
6. Accessing data type of element using type() function
7. Delete element by using pop function
8. Remove all elements using clear() function
9. Creating dictionary by using dict() and zip() function
10. Getting element using get() function.
PROGRAM/SOURCE CODE:
dict1 = {'StdNo':'532','StuName': 'Naveen', 'StuAge': 21, 'StuCity': 'Hyderabad'}
print("\n Dictionary is :",dict1)
#Accessing specific values
print("\n Student Name is :",dict1['StuName'])
print("\n Student City is :",dict1['StuCity'])
#Display all Keys
print("\n All Keys in Dictionary ")
for x in dict1:
print(x)
#Display all values
print("\n All Values in Dictionary ")
for x in dict1:
print(dict1[x])
#Adding items
dict1["Phno"]=85457854
25 | P a g e
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Change values
dict1["StuName"]="Madhu"
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Removing Items
dict1.pop("StuAge");
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Length of Dictionary
print("Length of Dictionary is :",len(dict1))
#Copy a Dictionary
dict2=dict1.copy()
#New dictoinary
print("\n New Dictionary is :",dict2)
#empties the dictionary
dict1.clear()
print("\n Uadated Dictionary is :",dict1)
26 | P a g e
OUTPUT
RESULT:
Thus the program for components of car using dictionaries was written and executed
successfully.
27 | P a g e
EX.No.6A)
FACTORIAL OF A NUMBER USING FUNCTIONS
AIM:
To write a python program to find factorial of a number by using functions.
ALGORITHM:
1. Start the program
2. Define a function to find factorial
3. The function name is recur_factorial(n)
4. Inside the function check for n value
a) If n is equal to 1 return 1 else call the function
b) Get input for finding factorial for a number
c) Check for number if it is negative print some message
d) Else if number is 0 then the factorial for 0 is 1 will be printed
e) Else Call the Function
PROGRAM/SOURCE CODE:
def recurfactorial(n):
if n == 1:
return n
else:
return n*recurfactorial(n-1)
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recurfactorial(num))
OUPUT:
Enter a number: 5
The factorial of 5 is 120
RESULT:
Thus the program for factorial of number using function was written and executed
successfully
28 | P a g e
Ex.No.6 B)
TO FIND A LARGEST OF THREE NUMBERS
AIM:
To write a python program to find largest of three numbers
ALGORITHM:
1. Define the function
2. Assign the element
3. Compare the elements with max in for loop
4. Return the maximum elements
5. Declare and initialize
6. Call the function inside print statement
PROGRAM/SOURCE CODE:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
OUTPUT
RESULT:
Thus the program for largest number using function was written and executed
successfully.
29 | P a g e
Ex.No.6C)
AREA OF SHAPE USING FUNCTION
AIM:
To write a python program to find the square of a shape using function
ALGORITHM:
1. Define function named calculate_area(name)
2. Inside function convert all characters into lower case
3. If name is rectangle get length and breadth and calculate area of rectangle using area=l*b
and print the result
4. If name is square get side length and calculate area of square using area=s*s and print the
result
5. If name is triangle get height and breadth length and calculate area of triangle using
area=0.5 * b * h and print the result
6. If name is circle get radius and calculate area of circle using area=pi * r * r and print the
result
7. If name is parallelogram get base and height and calculate area of parallelogram using
area=b * h and print the result
8. Else print “Shape is not available”
PROGRAM/SOURCE CODE:
defcalculate_area(name):\
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print(f"The area of rectangle is {rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"The area of square is {sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print(f"The area of triangle is {tri_area}.")
30 | P a g e
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print(f"The area of Circlee is {circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
if name == " main " :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 56
Enter rectangle's breadth: 70
The area of rectangle is 3920.
RESULT:
Thus the program for area of a shape using function was written and executed
successfully
31 | P a g e
To Convert Temperatures to and from Celsius, Fahrenheit
Ex.No.6D)
AIM :
Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
[Formula: c/5 = f-32/9]
ALGORITHM :
1
Print the Convert temperatures from Celsius to Fahrenheit
2
Print the Convert temperatures from Fahrenheit to Celsius
3
Get opt
4
Get cel
5
First enter the value of temperature in Celsius.
6
Calculate the formula of: f=(c*1.8)+32, convert Celsius to Fahrenheit.
7
Print the temperature in Fahrenheit.
PROGRAM/SOURCE CODE:
print("Options are \n")
print("1.Convert temperatures from Celsius to Fahrenheit \n")
print("2.Convert temperatures from Fahrenheit to Celsius \n")
opt=int(input("Choose any Option(1 or 2) : "))
if opt == 1:
print("Convert temperatures from Celsius to Fahrenheit \n")
cel = float(input("Enter Temperature in Celsius: "))
fahr = (cel*9/5)+32
print("Temperature in Fahrenheit =",fahr)
elif opt == 2:
print("Convert temperatures from Fahrenheit to Celsius \n")
fahr = float(input("Enter Temperature in Fahrenheit: "))
cel=(fahr-32)*5/9;
print("Temperature in Celsius =",cel)
else:
print("Invalid Option")
32 | P a g e
OUTPUT
RESULT:
Thus the program for to convert temperatures to and from Celsius, Fahrenheit. [Formula:
c/5 = f-32/9] was written and executed successfully
33 | P a g e
To Print Prim Numbers less than 20
Ex.No.6D)
AIM :
Write a python program to print prim numbers less than 20
ALGORITHM:
1
Print the Prime numbers between 1 and 20
2
Initialize ulmt=20
3
for num in range 20
4
Print the prime numbers 3 to 20
5
Stop
PROGRAM/SOURCE CODE:
print("Prime numbers between 1 and 20 are:")
ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
OUTPUT
RESULT:
Thus the program for to print the prime numbers less than 20 was written and executed
successfully
34 | P a g e
EX:NO: 7A)
IMPLEMENTING PROGRAMS USING STRINGS
(REVERSE OF A STRING)
AIM:
To write a python program for reverse of a string
ALGORITHM:
1. Get the input string from console using input() function
2. Define empty string rstr1
3. Define index as length of string
4. If the index value > 0 then entering into while loop
5. Add every character from index-1 to rstr1
6. Decrement index values by 1
7. Print reversed string
PROGRAM/SOURCE CODE:
str1=input("A string =")
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index – 1
print("Reverse",rstr1)
OUTPUT:
A string = python
Reverse nohtyp
RESULT:
Thus the program for reverse of a string was written and executed successfully.
35 | P a g e
EX:NO: 7B)
IMPLEMENTING PROGRAMS USING STRINGS(PALINDROME)
AIM:
To write a python program for palindrome of a string
ALGORITHM:
1. Get the input string from console using input() function
2. In if statement checks if string is equal to string[::-1] means: Start at the end (the
minus does that for you), end when nothing's left and walk backwards by 1
3. Then print the letter is palindrome
4. Else print the letter is not palindrome
PROGRAM/SOURCE CODE:
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")
OUTPUT:
Enter a letter:madam
The letter is a palindrome
RESULT:
Thus the program for palindrome of a string was written and executed successfully.
36 | P a g e
EX:NO: 7C) IMPLEMENTING PROGRAMS USING STRINGS
(CHARACTER COUNT)
AIM:
To write a python program for character count of a string
ALGORITHM:
1. Get the string from console using input()
2. Initialize total as 0
3. In for loop from staring to length of string
4. Increment total by 1 inside the loop
5. Print the total number of character in string using print() function
PROGRAM/SOURCE CODE:
str1 = input("Please Enter your Own String : ")
total = 0
for i in range(len(str1)):
total = total + 1
print("Total Number of Characters in this String = ", total)
OUTPUT:
Please Enter your Own String : Python
Total Number of Characters in this String = 6
RESULT:
Thus the program for character count of a string was written and executed successfully.
37 | P a g e
EX:NO: 7D)
IMPLEMENTING PROGRAMS USING FUNCTION(to define a module
and import a specific function in that module to another program)
AIM:
Write a python program to define a module and import a specific function in that module
to another program.
ALGORITHM:
1. Start
2. define Add(a,b):
3. define Sub(a,b):
4. define Mul(a,b):
5. Get num1
6. Get num2
7. Print the addition a,b
8. Print the subtraction a,b
9. stop
PROGRAM/SOURCE CODE:
arth.py
''' Arithmetic Operations Module with Multiple functions'''
def Add(a,b):
c=a+b
return c
def Sub(a,b):
c=a-b
return c
def Mul(a,b):
c=a*b
return c
week15.py
'''Write a python program to define a module and import a specific function in that
module to another program.'''
from arth import Add
num1=float(input("Enter first Number : "))
num2=float(input("Enter second Number : "))
print("Addition is : ",Add(num1,num2))
print("Subtraction is : ",Sub(num1,num2))
38 | P a g e
OUTPUT
RESULT:
Thus the program for implement the module function was written and executed
successfully.
39 | P a g e
EX:NO: 7E)
IMPLEMENTING PROGRAMS USING FUNCTION (To define a module to
find Fibonacci Numbers and import the module to another program)
AIM:
Write a python program to define a module to find Fibonacci Numbers and import the module to
another program.
ALGORITHM:
1. Start
2. This module defines two functions: fib(n) which returns the n-th Fibonacci number
and fib_sequence(n) which returns a list of the first n Fibonacci numbers.
3. This program first imports the fibonacci module using the import statement.
4. Import the Fibonacci module
5. Define Fib()
6. Initialize a,b
7. Get num
8. Print the addition a,b
9. Print the subtraction a,b
10. stop
PROGRAM/SOURCE CODE:
fibonacci.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end =" ")
a, b = b, a+b
week14.py
'''Write a python program to define a module to find Fibonacci Numbers and import the
module to another program'''
#import fibonacci module
import fibonacci
num=int(input("Enter any number to print Fibonacci series "))
fibonacci.fib(num)
40 | P a g e
OUTPUT
RESULT:
Thus the program for implement the module function was written and executed
successfully.
41 | P a g e
EX:NO: 7D)
IMPLEMENTING PROGRAMS USING FUNCTION (to convert an integer
to a roman numeral)
AIM:
Write a Python class to convert an integer to a roman numeral.
ALGORITHM:
1. Import the class irconvert
2. Initialize the num_map with values
3. Get num
4. Print the Roman number
5. stop
PROGRAM/SOURCE CODE:
week18.py
class irconvert:
num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),(50, 'L'),
(40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
def num2roman(self,num):
roman = ''
while num > 0:
for i, r in self.num_map:
while num >= i:
roman += r
num -= i
return roman
num=int(input("Enter any Number :"))
print("Roman Number is : ",irconvert().num2roman(num))
Output:
42 | P a g e
EX:NO: 8A) IMPLEMENTING PROGRAM USING WRITTEN MODULES AND
PYTHON STANDARD LIBRARY(PANDAS)
AIM:
To write a python program using pandas libaray
ALGORITHM:
6. Install the needed library using pip install pandas
7. Import the needed libraries
8. Initialize the list with values
9. Series used to create a one-dimensional data structure which can store different
types of data
10. Create series from dictionaries
11. Printing sliced value
12. Getting index position of element using index() function
13. Print the median of series using median() function
14. Random function used to select random values from series
15. Head function used to get the elements from top of series
16. Tail function used to get the element from bottom of series
PROGRAM/SOURCE CODE:
#To use pandas first we have to import pandas
import pandas as pd
importnumpy as np
A=['a','b','c','d','e']
df=pd.Series(A)
print(df)
data = np.array(['g','o','e','d','u','h','u','b'])
data
ser = pd.Series(data)
print(ser)
s1 = pd.Series(np.random.random(5) , index=['a', 'b', 'c', 'd', 'e'] )
print(s1)
43 | P a g e
data = {'pi': 3.1415, 'e': 2.71828} # dictionary
print(data)
s3 = pd.Series( data )
print(s3)
s1 = pd.Series(np.random.random(5) )
print(s1)
s1[3] # returns 4th element
s1[:2] #First 2 elements
print( s1[ [2,1,0]])
print(s1.index)
print("Median:" , s1.median())
s1[s1 > s1.median()]
s5 = pd.Series (range(6))
print(s5)
print(s5[:-1])
print(s5[1:])
s5[1:] + s5[:-1]
mys = pd.Series( np.random.randn(5))
print(mys)
print(mys.empty)
print(mys.head(2))
print(mys.tail(2))
print(mys.values)
print(mys.dtype)
44 | P a g e
OUTPUT:
0 a
1 b
2 c
3 d
4 e
dtype: object
0 g
1 o
2 e
3 d
4 u
5 h
6 u
7 b
dtype: object
a 0.060292
b 0.813180
c 0.267351
d 0.827797
e 0.605398
dtype: float64
{'pi': 3.1415, 'e': 2.71828}
pi 3.14150
e 2.71828
dtype: float64
0 0.386199
1 0.546025
2 0.168450
3 0.916291
4 0.860689
dtype: float64
2 0.168450
1 0.546025
0 0.386199
dtype: float64
RangeIndex(start=0, stop=5, step=1)
Median: 0.5460246240927344
0 0
1 1
2 2
3 3
4 4
5 5
dtype: int64
0 0
1 1
2 2
3 3
4 4
dtype: int64
1 1
2 2
3 3
4 4
5 5
dtype: int64
0 1.710777
1 0.107771
2 1.194663
3 0.442142
4 -1.006500
dtype: float64
False
0 1.710777
1 0.107771
dtype: float64
3 0.442142
4 -1.006500
dtype: float64
[ 1.71077658 0.10777064 1.19466255
0.4421425 -1.00649965]
float64
RESULT:
Thus the program using modules of pandas was written and executed successfully.
45 | P a g e
EX:NO: 8B) IMPLEMENTING PROGRAM USING WRITTEN MODULES AND
PYTHON STANDARD LIBRARY (NUMPY)
AIM:
To write a python program using numpylibaray
ALGORITHM:
1. Install the needed library using pip install pandas
2. Import the needed libraries
3. Initialize the array with values
4. Accessing array elements using its index position
5. Modify the element directly by using it index position
6. Printing sliced value
7. We can make the same distinction when accessing columns of an array
8. Calculate sum from sum() function
PROGRAM/SOURCE CODE:
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a))
print(a)
print(a[0], a[1], a[2])
a[0]=5
print(a)
b = np.array([[1,2,3],[4,5,6]])
print(b)
print(b.shape)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array
print(a.shape)
b = a[1:, 2:]
print(b)
46 | P a g e
row_r1 = a[1, :]
# Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
print(row_r1)
print(row_r1.shape)
print(row_r2)
print(row_r2.shape)
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)
print(col_r2, col_r2.shape)
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]])
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
print(x)
print(y)
print(x + y)
x = np.array([[1,2],[3,4],[8,9]])
print(np.sum(x))
print(np.sum(x, axis=0))
print(np.sum(x, axis=1))
print(x.T)
47 | P a g e
OUTPUT:
<class 'numpy.ndarray'>
[[ 2]
[1 2 3]
[ 6]
123
[10]] (3, 1)
[5 2 3]
[[1 2 3]
[1 4 5]
[4 5 6]]
[1 4 5]
(2, 3)
[[1 2]
[[ 1 2 3 4]
[3 4]]
[ 5 6 7 8]
[[5 6]
[ 9 10 11 12]]
[7 8]]
(3, 4)
[[ 6 8]
[[ 7 8]
[10 12]]
[11 12]]
27
[5 6 7 8]
[12 15]
(4,)
[ 3 7 17]
[[5 6 7 8]]
[[1 3 8]
(1, 4)
[2 4 9]]
[ 2 6 10] (3,)
RESULT:
Thus the program using modules of numpy was written and executed successfully.
48 | P a g e
EX:NO: 9A) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
FILE HANDLING(COPY ONE FILE TO ANOTHER)
AIM:
To write a python program to copy the contents of file from one to another file
ALGORITHM:
1. Enter the name of source and target file to copy in console
2. Open the file with read accessing rights
3. The file to write open with write accessing rights
4. For every line in source file write the content in destination file
5. Close the files
6. Check the condition (Y/N) for displaying content
7. If Y then open the file with read permission
PROGRAM/SOURCE CODE:
print("Enter Name of Source and Target File: ", end="")
sfile = input()
tfile = input()
with open(sfile, "r") as shandle:
with open(tfile, "w") as thandle:
for line in shandle:
thandle.write(line)
shandle.close()
thandle.close()
print("\nFile Copied!")
print("\nWant to Display the Content (y/n) ? ", end="")
chk = input()
if chk.lower()=='y':
with open(tfile, "r") as fhandle:
for line in fhandle:
print(line, end="")
fhandle.close()
print()
49 | P a g e
OUTPUT:
E:\Python 1st year\mathavi.txt
Enter the Name of Target File:
E:\Python 1st year\mathavi.txt
File Copied Successfully!
RESULT:
Thus the python program to copy the contents of file from one to another file was written
and executed successfully.
50 | P a g e
EX:NO: 9B) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
FILE HANDLING(WORD COUNT)
AIM:
To write a python program to count the number of words in a file
ALGORITHM:
1. Initialize the count as zero
2. Open the file with read permission
3. For every line in file
4. Split the words using split()
5. Increment the count value as count = count + len(words)
6. Close the file
PROGRAM/SOURCE CODE:
count = 0;
file = open("E:\ Python 1st year\mathavi.txt", "r")
for line in file:
words = line.split(" ");
count = count + len(words);
print("Number of words present in given file: " + str(count));
file.close();
OUTPUT:
Number of words present in given file: 40
RESULT:
Thus the python program to count the number of words in a file was written executed
successfully.
51 | P a g e
EX:NO: 9C) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
FILE HANDLING(LONGEST WORD)
AIM:
To write a python program to find longest file in word
ALGORITHM:
1. Define the function longest_words with parameter file name
2. Open the file with read permission
3. Read and split the words in file
4. Find maximum words length word in file using len(max(words, key=len))
5. Print the longest word in file
PROGRAM/SOURCE CODE:
def longest_words(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_words('E:\ Python 1st year\mathavi.txt'))
OUTPUT:
["'FrontStreeringAndSuspension',", "'FrontStreeringAndSuspension',"]
RESULT:
Thus the python program to find longest word in a file was written executed successfully.
52 | P a g e
EX:NO: 10A) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING (DIVIDE BY ZERO ERROR)
AIM:
To write a python program to handle exceptions for divide by zero
ALGORITHM:
1. Get the values of n,d,c from console
2. Inside try write division rule and print quotient
3. In Except throw Zero DivisionError
4. Inside except print Division by zero error message
PROGRAM/SOURCE CODE:
n=int(input("Enter the value of n:"))
d=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")
OUTPUT:
Enter the value of n:4
Enter the value of d:10
Enter the value of c:2
Quotient: 0.5
RESULT:
Thus the python program for divide by zero using exception handling was written
executed successfully.
53 | P a g e
EX:NO: 10B) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING(VOTERS AGE VALIDITY)
AIM:
To write a python program for voters age validity using exception handling
ALGORITHM:
1. Define function main()
2. Inside function use try block
3. Inside try block get the age value
4. Then check if age>18 print eligible to vote
5. Else print not eligible to vote
6. In except block print error default error message
7. Inside finallythe code to be executed whether exception occurs or not. Typically for
closing files and other resources
8. Call the main() function
PROGRAM/SOURCE CODE:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except ValueError as err:
print(err)
finally:
print("Thank you")
main()
OUTPUT:
Enter your age21
Eligible to vote
Thank you
RESULT:
Thus the python program for voters age validity using exception handling was written
executed successfully.
54 | P a g e
EX:NO: 10C) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING(STUDENT MARK VALIDATION)
AIM:
To write a python program for student mark validation using exception handling
ALGORITHM:
1) Get the name from console
2) Assign length of name to a
3) If the name is not numeric then print letter is not string
4) Else raise type error as “letter is numeric only strings are allowed”
5) Create empty list as mark_list[]
6) Inside for loop upto range 5
7) Get the mark and append in mark_list
8) Inside for loop check the mark is between 0 to 100
9) If yes then print “mark is accepted”
10) Else raise ValueError "mark should lies between 0 to 100"
PROGRAM/SOURCE CODE:
name=input("Enter name of the student")
isnum=True
a=len(name)
print(a)
for i in range(0,a):
if name[i].isnumeric()!=isnum:
print("letter",i,"is string")
else:
raise TypeError("letter is numeric:Only strings are allowed")
mark_list=[]
for i in range(5):
mark=input("Enter mark:")
mark_list.append(mark)
print(mark_list)
55 | P a g e
for i in mark_list:
x=int(i)
if(0<=x<=100):
print(x)
print("mark list is accepted")
else:
raise ValueError("mark should lies between 0 to 100")
OUTPUT:
= RESTART:
C:\Users\HP\AppData\Local\Programs\Pyth
on\Python37-32\exce stu.py =
['12', '3', '56', '7', '3']
Enter name of the student sat
mark list is accepted 3
4
mark list is accepted 56
letter 0 is string
mark list is accepted 7
letter 1 is string
mark list is accepted 3
letter 2 is string
mark list is accepted 4
letter 3 is string
4
Enter mark:12
['12']
= RESTART:
C:\Users\HP\AppData\Local\Programs\Pyth
on\Python37-32\exce stu.py =
Enter mark:3
Enter name of the student 7hgg
['12', '3']
5
Enter mark:56
letter 0 is string
['12', '3', '56']
Traceback (most recent call last):
Enter mark:7
File
"C:\Users\HP\AppData\Local\Programs\Pyt
hon\Python37-32\exce stu.py", line 9, in
<module>
['12', '3', '56', '7']
Enter mark:3
56 | P a g e
12
raise TypeError("letter is numeric:Only
strings are allowed")
Enter mark:6
['123', '6']
TypeError: letter is numeric:Only strings are
allowed
Enter mark:89
>>>
['123', '6', '89']
= RESTART:
C:\Users\HP\AppData\Local\Programs\Pyth
on\Python37-32\exce stu.py =
Enter mark:10
['123', '6', '89', '10']
Enter mark:76
Enter name of the student sat
['123', '6', '89', '10', '76']
4
Traceback (most recent call last):
letter 0 is string
letter 1 is string
letter 2 is string
letter 3 is string
Enter mark:123
File
"C:\Users\HP\AppData\Local\Programs\Pyt
hon\Python37-32\exce stu.py", line 21, in
<module>
raise ValueError("mark should lies
between 0 to 100")
ValueError: mark should lies between 0 to
100
['123']
RESULT:
Thus the python program for student mark validation using exception handling was
written and executed successfully
57 | P a g e
EX:NO: 11)
EXPLORING PYGAME TOOL
AIM:
To write a python program for exploring pygame tool.
ALGORITHM:
1. Import the needed libraries
2. Initialize pygame by init()
3. Set up the drawing window with height and width as parameters
4. Run until the user asks to quit by running=True
5. Inside while check whether the user click the window close button. If yes then Quit
the pygame
6. Fill the background with white fill(255,255,255)
7. Then draw a solid blue circle in the center
8. Flip the display
PROGRAM/SOURCE CODE:
import pygame
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([500, 500])
# Run until the user asks to quit
running = True
while running:
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the background with white
screen.fill((255, 255, 255))
# Draw a solid blue circle in the center
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
# Flip the display
pygame.display.flip()
58 | P a g e
# Done! Time to quit.
pygame.quit()
OUTPUT:
RESULT:
Thus the python program for exploring pygame was written executed successfully.
59 | P a g e
EX:NO: 12A)
DEVELOPING GAME ACTIVITY USING PYGAME
(BOUNCING BALL)
AIM:
To write python program using pygame for bouncing ball
ALGORITHM:
1. Import the needed libraries
2. Initialise the pygame window
3. Set the pygame window using set_mode(width,height)
4. Set the pygame window titke as bouncing ball using set_caption()
5. Load the ball image in pygame.image.load()
6. If the pygame event is QUIT then exit.
7. Else move the ball with particular speed
8. If ballrect.left< 0 or ballrect.right> width and ballrect.top< 0 orballrect.bottom>
height then reduce the speed
PROGRAM/SOURCE CODE:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jfif")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
60 | P a g e
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT:
RESULT:
Thus the python program for bouncing ball using pygame was written and executed
successfully.
61 | P a g e
EX:NO: 12A)
DEVELOPING GAME ACTIVITY USING PYGAME
(CAR GAME)
AIM:
To write python program using pygame for car game.
ALGORITHM:
1) Import needed libraries
2) Initialise pygame window with height and width
3) Load the background and car images
4) Run the car by calling run_car function
5) If not crashed run else game over
6) If left key is pressed then self.car_x_coordinate -= 50
7) If right key is pressed then self.car_x_coordinate += 50
PROGRAM/SOURCE CODE:
import random
from time import sleep
import pygame
class CarRacing:
def
init (self):
pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.clock = pygame.time.Clock()
self.gameDisplay = None
self.initialize()
def initialize(self):
self.crashed = False
self.carImg = pygame.image.load('C:/Users/lenovo/Desktop/car game/car.png')
self.car_x_coordinate = (self.display_width * 0.45)
self.car_y_coordinate = (self.display_height * 0.8)
62 | P a g e
self.car_width = 49
# enemy_car
self.enemy_car = pygame.image.load('C:/Users/lenovo/Desktop/car
game/enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100
# Background
self.bgImg = pygame.image.load("C:/Users/lenovo/Desktop/car game/back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0
def car(self, car_x_coordinate, car_y_coordinate):
self.gameDisplay.blit(self.carImg, (car_x_coordinate, car_y_coordinate))
def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('Car Race -- Godwin')
self.run_car()
def run_car(self):
while not self.crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.crashed = True
# print(event)
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
63 | P a g e
self.car_x_coordinate -= 50
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
self.gameDisplay.fill(self.black)
self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed
if self.enemy_car_starty > self.display_height:
self.enemy_car_starty = 0 - self.enemy_car_height
self.enemy_car_startx = random.randrange(310, 450)
self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
self.count += 1
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate <
self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width >
self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game Over !!!")
if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:
self.crashed = True
self.display_message("Game Over !!!")
pygame.display.update()
self.clock.tick(60)
def display_message(self, msg):
font = pygame.font.SysFont("comicsansms", 72, True)
64 | P a g e
text = font.render(msg, True, (255, 255, 255))
self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
def back_ground_raod(self):
self.gameDisplay.blit(self.bgImg, (self.bg_x1, self.bg_y1))
self.gameDisplay.blit(self.bgImg, (self.bg_x2, self.bg_y2))
self.bg_y1 += self.bg_speed
self.bg_y2 += self.bg_speed
if self.bg_y1 >= self.display_height:
self.bg_y1 = -600
if self.bg_y2 >= self.display_height:
self.bg_y2 = -600
def
run_enemy_car(self,
thingx,
thingy):
self.gameDisplay.blit(self.enemy_car, (thingx, thingy))
def highscore(self, count):
font = pygame.font.SysFont("lucidaconsole", 20)
text = font.render("Score : " + str(count), True, self.white)
self.gameDisplay.blit(text, (0, 0))
def display_credit(self):
font = pygame.font.SysFont("lucidaconsole", 14)
text = font.render("Thanks & Regards,", True, self.white)
self.gameDisplay.blit(text, (600, 520))
text = font.render("J Godwin", True, self.white)
self.gameDisplay.blit(text, (600, 540))
text = font.render("godwin@gamail.com", True, self.white)
self.gameDisplay.blit(text, (600, 560))
65 | P a g e
if
name
== ' main ':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT:
RESULT:
Thus the python program for car race game using pygame was written and executed
successfully.
66 | P a g e
Download