Lab Record (1)
Lab Record (1)
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:
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:
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:
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:
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:
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)
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:
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:
Aim:
To write a Python program with conditional and iterative statements for Number Pattern.
Algorithm:
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:
Aim:
To Write a Python program with conditional and iterative statements for Pyramid Pattern.
Algorithm:
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:
Aim:
To Write a python program to implement items present in library
Algorithm:
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:
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
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:
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
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:
Aim:
To write a python program to implement Components of an automobile using Sets and
Dictionaries.
Algorithm:
Step 3: Compute the set operations add and discard on the automobile component elements
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:
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:
Aim:
To write a python program to implement language system using Sets and Dictionaries
Algorithm:
Step 1: Start the program
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
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:
Aim:
To write a python program to implement reverse of a string using string functions.
Algorithm:
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:
Aim:
To write a python program to implement palindrome using string functions.
Algorithm:
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:
Aim:
To write a python program to implement Characters count using string functions.
Algorithm:
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:
Aim:
To write a python program to implement Replacing Characters using string functions.
Algorithm:
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
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
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:
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:
Algorithm:
Step 1: Start the program
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:
Aim:
To write a python program to implement carrace using pygame tool
Procedure:
Step1:
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
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:
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