python programs (1)-GE3181 LAB MANUAL
python programs (1)-GE3181 LAB MANUAL
AIM:
To develop a flowchart for electricity billing.
ALGORITHM:
Step1: Start.
Step 3: Calculate the used units by subtracting the current unit and previous unit.
Step6: Stop.
PSEUDOCODE:
PRINT ElectricityBill
FLOWCHART:
RESULT:
AIM:
To develop a flowchart for the retail shop billing.
ALGORITHM:
Step1: Start.
Step2: Read the barcode of the product.
Step3: Display the product name and the amount.
Step 4: Check if more products is available, if available go to Step 2, otherwise go to
Step 5.Step5: Calculate the total cost of the products.
Step6: Print total cost
Step7: Stop.
PSEUDOCODE:
RESULT:
Thus, the flowchart for retail shop billing was developed.
EX. NO:1C. IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
DATE: OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DEVELOPING FLOW CHARTS FOR THE SIN SERIES
AIM:
ALGORITHM:
Step1: Start
Step2: Read x and n.
Step3: Print x and n.
Step 4: Convert x values into radian using formula x = x * 3.1412/180.
Step5: Substitute t=x and sum=x.
Step 6: Set the for loop for doing the calculation as initialize i to 1 and check i is less than n+1and
increment i by 1.
Step 7:Calculate t=(t*pow(-1),(2*i- 1))*x*x)/(2*i*(2*i+1).
Step8: Calculate sum = sum + t.
Step9: Print sum.
Step10: Stop
PSEUDOCODE:
READ x, n
PRINT x, n
CONVERT x =x * 3.1412/180 SUBSTITUTE t=x,
sum=x
FOR i=1;i<n+1;i++
t= (t*pow (-1), (2*i- 1))*x*x)/(2*i*(2*i+1).
sum = sum + t
END FOR
PRINT sum
FLOWCHART:
RESULT:
AIM:
To develop a flowchart for finding the weight of a motor bike.
ALGORITHM:
Step1: Start.
Step2: Read the size of the motor bile in cc.
Step3: Check whether the size of the motor bike is less than or equal to 300 cc, if so, Print
Average weight is 350pounds otherwise go to step 4.
Step4: Check whether the size of the motor bike is less than or equal to 500 cc, if so, Print
Average weight is 410pounds otherwise go to step 5.
Step5: Check whether the size of the motor bike is less than or equal to 900cc, if so, Print
Average weight is 430pounds otherwise go to step 6.
Step6: Check whether the size of the motor bike is equal to 1100 cc, if so, Print Average weight
is 500 pounds otherwise go to step 7.
Step 7: Print Average weight is 600 pounds.
Step 8: Stop.
PSEUDOCODE:
READ size in cc
IF size<=300 THEN
PRINT Average weight = 350 pounds
ELSE IF size <=500 THEN
PRINT Average weight = 410
pounds
ELSE IF size <=900 THEN
PRINT Average weight = 430 pounds
ELSE IF size =1100 THEN
PRINT Average
weight=500pounds
ELSE
PRINT Average weight=600 pounds
END IF
FLOWCHART:
RESULT:
Thus, the flowchart for finding the weight of the motor bike was developed.
EX. NO:1E
IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
DATE: OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DEVELOPING FLOW CHARTS FOR THE WEIGHT OF A
STEEL BAR
AIM:
To develop a flowchart for finding weight of a steel bar.
ALGORITHM:
Step1: Start.
Step2: Read the diameter in mm and length of the steel bar.
Step3: Check whether the length is in meter if so, calculate weight as diameter x diameter x length and
divide it by162, otherwise go to step4.
Step 4: calculate weight as diameter x diameter x length and divide it by 533.
Step5: Print the weight.
Step6: Stop.
PSEUDOCODE:
RESULT:
Thus, the flowchart for finding the weight of a steel bar was developed.
.
EX. NO:1F
IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DATE: DEVELOPING FLOW CHARTS FOR THE COMPUTE
ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
AIM:
ALGORITHM:
Step1: Start.
Step2: Get the value of voltage, resistance, current and power factor.
Step3: Compute the electric current by multiplying voltage, resistance, current and power factor with
3.
Step 4: Print the calculated electric current.
Step5: Stop.
PSEUDOCODE:
.
FLOWCHART:
RESULT:
Thus, the flowchart for computing the electric current in three phase AC circuit
was developed.
.
EXP NO:2A
EXCHANGE THE VALUES OF TWO VARIABLES
DATE:
AIM:
To write a python program for exchanging the values of two variables.
ALGORITHM:
STEP1: Start
STEP2: Initialize two variables, a and b, with some values.
STEP3: Print the values of a and b before swapping.
STEP4: Exchange the values of a and b using a temporary variable.
STEP5: Print the values of a and b after swapping.
STEP6: Stop
PROGRAM:
.
OUTPUT:
RESULT:
Thus a python program for exchanging the values of two variables was written and verified
successfully.
.
EXP NO:2B
CIRCULATE THE VALUES OF N VARIABLES
DATE:
AIM:
To write a python program for circulating the values of n variables.
ALGORITHM:
STEP1: Start
STEP2: Initialize n variables with some values.
STEP3: Print the values of all variables before circulating.
STEP4: Circulate the values of the variables.
STEP5: Print the values of all variables after circulating.
STEP6: Stop
PROGRAM:
.
OUTPUT:
RESULT:
Thus a python program for circulating the values of n variables was written and
executed successfully.
.
Exp No:2c
CALCULATE DISTANCE BETWEEN TWO POINTS
Date:
AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
STEP1: Start
STEP2: Define the coordinates of two points.
STEP3: Calculate the distance using the distance formula.
distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
STEP4: Print the calculated distance.
STEP5: Stop
PROGRAM:
#Method 1
#----------
import math
# to get input 2points (x1,y1) & (x2,y2)
x1 = int(input("Enter a number: "))
y1 = int(input("Enter a number: "))
x2 = int(input("Enter a number: "))
y2 = int(input("Enter a number: "))
#process calculate distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
a=x1-x2
b=y1-y2
d=math.sqrt((a**2)+(b**2))
print("distance between 2 points=",d)
.
OUTPUT:
#Method 2
#------------
import math
#process calculate distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
p1=[0,0]
p2=[0,0]
# to get input 2points p1(x1,y1) & p2(x2,y2) using List
#-----------------------------------------------------------------
p1[0]=int(input("Enter p1[x1] value:"))
p1[1]=int(input("Enter p1[y1] value:"))
p2[0]=int(input("Enter p2[x2] value:"))
p2[1]=int(input("Enter p2[y2] value:"))
a=p1[0]-p2[0]
b=p1[1]-p2[1]
d = math.sqrt((a**2)+(b**2))
print("distance between 2 points using List=",d)
.
OUTPUT:
RESULT:
Thus, a python program for calculating the distance between two points was written and
executed successfully.
.
EXP NO:3A
NUMBER SERIES
DATE:
AIM:
To write a python program for generating different number series using iterative loops and
conditionals.
ALGORITHM:
STEP1: Start
STEP2: Prompt the user to input the type of number series to generate (e.g., Fibonacci, prime,
square).
STEP3: Depending on the user's choice, generate the corresponding number series using iterative
loops and conditionals.
STEP4: Print the generated number series.
STEP5: Stop
PROGRAM:
.
OUTPUT:
..
.
RESULT:
Thus, the Python program number series has executed successfully and the output has
been verified.
.
EXP NO:3B
NUMBER PATTERNS
DATE:
AIM:
To write a python program for printing a number pattern using iterative loops and conditionals
ALGORITHM:
PROGRAM:
for i in range(1,rows+1):
for j in range(1,i+1):
print(" ")
.
Output:
RESULT:
Thus the python program to print numbers patterns was executed and verified successfully.
.
EXP NO:3C
PYRAMID PATTERN
DATE:
AIM:
To write a python program to print pyramid patterns
ALGORITHM:
Step 1 : Start the program.
Step 2 : Read the input values using input()
Step 3 : Perform the following. m = (2 * n) – 2
Step 4 : Decrementing m after each loop Perform the following.
Step 5 : m = m – 1
Step 6 : Print full Triangle pyramid using stars.
Step 7 : Print the value until the for loop ends.
Step 8: Stop the program.
PROGRAM:
.
OUTPUT:
RESULT:
Thus, the Python program to print Pyramid Pattern has executed successfully and the output
has been verified.
.
EXP NO:4A
LIBRARY FUNCTIONALITY USING LIST
DATE:
AIM
To write a python program to implement the library functionality using list.
ALGORITHM
Step 1 : Start the program
Step 3 : Get option from the user for accessing the library function
3.1. Add the book to list
3.2. Issue a book
3.3. Return the book
3.4. View the list of book
Step 4 : if choice is 1 then get book name and add to book list
Step 5 : if choice is 2 then issue the book and remove from book
list Step 6 : if choice is 3 then return the book and add the
book to list Step 7 : if choice is 4 then the display the book
list
Step 8 : otherwise exit from
menu Step 9 : Stop the
program.
Program:
booklist=["python","tamil","english"]
print("Welcome to library”")
while(1):
ch=int(input(" 1. add the book to list \n 2. issue a book \n 3. return the book
\n 4. view the book list \n 5. Exit \nEnter Ur Choice::"))
.
if(ch==1):
bk=input("enter the book name::")
booklist.append(bk)
print(booklist)
elif(ch==2):
ibk=input("Enter the book to issue::")
booklist.remove(ibk)
print(booklist)
elif(ch==3):
rbk=input("enter the book to return::")
booklist.append(rbk)
print(booklist)
elif(ch==4):
print(booklist)
else:
break
.
OUTPUT
RESULT
Thus the Python program to implement the library functionality using a list has executed
and the results are verified. .
EXP.NO : 4B
DATE: LIBRARY FUNCTIONS USING TUPLES
AIM
To write a python program to implement the library functionality using tuples.
ALGORITHM
Step 1 : Start the program
Step 2 : Create a tuple named as book.
Step 3 : Add a “NW” to a book tuple by using + operator.
Step 4 : Print book.
Step 5 : Slicing operations is applied to book tuple of the range 1:2 and print book.
Step 6 : Print maximum value in the tuple.
Step 7 : Print maximum value in the tuple.
Step 8 : Convert the tuple to a list by using list function.
Step 9 : Delete the tuple.
Step 10 : Stop the program.
PROGRAM
.
OUTPUT
RESULT
Thus the python program to implement the library functionality using tuple has executed and
the results are verified .
EXP NO:5A IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING SETS, DICTIONARIES.
DATE:
LANGUAGES USING DICTIONARIES
AIM
To write a python program to implement the languages using dictionaries.
ALGORITHM
Step 1 : Start the program
Step 2 : Create a empty dictionary using {}
Step 3 : dict( ) is used to create a dictionary.
Step 4 : To add a value, update() is used in key value pair.
Step 5 : Calculate the total values in the dictionary using len( ) .
Step 6 : Remove the particular key in the dictionary by using pop( )
Step 7 : Print the keys in the dictionary by using key( )
Step 8 : Print the values in the dictionary by using values( )
Step 9 : Print the key value pair in the dictionary using items( )
Step 10 : Clear the the key value pair by using clear( )
Step 11 : Delete the dictionary by using del dictionary
PROGRAM
print("List of Library Function in Set,Dictionary!!!!!!")
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"}#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
.
print(" the length of the languages :",len(Language))
Language.pop(5)
print(" key 5 has been popped with value :",Language)
print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
Language.clear()
print(" The items are cleared in dictionary ",Language)
del Language
print(Language)
.
OUTPUT
Result:
Thus the python program to implement languages using dictionaries has executed
and verified.
.
EXP NO:5B
DATE: COMPONENTS OF AUTOMOBILE USING
DICTIONARIES
AIM
To write a python program to implement automobile using dictionaries.
ALGORITHM
Step 1: Start the program
Step 2: Create a empty dictionary using
{} Step 3: dict() is used to create a
dictionary.
Step 4: Get the value in the dictionary using get()
Step 5: adding [key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using popitem().
Step 7: To check whether key is available in dictionary by using membership operator
in. Step 8: Stop the program.
PROGRAM
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is ",auto_mobile.get(2))
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile)
print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile parts")
.
print(2 in auto_mobile)
OUTPUT
RESULT
Thus the python program to implement automobile
. using dictionaries was executed and verified
successfully.
EX NO: 5C
ELEMENTS OF A CIVIL STRUCTURE
DATE:
AIM
To write a python program to implement elements of a civil structure using dictionaries.
ALGORITHM
PROGRAM
civil_ele={ }
print("Civil_Ele=",civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print("Civil_Ele=",civil_ele)
new=civil_ele.copy( )
print(" The copy of civil_ele ",new)
print(" The length of Dictionary:: ",len(civil_ele))
print("Dictionary Elements:: ")
for i in civil_ele:
print(civil_ele[i])
.
OUTPUT
RESULT
Thus the python program to implement elements of a civil structure using dictionaries has
executed and verified successfully.
.
EXP NO:6A
FACTORIAL OF A NUMBER USING FUNCTION
Date:
AIM:
To write a python program for calculating the factorial of a given number using a function.
ALGORITHM:
STEP1: Start
STEP2: Define a function factorial(n) that takes an integer n as input.
STEP3: Initialize a variable result to 1.
STEP4: Use a for loop to iterate from 1 to n (inclusive).
STEP5: Multiply result by the current value of i.
STEP6: Return the value of result.
STEP7: Stop
PROGRAM:
def fact(n):
if(n==0):
return 1
else:
return n*fact(n-1)
n=int(input("enter n:"))
o=fact(n)
print("The Factorial of {} is {}".format(n,o))
.
OUTPUT:
RESULT:
Thus the python program to find the factorial of a given number by using function has executed
and the results are verified.
.
EXP NO:6B
LARGEST NUMBER IN A LIST USING FUNCTION
DATE:
AIM:
To write a python program for finding the largest number in a given list using a function.
ALGORITHM:
STEP1: Start
STEP2: Define a function find_largest(lst) that takes a list lst as input.
STEP3: Initialize a variable max_num to the first element of the list.
STEP4: Use a for loop to iterate through each element of the list.
STEP5: If the current element is greater than max_num, update max_num to the current element.
STEP6: Return the value of max_num.
STEP7: Stop
PROGRAM:
OUTPUT:
.
RESULT:
Thus the python program to find the largest number in the list by using function is executed and
the results are verified.
.
EXP. NO : 6C
DATE: AREA OF SHAPES
AIM:
To write a python program for area of shape using functions.
ALGORITHM:
.
PROGRAM:
import math
#Function to find area of rectangle
def rect(x,y):
return x*y
#Function to find area of circle
def circle(r):
PI = 3.142
return PI * (r*r)
#function to find area of Traingle
def triangle(a, b, c):
Perimeter = a + b + c
s = (a + b + c) / 2
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print("The Perimeter of Triangle = %.2f" %Perimeter)
print("The Semi Perimeter of Triangle = %.2f" %s)
print("The Area of a Triangle is %0.2f" %Area)
#Main Program to Call Various Functions
# Python program to compute area of rectangle
print("1.Rectangle")
l = int(input("Enter the length of rectangle : "))
b = int(input("Enter the breadth of rectangle : "))
a = rect(l,b)
print("Area =",a)
# Python program to find Area of a circle
print("\n2.Circle")
num=float(input("Enter r value of circle:"))
print("Area of Circle is %.6f" % circle(num))
# python program to compute area of triangle
print("\n3.Triangle")
triangle(6, 7, 8)
OUTPUT:
RESULT:
Thus the python program for area of shapes using functions has executed and the
results are verified.
EXP NO:7A
REVERSING A STRING
DATE:
AIM:
To write a python program for reversing a given string.
ALGORITHM:
STEP1: Start
STEP2: Define a function reverse_string(s) that takes a string s as input.
STEP3: Use for to reverse the string.
STEP4: Return the reversed string.
STEP5: Stop
PROGRAM:
RESULT:
Thus the python program for reversing a .string has executed and the results are verified
EXP NO:7B
PALINDROME OR NOT
DATE:
AIM:
To write a python program for checking if the given string is a palindrome or not.
ALGORITHM:
STEP1: Take the input string from the user.
STEP2: Remove any non-alphanumeric characters from the input string and convert it to lowercase.
STEP3: Compare the cleaned string with its reverse.
STEP4: If the cleaned string is equal to its reverse, print "The string is a palindrome."
STEP5: Otherwise, print "The string is not a palindrome."
PROGRAM:
RESULT:
Thus the python program for palindrome of a string is executed and the results
are verified
EXP NO : 7C
DATE: CHARACTER COUNT OF A STRING
AIM:
To write a python program for counting the characters of string.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a string.
Step 3: Define and initialize a variable count to 0.
Step 4: Iterate through the string till the end and for each character except spaces, increment
the count by 1.
Step 5: To avoid counting the spaces check the condition i.e. string[i] != ' '.
Program:
#Function for Counting a String
def count(s):
c=0
for i in range(0,len(s),1):
c=c+1
return c
Result:
Thus the python program for counting the characters of string is executed and the results are
verified.
EXP.NO : 7D
REPLACE OF A STRING
DATE:
AIM:
To write a python program for replacing the characters of a string.
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
Thus the python program for replacing the given characters of string has executed and the
results are verified.
EXP.NO : 8A
DATE: CONVERT LIST IN TO A SERIES USING
PANDAS
AIM:
To write a python program for converting list in to a Series.
ALGORITHM:
PROGRAM:
OUTPUT:
0 a
1 b
2 c
3 d
4 e
dtype: object
RESULT:
Thus the python program for converting list in to a series has executed and the results are
verified.
EXP.NO : 8B
DATE: FINDING THE ELEMENTS OF A GIVEN ARRAY IS
ZERO USING NUMPY
AIM:
To write a python program for testing whether none of the elements of a given array is zero.
ALGORITHM:
PROGRAM:
import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
OUTPUT:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero: True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero: False
RESULT:
Thus the python program for testing whether none of the elements of a given array is zero has
executed and the results are verified.
EXP.NO : 8C
DATE: GENERATE A SIMPLE GRAPH USING MATPLOTLIB
AIM:
To write a python program for generating a simple graph using matplotlib.
ALGORITHM:
Step 1: Start the program.
Step 2: from matplotlib import pyplot libaray
Step 3: Create a object as plt for pyplot
Step 4: Use plot function to plot the given values
Step 5: Plot the result using show function
Step 6: Stop the program.
PROGRAM:
OUTPUT:
RESULT:
Thus the python program for generating a simple graph using matplotlib zero has executed
and the results are verified.
EXP.NO : 8D
DATE: SOLVE TRIGONOMETRIC PROBLEMS USING SCIPY
AIM:
To write a python program for finding the exponents and solve trigonometric problems using
scipy.
ALGORITHM:
PROGRAM:
OUTPUT:
1000.0
8.0
1.0
0.707106781187
RESULT:
Thus the python program for finding the exponents and solve trigonometric problems using
scipy has executed and the results are verified.
EXP NO:9A
COPYING FROM ONE FILE TO ANOTHER
DATE:
AIM:
To write a python program for copying the contents of one file to another.
ALGORITHM:
STEP1: Open the source file in read mode and the destination file in write mode.
STEP2: Read the content from the source file.
STEP3: Write the read content to the destination file.
STEP4: Close both files after copying is completed.
PROGRAM:
INPUT:
Source file:
Destination file
OUTPUT:
Source file:
Destination file
RESULT:
Thus the python program for copying text from one file to another has executed and the results are
verified.
EXP NO:9B
COUNTING THE WORDS IN A FILE
DATE:
AIM:
To write a python program for counting the number of words in a file.
ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Count the number of words in the list of words.
STEP5: Close the file after counting is completed.
STEP6: Stop
PROGRAM:
def word_count(soc):
with open(soc, 'r') as file:
content = file.read()
words = content.split()
return len(words)
OUTPUT:
RESULT:
Thus the Python program for command line arguments is executed
successfully and the output is verified.
EXP NO:9C
FINDING THE LONGEST WORD IN A FILE
DATE:
AIM:
To write a python program for finding the longest word in a file.
ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Iterate over each word in the list of words and find the length of each word. STEP5: Keep
track of the longest word encountered.
STEP6: Close the file after finding the longest word.
PROGRAM:
def longest_word(soc):
with open(soc, 'r') as file:
content = file.read()
words = content.split()
longest = max(words, key=len)
return longest
OUTPUT:
RESULT:
Thus the Python program finding the longest words using file handling concepts is executed
successfully and the output is verified
EXP.NO : 10A
DATE: DIVIDE BY ZERO ERROR – EXCEPTION HANDING
AIM:
To write a Python program for finding divide by zero error.
ALGORITHM:
PROGRAM:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
OUTPUT:
Enter First Number: 12.5
Invalid Input Please Input Integer...
Enter First Number: 12
Enter Second Number: 0
division by zero
RESULT:
Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
EXP.NO : 10B
DATE: VOTER’S AGE VALIDITY
AIM:
To write a Python program for validating voter’s age.
ALGORITHM:
PROGRAM:
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except ValueError:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main( )
OUTPUT:
Enter your age20.3
age must be a valid number
RESULT:
Thus the Python program for validating voter’s age is executed successfully and the output is
verified.
EXP.NO : 10C
STUDENT MARK RANGE VALIDATION
DATE:
AIM:
To write a python program for student mark range validation
ALGORITHM:
PROGRAM:
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")
main()
OUTPUT:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed
RESULT:
Thus the python program for student mark range validation is executed and verified.
EXP.NO : 11
EXPLORING PYGAME TOOL.
DATE:
Pygame :
RESULT:
AIM:
To write a Python program to simulate bouncing ball in pygame.
ALGORITHM:
Step1: Start
Step3: Initialize the height, width and speed in which the ball bounce
Step7: Stop
PROGRAM:
import sys, pygame
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("Tree_Short.png")
ballrect = ball.get_rect()
while 1:
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Execution Procedure:
1. Copy this url: https://trinket.io/features/pygame to your browser and open pygame
interpreter
2. Remove the source code in main.py and copy the below source code to main.py
3. Click the Run button to execute.
OUTPUT:
RESULT:
Thus the Python program to simulate bouncing ball using pygame is executed successfully
and the output is verified.
EXP.NO : 12B
CAR RACE
DATE:
AIM:
To write a Python program to simulate car race in pygame.
ALGORITHM:
Step1: Start
Step2: Import the necessary packages
Step3: Initialize the height, width and speed in which the ball
bounce Step4:Set the screen mode
Step5: Load the ball image
Step4: Move the ball from left to
right Step5: Stop
PROGRAM:
import pygame pygame.init()
#initializes the Pygame from pygame.locals
import* #import all modules from Pygame screen = pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('RacingBeast')
#changing the logo
logo = pygame.image.load('car game/logo.png')
pygame.display.set_icon(logo) #defining our gameloop function def
gameloop():
#setting background image
bg = pygame.image.load('car game/bg.png') # setting our
player maincar = pygame.image.load('car game\car.png')
maincarX = 100 maincarY = 495
maincarX_change = 0
maincarY_change = 0 #other
cars
car1 = pygame.image.load('car
game\car1.png') car2 =
pygame.image.load('car game\car2.png')
car3 = pygame.image.load('car game\car3.png') run =
True while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT: maincarX_change
+= 5 if event.key == pygame.K_LEFT:
maincarX_change -= 5
Execution Procedure:
OUTPUT:
RESULT:
Thus the Python program to simulate car race using pygame is executed successfully and
the output is verified.