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

Lab Record (1)

python program

Uploaded by

anandhanr668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Lab Record (1)

python program

Uploaded by

anandhanr668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Ex.

No: 1 A
Date:
Identification and solving of simple real life or scientific or technical problems and developing
flowcharts for the same - Electricity Billing
Aim:
To develop a flowchart for Electricity billing in MSWord

Procedure:
1. For the first 50 units Rs. 0.50/unit
2.For the next 100 units Rs. 0.75/unit
3.For the next 100 units Rs. 1.20/unit
4.For unit above 250 Rs. 1.50/unit
5.An additional surcharge of 20% is added to the bill.

Flow Chart:

Result:

1
Ex. No: 1 B
Date:

Retail Shop billing


Aim:
To develop a flowchart for Retail Shop Billing in MSWord

Flow-Chart:

Result:

2
Ex. No: 1 C
Date:

Sin series

Aim:
To develop a flowchart for Sine Series in MSWord.

Flow Chart:

Result:

3
Ex. No: 1 D
Date:

To compute Electrical Current in Three Phase AC Circuit

Aim:
To Develop a flowchart for Electric Current in Three Phase AC Circuit in MSWord.

Flowchart:

Result:

4
Ex. No: 2 A
Date:
Python programming using simple statements and expressions-
Exchange the values of two variables

Aim:
To write a python program to exchange the values of two variables.

Algorithm:

Step 1: Start the Program


Step 2: Declare a variable a,b as integer
Step 3: Read two numbers a and b
Step 4: Assign a,b=b,a
Step 5: Print a and b
Step 6: Stop the Program

Code:

a=10
b=20
print("Before swap a=",a, "b=",b)
a,b=b,a
print("After swap a=",a)
print("After swap b=", b)

Output:

Result:

5
Ex. No: 2 B
Date:
Python programming using simple statements and expressions –
(circulate the values of n variables)
Aim:
To write a python program to circulate the values of n variables

Algorithm:

Step 1: Start the Program


Step 2: Create a list of integers
Step 3: Read the value of into be circulated
Step 4: Compute the circulation operation using List slicing- list[n:]+list[:n]
Step 5: Print the circulated list
Step 6: Stop the Program

Code:

list=[10,20,30,40,50]
n=int(input("enter the value of n"))
print(list[n:]+list[:n])

Output:

Result:

6
Ex. No: 2 C
Date:

Python programming using simple statements and expressions


(Calculate the distance between two points)

Aim:
To write a python program to calculate the distance between two numbers

Algorithm:
Step1: Start the Program
Step 2: Read the values of x1, x2, y1, y2

Step 3: Calculate the difference between the corresponding X-cooridinates i.e :X2 -
X1 and Y-cooridinates i.e : Y2 -Y1 of two points.

Step 4: Apply the formula derived i.e : sqrt((X2 - X1)^2 + (Y2- Y1)^2)

Step 5: Stop the program

Code:
import math
x1=int(input("Enter the value of x1:" ))
x2=int(input("Enter the value of x2:" ))
y1=int(input("Enter the value of y1:" ))
y2=int(input("Enter the value of y2:" ))
dx=x2-x1
dy=y2-y1
d=(dx**2)+(dy**2)
result=math.sqrt(d)
print("Distance between two variable is:",result)

7
Output:

Result:

8
Ex. No: 3A
Date:

Scientific problems using Conditionals and Iterative loop-Number series

Aim:
To Write a Python program with conditional and iterative statements for printing all number
divisible by 7 and 5 in the Number Series.

Algorithm:
Step 1: Start the program
Step 2: Initialize an empty list and read the numbers with range().
Step 3: if x%7==0andx%5==0 then goto step 4.
Step 4: Append to the empty list n1.
Step 5: Display the list with multiples of 7 and 5.
Step 6: Stop the program

Code:
nl=[]
for x in range(1,200):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print("Number divisible by 5 & 7 within 200:",','.join(nl))

Output:

Result:

9
Ex. No: 3B
Date:

Scientific problems using Conditionals and Iterative loops.-Number Pattern

Aim:

To write a Python program with conditional and iterative statements for Number Pattern.

Algorithm:

Step1: Start the program


Step 2: Let i be an integer number.
Step 3: Let j be an integer number.
Step 4: Let n be a integer number and initialize by 5.
Step 5: Repeat step 6to 9until all value parsed.
Step 6: Set i = 0 and check i<nrows
Step 7: Set j = 0 and check j < i+1
Step 8: Print j
Step 9: Increment j=j+1
Step 10:Print\r
Step 11: Increment i=i+1 and repeat step 5
Step 12: Stop the program

Code:
nrows=5
for i in range(0,nrows,1):
for j in range(0,i+1):
print(j,end=" ")
print("\r")

10
Output:

Result:

11
Ex. No: 3C
Date:

Scientific problems using Conditionals and Iterative loops.-Pyramid Patterns

Aim:
To Write a Python program with conditional and iterative statements for Pyramid Pattern.

Algorithm:

Step 1: Start the program


Step 2: Initialize the variables
Step 3: Read the input
Step 4: Let n be a integer number and initialize by 5.
Step 5:Check the range value by using for loop
Step 6: Calculate the space for pyramid pattern
Step 7: Increment the pattern * until the loop ends
Step 8: Print the pyramid pattern
Step 9: Stop the program

Code:
print("Printing equilateral triangle Pyramid using asterisk symbol ")
size=7
m=(2*size)-2
for i in range(0, size,2):
for j in range(0,m):
print(end=' ')
#m = m-1
for j in range(0,i+1):
print("*",end="")
print("\r")
m=m-1

12
Output:

Result:

13
Ex. No: 4 A
Date:

Implementing real-time/technical applications using Lists, Tuples –


Items present in a library

Aim:
To Write a python program to implement items present in library

Algorithm:

Step1: Start the program

Step 2: Initialize the list and tuple values for library book details

Step 3: Compute the list operations for accessing the library book details and tuple
operations such as updating and concatenation the elements.
Step 4: Print all the outputs
Step 5: Stop the program

Code:
print("--------Using List---------")
library=["books", "author", "barcodenumber" , "price"]
print("Before adding",library)
library[0]="ramayanam"
library[1]="valmiki"
library[2]=123987
library[3]=234
print("After adding an item", library)
print("--------Using Tuple---------")
tup1=("books","totalprice")
print("Tuple1", tup1)
tup2=(12134,25000)
print("Tuple2", tup2)
tup3 = tup1 +tup2;
print("Tuple adding(tup1+tup2):",tup3)

14
Output:

Result:

15
Ex. No: 4 B
Date:

Implementing real-time/technical applications using Lists, Tuples -Components of a car

Aim:
Write a python program to implement components of a car Algorithm

Algorithm:
Step 1: Start the program

Step 2: Initialize the list and tuple values for components of a car

Step 3: Compute the list operations append with list looping and tuple operations such as
accessing the elements of car components

Step 4: Print all the outputs

Step 5: Stop the program

Code:
cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]
print("Original list:", cars)
new_list =[ ]
for i in cars:
if"M" in i:
new_list.append(i)
print("company start with M:",new_list)
print("--------using tuples--------")
cars=("Ferrari", "BMW", "Audi", "Jaguar")
print("Items in tuples:",cars)
print("0th item in tuple:",cars[0])
print("1st item in tuple:",cars[1])
print("2nd item in tuple:",cars[2])
print("3rd item in tuple:",cars[3])

16
Output:

Result:

17
Ex. No: 4 C
Date:

Implementing real-time/technical applications using Lists, Tuples –


Materials required for construction of a building

Aim:
Write a python program to implement materials required for construction of building

Algorithm:
Step 1: Start the program

Step 2: Initialize the list and tuple values for Materials required for constructing a building

Step 3: Compute the list operations such as append, insert, accessing, removing the elements
and tuple operations such as accessing and deleting elements

Step 4: Print all the outputs

Step 5: Stop the program

Code:
List:
materials_for_construction = ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
print("Original list", materials_for_construction)
materials_for_construction.append("Tiles")
print("After append", materials_for_construction)
materials_for_construction.insert(3,"Aggregates")
print("After insert", materials_for_construction)
materials_for_construction.remove("sand")
print("After remove", materials_for_construction)
materials_for_construction[5]="electrical"
print("Using assignment", materials_for_construction)
Tuple:
print("-------------Using Tuples------------")
materialsforconstruction = ("cementbags", "bricks", "sand", "Steelbars", " Paint")
print(materialsforconstruction)
del(materialsforconstruction)
print("After deleting materials for construction")

18
print(materialsforconstruction)

Output:

Result:

19
Ex. No: 5 A
Date:

Implementing real-time/technical applications using Sets, Dictionaries. –


Components of an automobile

Aim:
To write a python program to implement Components of an automobile using Sets and
Dictionaries.

Algorithm:

Step 1: Start the program

Step 2: Initialize the set for components of an automobile

Step 3: Compute the set operations add and discard on the automobile component elements

Step 4: Print all the outputs

Step 5: Stop the program

Code:
cars = {'BMW', 'Honda', 'Audi', 'Mercedes', 'Honda', 'Toyota', 'Ferrari', 'Tesla'}
print('Approach#1=', cars)
print('==========')
print('Approach #2')
for i in cars:
print('Car name = {}'.format(i))
print('==========')
cars.add('Tata')
print('New cars set ={}'.format(cars))
cars.discard('Mercedes')
print('discard()method={}'.format(cars))

20
Output:

Result:

21
Ex. No: 5 B
Date:

Implementing real-time/technical applications using Dictionaries

Aim:
To develop program to create and display element using dictionaries.

Algorithm:
Step 1: Open a new python file.
Step 2: Create a new dictionary with some data.
Step 3: Length calculation is used here to find the length.
Step 4: Popitem() is used in the dictionary.
Step 5: After adding the element.
Step 6: To find the value of the given key.
Step 7: Copy the function and print element.
Step 8: Clear the dictionary.
Step 9: Stop the program.

Code:

dict1={'cat':'cute','dog':'furry'}
l=len(dict1)
print("Length of the dict1:",l)
p=dict1.popitem ()
print("Popitem of dictionary is:",p)
dict1['elephant'] = 'big'
print('After adding the element is:',dict1)
print('The value of the given key is:',dict1.get('elephant'))
c=dict1.copy()
print('dict1:',dict1)
print('c:',c)
dict1.clear()
print('dict1=',dict1)

22
Output:

Result:

23
Ex. No: 5 C
Date:

Implementing real-time/technical applications using Sets, Dictionaries–Language

Aim:
To write a python program to implement language system using Sets and Dictionaries

Algorithm:
Step 1: Start the program

Step 2: Create a text file james_joyce_ulysses.txt and open in read mode

Step 3: Find the frequency of the word in the file using count method

Step 4: Remove the duplicate and print the unique words in file using set operation

Step 5: Stop the program

Code:
import read
Ulysses_txt=open("text1.txt").read().lower()
words=re.findall(r"\b[\w-]+\b", Ulysses_txt)
print("The novel ulysses contains:" +str(len(words)))
for word in ["the", "my", "good", "bad", "ireland", "python"]:
print("The word '" + word + "' occurs " + str(words.count(word)) +" times in the novel!")
diff_words=set(words)
print("'Ulysses'contains"+str(len(diff_words))+"different words!")

24
Output:
Module name - read
text1.txt - This is my python programming language

Result:

25
Ex. No: 6 A
Date:
Implementing programs using Functions–Factorial
Aim:
To write a python program to implement Factorial program using functions.

Algorithm:
Step 1: Start the program
Step 2: Define the function and read a number n
Step 3: if n=0or n==1, return 1
Step 4: else return n * factorial(n-1)
Step 5: Print factorial
Step 6: Stop the program

Code:
def factorial(n):
if n ==0 or n==1:
return 1
else:
return n*factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

Output:

Result:

26
Ex. No: 6 B
Date:
Implementing programs using Functions–largest number in a list

Aim:
To write a python program to implement largest number in a list using functions

Algorithm:
Step 1: Start the program
Step 2: Define the function
Step 3: Create the list.
Step 4: Initialize the variable x.
Step 5: if x > max, print maximum element.
Step 6: Print largest element from the list
Step 7: Stop the program
Code:
def myMax(list1):
max = list1[0]
for x in list1:
if x > max :
max = x
return max
list1=[10,20, 4, 45, 99]
print("Largest element is:",myMax(list1))

Output:

Result:

27
Ex. No: 6 C
Date:
Implementing programs using Functions–area of shape
Aim:
To write a python program to implement area of shape using functions.

Algorithm:
Step 1: Start the program
Step 2: Define the function
Step 3: Perform the area of shape, rectangle = l * b, square = s * s, triangle = 0.5 * b * h,circle=pi *r * r.
Step 4: Calculate and print all the shapes.
Step 5: Stop the program

Code:
def calculate_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}.")
elif name=="circle":
r = int(input("Enter circle's radius length: "))
pi =3.14
circ_area=pi*r *r
print(f"The area of triangle is {circ_area}.")

28
else:
print("Sorry! This shape is not available")
shapename=input("Enter shape name you want to find:")
calculate_area(shapename)

Output:

Result:

29
Ex. No: 7A
Date:

Implementing program using Strings–Reversing

Aim:
To write a python program to implement reverse of a string using string functions.

Algorithm:

Step 1: Start the program


Step 2: Define the function
Step 3: Use slice operator and return the string
Step 4: Compute the string using reverse function
Step 5: Print the string
Step 6: Stop the program

Code:
def reverse(string):
string = string[::-1]
return string
s="First year IT"
print ("The original string is : ",s)
print ("The reversed string(using extended slice syntax) is :",reverse(s))

Output:

Result:

30
Ex. No: 7 B
Date:

Implementing programs using Strings-palindrome

Aim:
To write a python program to implement palindrome using string functions.

Algorithm:

Step 1: Start the program


Step 2: Get input from the user.
Step 3: Using slice operator check the condition
Step 4: if n ==n[::-1]:
Step 5: Print this string is palindrome
Step 6: else print this string is not palindrome
Step 7: Stop the program

Code:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome:")
else:
print("The string is not a palindrome:")

Output:

Result:

31
Ex. No: 7 C
Date:

Implementing programs using Strings-character count

Aim:
To write a python program to implement Characters count using string functions.

Algorithm:

Step 1: Start the program


Step 2: Get the string to count
Step 3: Initialize count=0.
Step 4: Using for loop, check the condition whether i=t.
Step 5: Increment the count.
Step 6: Print the character count of the given string
Step 7: Stop the program

Code:
test_str ="Count the t in the text"
count=0
for i in test_str:
if i =='t':
count=count+1
print("Count of t is:",count)

Output:

Result:

32
Ex. No: 7 D
Date:

Implementing programs using Strings–Replacing Characters

Aim:
To write a python program to implement Replacing Characters using string functions.

Algorithm:

Step 1: Start the program


Step 2: Get the string to replace
Step 3: Use inbuilt function replace() the character.
Step 4: Print the string
Step 5: Stop the program

Code:
string = "geeks for geeks geeks geeks geeks"
print("Original string:",string)
print("Replace e with a:",string.replace("e","a"))
print("Replace ek with a:",string.replace("ek","a",2))

Output:

Result:

33
Ex. No: 8 A
Date:
Implementing programs using written modules and Python Standard Libraries–pandas

Aim:
To write a python program to implement pandas modules.

Algorithm:
Step 1: Start the program
Step 2: Install pandas as a standard library
Step 3: create Data frame
Step 4: print the maximum age from the data frame.
Step 5: Using the function describe() display min, max, count, percentage ,mean, std.
Step 6: Stop the program

Code:
import pandas as pd
df = pd.DataFrame( { "Name": [ "Harris", "Henry", "Elizabeth",], "Age": [22, 35, 58],"Sex": ["Male",
"Male", "Female"], } )
print(df)
print(df['Age'])
ages = pd.Series([22, 35, 58], name="Age")
print(ages.max())
print(ages.min())
print(df.describe())

34
Output:

Result:

35
Ex. No: 8 B
Date:
Implementing programs using written modules and Python Standard Libraries–matplotlib

Aim:
To write a python program to implement matplotlib module in python. .Matplotlib python are
used to show the visualization entities in python.

Algorithm:
Step 1: Start
Step 2: Import matplot lib as plt import Numpy module as np
Step 3: visualize the graph using the method subplots.
Step 4: Stop the program

Matplotlib is a python library that helps in visualizing and analysing the data and helps in better
understanding of the data with the help of graphical, pictorial visualizations that can be simulated
using the matplotlib library.

Code:
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,11)
y = 2 * x + 5.5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()

36
Output:

Result:

37
Ex. No: 8 C
Date:
Implementing programs using written modules and Python Standard Libraries–Numpy

Aim:
To write a python program to implement Numpy module in python .

Algorithm:
Step 1: Start the program
Step 2: Import Numpy module
Step 3: Create a array with non zero value
Step 4: Test the array
Step 5: Create the array with zero value and test
Step 6: Stop the program

Code:
import numpy as np
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))
x=np.array([0,1,2,3])
print("original array:")
print(x)
print("test if none of the elements of the 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 array is zero:
False
Result:
38
Ex. No: 8 D
Date:
Implementing programs using written modules and Python Standard Libraries–Scipy

Aim:
To write a python program to implement Scipy module in python. Scipy python are used to
solve the scientific calculations.

Algorithm:
Step 1: Start the program
Step 2: Import the essential Scipy library in python with I/O package
Step 3: Use constant to calculate minutes, hours, day, week
Step 4: Stop the program
SciPy is a scientific computation library that uses NumPy underneath. SciPy stands for Scientific
Python. It provides more utility functions for optimization, stats and signal processing. Like
NumPy,SciPy is also a open source

Code:
from scipy import constants
print(constants.minute)
print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)

Output:
60.0
3600.0
86400.0
604800.0
31536000.0

Result:

39
Ex. No: 9 A
Date:
Implementing real-time/technical applications using File handling –
copy from one file to another

Aim:
To write a python program to implement File Copying.

Algorithm:
Step 1: Start
Step 2: Create a file and enter the data
Step 3: Initialize f1 and open the file in read mode
Step 4: Initialize f2 and open the file in write mode
Step 5: Use read() method to open f1
Step 6: Use write() method to write file2 and close the file
Step 7: Read the file f3 and use len() to find the number of elements ,set maximum
Step 8: If len(words) equal to maximum, then print the longest word, close the file
Step 9: Stop

Create a file:
text1.txt
This is my python programming

Code:
f1=open("text1.txt","r")
f2=open("text2.txt","w")
str=f1.read()
f2.write(str)
print("content of file(f1)is read and it will copy to file2(f2)")
f1.close()
f2.close()
f3=open("text1.txt","r")
words=f3.read().split()
print("The word count in the file(f3)is",len(words))
max_len=len(max(words,key=len))
for word in words:
if len(word)==max_len:
print("The longest word in the file(f3)is",word)

40
f3.close()

Output:

Result:

41
Ex. No: 9 B
Date:
Implementing real-time/technical applications using File handling word count

Aim:
To write a python program to implement word count in File operations in python

Algorithm:
Step 1: Start the program
Step 2: Create a file it.txt
Step 3: Open the file in read mode
Step 4: Read the using read()function
Step 5: Split the text. Assume that words in a sentence are separated by a space character.
Step 6: The length of the split list should equal the number of words in text file.
Step 7: Stop the program

Create file it.txt with the following content


Welcome to python examples. Here, you will find python programs for all general usecases.

Code:
file = open("it.txt", "rt")
data= file.read()
words=data.split()
print('Number of words in text file:',len(words))

Output:

Result:

42
Ex. No: 9 C
Date:
Implementing real-time/technical applications using File handling-Longest word
Aim:
To write a python program to implement longest word in File operations

Algorithm:
Step 1: Start the program
Step 2: create a file test.txtand give the longest word
Step 3: open the file
Step 4: split the word using split method
Step 5:max_len = len(max(words, key=len))
Step 6: Return the longest word
Step 7: Stop the program

Create a file test.txt with the following input


hi I have pendrive

Code:
def longest_word(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_word("test.txt"))

Output:

Result:

43
Ex. No: 10 A
Date:

Implementing real-time/technical applications using Exception handling. Divide by zero error

Aim:
To write a exception handling program using python to depict the divide by zero error.

Algorithm:
Step 1: Start the program
Step 2.Get the inputs from the user.
Step 3: If the remainder is 0, throw divide by zero exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program

Code:
#mark=100
#a=mark/0
#print(a)
a=int(input("Entre value for a="))
b=int(input("Entre value for b="))
try:
c = ((a+b) / (a-b)) #Raising Error
if a==b:
raise ZeroDivisionError #Handling of error
except ZeroDivisionError:
print ("The result of a/b is 0")
else:
print(c)

44
Output:

Result:

45
Ex. No: 10 B
Date:
Implementing real-time/technical applications using Exception handling.
Check voter’s eligibility
Aim:
To write a exception handling program using python to depict the voters eligibility

Algorithm:
Step 1: Start the program
Step 2: Get the age of the person.
Step 3: If age is greater than or equal to18, then display 'Eligible to vote'.
Step 4: If age is less than18.
Step 5: Then display 'Not eligible to vote'.
Step 6: If enter negative number, then display “Enter valid age’
Step 7: Stop the program

Code:
def main():
try:
age=int(input("Enter your age:"))
if(age<0):
raise TypeError
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except TypeError:
print("Enter valid age")
main()

46
Output:

Result:

47
Ex. No: 11
Date:
Exploring pygame tool
Pygame
 Pygame is a cross-platform set of Python modules which is used to create video games.
 It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
 Pygame was officially written by Pete Shinners to replace PySDL.
 Pygame is suitable to create client-side applications that can be potentially wrapped in a standalone
executable.
Pygame Installation in Windows
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1 or above
version because it is much friendlier to beginners, and additionally runs faster.

There are mainly two ways to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what python uses
to install packages). The command is the following:
py -m pip install -U pygame --user
2. Installing through an IDE: The second way is to install it through an IDE and here we are using Pycharm
IDE. Installation of pygame in the pycharm is straightforward.
We can install it by running the above command in the terminal or use the following steps:
 Open the File tab and click on the Settings option.
 import pygame
Simple pygame Example
import pygame pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()

Result:

48
Ex. No: 12
Date:

Developing a game activity using Pygame like bouncing ball


Aim:
To write a python program to implement bouncing balls using pygame tool

Algorithm:
Step 1: Start the program

Step 2: Set screen size and background color.

Step 3: Set speed of moving ball.


Step 4: Create a graphical window using set_mode()
Step 5: Set caption
Step 6: Load the ball image and create a rectangle area covering the image
Step 7: Use blit()method to copy the pixel color of the ball to the screen
Step 8: Set background color of screen and use flip() method to make all images visible.
Step 9: Move the ball in specified speed.
Step10: If ball hits the edges of the screen reverse the direction.

Step 11: Create an infinite loop and Repeat steps 9 and 10 until user quits the program
Step12: Stop the program
Code:
#Simulate bouncing ball in pygame
# Bouncing ball
import sys, pygame
pygame.init()
size = width, height = 700, 300
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("Ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
49
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
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()
Ball.jpg

Output:

Result:

50
Ex. No: 12 B
Date:

Developing a game activity using Pygame like Carrace

Aim:
To write a python program to implement carrace using pygame tool

Procedure:

Step1:

a) Python installed on your computer.


b) A Code Editor because it makes your work easy. Using Visual Studio Code you can
use Pycharm or any editor you want.
c) Pygame library is installed because if not then open command prompt or terminal on
your computer and then type one of the following commands in terminal:

1.”pipinstallpygame”
2.py -m pip install -U
pygame –user”3.”py-m
pip install pygame”

Step2:
After installing pygame,you can start to develop the game

Step3:
import pygame

This will initialize and import all modules from Pygame.


Step4:
We imported and initialized the Pygame and then created a screen variable in which we
give the value for our game window.
Step5:
Check all the events one by one and checked whether a cross button or close button
has been pressed if yes we get out of the loop.
Step 6:
Changing the title in Pygame
Pygame.display.set_caption(‘RacingBeast’)
Step 7:
Changing the PyGame window Logo
logo=pygame.image.load(‘car game.jpeg’)

51
pygame.display.set_icon(logo)

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('.\\img\\car.png')
self.car_x_coordinate = (self.display_width * 0.45)
self.car_y_coordinate = (self.display_height * 0.8)
self.car_width = 49
# enemy_car
self.enemy_car = pygame.image.load('.\\img\\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(".\\img\\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
52
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 Dodge')
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):
self.car_x_coordinate -= 50
print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
print ("x: {x}, y: {y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))
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:

53
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)
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("arial", 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 for playing!", True, self.white)
self.gameDisplay.blit(text, (600, 520))
if __name__ == '__main__':
54
car_racing = CarRacing()
car_racing.racing_window()

Output:

Result:

55
Ex. No: 13
Date:
Python program to get a list of dates between two dates

Aim:
To write a python program to get a list of dates between two dates

Algorithm:
Step 1: Start the Program
Step 2: import time delta, date from date time
Step 3: Read the start and end date as input
Step 4: Compute the dates as yield date1 + timedelta(n)
Step 5: Print the dates between the range
Step 6: Stop the Program

Code:
from datetime import timedelta,date
def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 +timedelta(n)
start_dt=date(2021,11, 20)
end_dt=date(2021,12,11)
for dt in daterange(start_dt, end_dt):
print(dt.strftime("%Y-%m-%d"))

Output:

56
Result:

Ex. No: 14
Date:

Python program convert RGB color to HSV color

Aim:
To write a python to convert RGB color to HSV color

Algorithm:
Step 1: Start the Program
Step 2: Intialize the r,g,b values
Step 3: Find the min and max in r,g,b
Step 4: Compute the difference between max and min
Step 5: if mx ==mn compute h as:
h =0
elif mx==r:
h=(60 *((g-b)/df) +360)%360
elif mx==g:
h=(60 *((b-r)/df) +120)%360
elif mx==b:
h=(60 *((r-g)/df)+240)%360
Step 6: Computes if mx == 0:
s =0
else:
s = (df/mx)*100
Step 7: v = mx*100
Step 8: Print h,s,v

Code:
def rgb_to_hsv(r,g,b):
r,g,b = r/255.0, g/255.0, b/255.0
mx= max(r, g, b)
mn = min(r, g, b)
df=mx-mn
if mx == mn:
h =0
elif mx==r:
h=(60 *((g-b)/df) +360)%360

57
elif mx==g:
h=(60 *((b-r)/df) +120)%360
elif mx==b:
h=(60 *((r-g)/df)+240)%360
if mx == 0:
s =0
else:
s=(df/mx)*100
v =mx*100
return h, s,v
print("Sample 1:",rgb_to_hsv(255,255,255))
print("Sample 2:",rgb_to_hsv(200,215,0))

Output:

Result:

58

You might also like