0% found this document useful (0 votes)
1 views46 pages

Python Lab Exercise

python lab excersice

Uploaded by

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

Python Lab Exercise

python lab excersice

Uploaded by

jan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
and Iterative loops Operations of tand Tuples a) Write a Python tuple operations for Library b) Write a Python tuple operations for Mate frequired for construction of a building Write a Python list Operations for Components of a car details als t Sets and Dictionaries 18 Write a Python program to implement the Programming Language details using Set operations ee PROBLEM SOLVING AND Prtyoy P; b) Write a Python program to implement the components of an automobile using Dictionaries Functions Write a Python program for Factorial using Functions using Functions. Strings Implementing Python program using Strings (reverse, palindrome, character count, replacing characters) Pandas, NumPy, Matplotlib & SciPy Implementing programs using written modules and Python Standard Libraries (pandas, numpy, matplotlib, scipy) File handling Write a Python program to Implement copy from one file to another, word count and find the longest word using File handling Exception handling Write a Python program to Implement Divide by zero error using Exception handling b) Write a Python program to check the voter's age validity. Pygame Tool Exploring Pygame tool Game Activity Using Pygame a) Develop a Bouncing Ball game activity using Pygame a) 2 Write a Python program to calculate the Largest number in the list > using Functions Write a Python program to calculate the Area of different Shapes} 95 b) Develop a Car Race game activity using Pygame Slim 1 Solving Simple Real Life Problems Using Flowchart "Dele ste SEE ‘Read the unit values 7 = 7 ¥*5 | ame=25e(unitSOPO7S S_charges=amt*0.20 amt=25e(unk-sop-a7s S_charges-amtt0.20 amt=220+(unit-250)*1.50 Total_amt=amtss charges Prone ovine Aun Prion Poona, Vb) Dovolop a Flowchart for Shop billing. (Ct )) | ves tt’) | is tate -input( enter the of Discount’) | Discounts price *bis_rate/100 | pricesprice discount | Print("price before Discou discount: Rs.” Pricey , Print(“discounst rate ate) J : : Print("pricesRs Print(“discount amount ZR Discount) Lo / We) u Print("Price after Discount=Rs "Discounted price ¥ i stop ne La t= (t*(-1) *x* x)/ (Que (2 te 1) sum = sum+t Print “Sin” + (y) print “is” + sum eee! Late) ) Prosiem Sotvinc Ano PyTHoN PROGRAMMING 1d) Develop a Flowchart for weight of steel bar Flowchart D? = eR Gar) Head Read D, L Eg: D (diameter) = 10 mm (10)? 100 Wt= =——— 1622 1622 | wt=0.616 kg/m i ees Wt =0616x2 =1232kg. Professional Pree Lo le Statements And Expressions simp! a Python program to exchange the values of two variables. Towrite a Python program for exchange the values of two variables. Algorithm Step 1: Start the program. Step 2: Get the values from user. ‘Step 3: Swap both the values using temporary variables. Step 4: Print the swapped outpt. Step 5: Stop the Program. Program: // Exchange the values of two variables print("Enter the value for A:") a=int(input()) print("Enter the value for B:”) b=int(input()) print(Before Exchanging the Values’) print(’A="a/'B="b) temp =a a=b b=temp print("After Exchanging the values of variables") print(’A="a/'B="b) ( rice NAST POU) Prostem Sowvinc AND PYTHON a: Result Thus the Python program for swapping two variables loops was executed successfully. 2.b) Write a Python program to Circulate the Values of n Variables Aim To write a Python program for Circulate the Values of n Variables Algorithm Step 1: Start the program. Step 2: Get the number of values from user. Step 3: Declare the array variable. Step 4: Get the list values from user and append it Step 5: Circulate the list values by using for loop. Step 6: Print the circulated output. Step 7: Stop the program. Program //Circulate the Values of n Variables ‘no_of_terms = int(input("Enter number of values :")) teehee EXPERIENCES Pree list) = 0 for val in range(0,no_of_terms,1): element = int(input(“Enter integer :")) list] .append(element) print(‘Circulating the elements of list’ list) for val in range(0,no_of_terms,1): element = list! .pop(0) [Link](element) print(list1) Output Enter number of values : 4 Enter integer : 10 Enter integer : 20 Enter integer : 30 Enter integer : 40 Circulating the elements of ist [10, 20,30, 40) [20, 30, 40, 10] [30, 40, 10, 20] [40, 10, 20, 30] [10, 20, 30, 40] a Result Thus the Python program for Circulate the Values of nVariabl les was executed successfully: * ty We Python program fo find the iste between 4o Pl ing built in functions. Ai a ult in functions, To write a Python program for Distance between two points using b Step 1: Start the program. Step 2: Import the math module. Step 3: Get the four values from user. step 4: Calculate the Distance between two points by usin Step 5: Print the Distance between two points output. [Link] built in function Step 7: Stop the program, Program //Distance between two points import math x1=int(input("Enter the value for x1:”)) y1=int(input(“Enter the value for y1:")) x2=int(input(“Enter the value for x2:”)) y2=int(input(“Enter the value for y2:”)) distance=[Link](((x2-x1)**2)+((y2-y1)"*2)) print("The distance between two points is“\distance) Output == RESTART: C:/Users/SUGA PRIYA/AppData/Local/Programs/Python/Python39/lab manual/[Link]=== Enter the value for x1:2 Enter the value for y1:3 Enter the value for x2:5 Enter the value for y2:6 The distance between two points is 4.242640687119285 Result | Th ‘i lus the Python program for Distance between two points was executed successfully. jonals and Iterative Loops 3.0) Write o Python program for Number series using Conditionals and Weratve loops. Aim Jo write a Python program for Number series using Conditional Algorithm Step 1: Start the program. Is and Iterative loops. Step 2: Initialize the array variables. Step 3: Get the values from the user. Step 4: Check the range value by using for loop. Step 5: Process the N series of numbers until the loop ends Step 6: Append all the numbers one by one. Step 7: Print the result. Step 8: Stop the Program. Program neint(input(“Enter a number:")) a= fori in range(1, n+1): print(i, sep="", end="") iffi 1): fact*=n, n-=1 return fact # Driver Code um = int(input("Enter th é »). Print("Factorial of oi Output Enter the number: 4 num,'is;factorial(num)) @ Lefties ral factorial of 4 1s 24 Enter the number: 6 factorial of 6 is 720 Result thusthePythonpr an oan fogram for Factorial using user defined Functions Was: executed successfully. program to calculate the Largest number in the list using Functions. Aim i . vi a Python program to calculate the largest number in the list using Functions. Step 1: Start the program. Step 2: Initialize the list values. Step 3: Call the appropriate user defined function (function name: large())- Step 4: Declare the first element as max within the def function. Stop 5: Compare each element by using for loop. Step 6: Find the largest element by using if conditions Step 7: Then retum the largest element present in the initialized list. Step 8: Stop the Program. Program def large(arr): #root element variable max =arr[0] for elem in arr: if(elem > max): max = elem return max list) = (1,4,5,2,6) result = large(list!) print(result) Output 6 Result Thus the Python program. for largest number in the list successfully. ll Aas — using Functions was executed i Professional () CRY Prooiem SoLvinc AND PYTHON Pri irl 6 ¢) Write a Python program to calculate the Area of different Shapes using Functions, - tea Python program to calculate the Area of different Shapes using Functions, fo write a Algorithm Step 1: Start the program. Step 2: Get the shape from user for calculating the area. Step 3: Call the appropriate user defined function Step 4: Calculate the area of different Shapes like rectangle, square, triangle, circle and parallelogram) Step 5: Print the area value. Step 6: Stop the Program. Program “def calculate_area(name): # converting all characters into lower cases name = [Link]() # check for the conditions if (name =="rectangle"): |= int(input("Enter rectangle’s length:”)) b=int(input(“Enter rectangle’s breadth:")) # calculate area of rectangle t_area=|*b Print(f’The area of rectangle is {t_area}.”) elif (name =="square”): $= int(input("Enter Square's side length:”)) # calculate area of square 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= intlinput(“Enter triangle’s breadth length:”)) # calculate area of triangle tr_area=0.5*b*h ae a print(f”The area of triangle is {tri_area}”) elif (name == "“circle"): int(input(“Enter circle’s radius length:")) 14 pi # calculate area of circle circle_area=pi*r*r print("The area of triangle is(circle_area}”) elif name =="parallelogram): = int(input(“Enter parallelogram’ base length:”)) = int(input(“Enter parallelogram’ height length:")) # calculate area of parallelogram para_area=b*h printf"The area of parallelogram isipara_area}”’) else: print("Sorry! This shape is not available”) # driver code if__name__=="_main_": print(“Calculate Shape Area”) shape_name = input("Enter the name of shape whose area you want to # function calling calculate_area(shape_name) Output Calculate Shape Area Enter the name of shape whose area you want to find: square Enter squares side length: 5 The area of square is 25. >> Programs/Python/Python39/lab manual/[Link] Calculate Shape Area Enter the name of shape whose area you want to find: rectangle Enter rectangle’s length: 5 Enter rectangle's breadth: 3 find:”) == RESTART: C:/Users/SUGA PRIVA/AppData/Local/ @ UConn \ cate tsigd TT, EIS = The area of rectangle is 15. >> RESTART: _C:/Users/SUGA PRNA/APPDatatoeay Programs/Python/Python39/lab manual/[Link] = Calculate Shape Area i Enter the name of shape whose area you want to find: triangle Enter triangle’s height length: 5 Enter triangle’s breadth length: 3 The area of triangle is 7.5. RESTART: C/Users/SUGA PRIYA/AppDatay Programs/ Python/Python39/lab manual/[Link] = Calculate Shape Area Enter the name of shape whose area you want to find: circle Enter circle’s radius length: 3 ‘The area of triangle is 28.259999999999998, Localy RESTART: — C:/Users/SUGA Programs/Python/Python39/lab manual/[Link] Calculate Shape Area PRIYA/AppData, Local Enter the name of shape whose area you want to find: parellogram Sorry! This shape is not available >>> RESTART: — C:/Users/SUGA Programs/Python/Python39/lab manual/[Link] Calculate Shape Area Enter the name of shape whose area Enter parallelogram’s base length:3 Enter parallelogramis height length:?. ‘The area of parallelogram is 6, Result Thus the Python p ram for i successfully, “oaram for Area of diferent Shapes using Functions was executed you want to find: parallelogram : Lites ee Need Strings {Implementing Python program using Strings (reverse, palindrome, character count, replacing characters) Aim jing the string, To Write a python program for implementing the string methods for reversing : ir heck whether counting the character in a string, replacing a character in the string and cl the given string is palindrome or not, Algorithm Step 1: Start the program Step 2: Get the string from the user in the variable(str). Step 3: Using the string method [:-1], for displaying the reverse of the string. Step 4: Using the function is Palindrome, check whether the string is palindrome or not. Step 5: Using the string method {en(str), for finding the length of the given string. Step 6: Using the string method replace(), for replacing a character in the string. Step7: Stop the program. Program defisPalindrome(s): 1] str=input(‘Enter the String:’) return s=: Print("The Reverese of the string is" str:-1}) check_palin = isPalindrome(str) ifcheck_palin: brint("The Given String ("str is a Palindrome”) else: rint("The Given String (iste)is nota Palindrome”) Print("The length of the given string is len(str)) Print Replace a characterin the sti ing "strseplacetmth)) Sr oes er) Le Prose SOLVING AND PrrHon p; Output - 1 Enter the String:madam The Reverese of the string is madam The Given String ( madam ) is a Palindrome The length of the given string is 5 Replace a character in the string hadam Output - 2 Enter the String:machine The Reverese of the string is enihcam The Given String (machine) is nota Palindrome The length of the given string is 7 Replace a character in the string hachine Result Thus the Python program for imple! counting the character in a string, the given string is palindrome or not was Pandas, NumPy, Matplotlib & SciPy menting the string methods for reversing the s replacing a character in the string and check w implemented successfully. ‘Standard Libraries (pandas, numpy, matplotlib, scipy) ‘The word pandas is an acronym which is derived from “Python and data ana\ys “panel data’ Pandas is a software library written for the Python programming language. “+ Itis used for data manipulation and analysis. + Itprovides sie ee nema ee remenipulation of numerical and time series. Pandas is free software. terete lien Peake es) wo important data structures of Pandas: + Series * DataFrame Series: A Series = is = raiding any data type, 9. a one-dimensional labelled array-like object. It's capable of ‘data structure with pi integers, floats, strings, Python objects, and so on. tan paceenias Rae i he other one contains the actual date ning as the index, [Link] labels, andt DataFrame: Feral fe: Like a spreadsheet or Excel sheet, a DataFrame object contains an eee in ae GF columns. Each coluran eonsesi cf alenlerc# Ee at different femmes avescliterent types, e.g, the figs column may consist of integers while the second one consists of boolean values and so on. To yereert Pandas and NumPy in your Python script, add the below piece of ode: import pandas as pd “import numpy as np NumPy NumPy means “Numeric Python” or“Numerical Python". ¢ NumPyis the fundamental package for scientific computing in Python. ItisaPython library that provides a multidimensional array: ‘object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations ‘on arrays, including mathematical, logical, shape manipulation, sorting, selecting, /O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more. Program. import numpy as np # Initial Array arr=nparray(({-1, 2,0,41, (4,-0.5, 6,01, (2.6, 0,7, 8], 3,-7.4 2.0])) print(“Initial Arrays") print(arr) # Printing a range of Array Prosien Sou Avo PYTHON Prog # with the use of slicing method an e a - 2 rows and” alternate columns(0 and 2):\n’, sliced_ary print (" : are ‘elements at # specific Indices Index_arr = arr{{1, 1, 0, 3], i 8,2,1,01 Print ("\nElements at indices (1, 3),” “(1,2), (0, 1), (3, 0)\n Index_arr) Output (NumPy) Initial Array: (H. 2.0, 4) (4. -05 6. 0.) | (260. 7. 8) 3.7.4 27 ) roduces publication quality Y figures ing lents Across platforms, ts of arrays, built on NumPy arra ys. and YS a or import [Link] as pit gosit plots in Matplotlib: 3 Matplotlib comes with a wide variety of plots. ‘g Plotshelps to understand trends, patterns, and to make correlations. if the gy They'e typically instruments for reasoning about quantitative information. Some of sample plots are covered here. Program for Line plot : # importing matplotlib module from matplotlib import pyplot as pit # x-axis values x=[5,2,9,4,7] # Y-axis values y=110,5,8,4,2) # Function to plot [Link](xy) # function to show the plot [Link]() Output (lineplot) Tom iets d tenes Program for Bar plot : # importing matplotlib module from matplotlib import pyplot as plt # x-axis values x= [5,2,9, 4,7] # Y-axis values y =[10,5,8, 4, 2] # Function to plot the bar [Link](x,y) # function to show the plot [Link]() Output (Bar plot) PRostem SOLVING AND PYTHON Prog oo _— ———————— RAMMING SciPy stands for Scientific Python. SciPy isa f ree and open-source Python library used for scientific computing and technical computing Itisa collection of mathematical algorithms and convenience functions built on the NumPy extension of Python. session by providing the user with It adds significant power to the interactive Python d visualizing data. high-level commands and classesfor manipulating an ciPy, there is no 4 Asmentioned earlier, SciPy builds on NumPy and therefore if you import need to import NumPy. Install SciPy using pip ‘Install the SciPy library by using the pip command. s+ Pip is basically a recursive acronym which stands for'Pip Installs Packages: Itis a standard package manager which can be installed in most of the operating systems. minal: pip install scipy To install, run the following command in the ter Install SciPy using Anaconda Conda install -c anaconda scipy Sub packages in SciPy computing, and SciPy is ‘ols are necessary for Python scientific an work with in order to “Many dedicated software to’ ring many Python modules that we ¢ ‘one such tool or library offe perform complex operations. Prosiem Sowvinc Ano PytHon The following table shows some of the modules or sub-packages that can be used for computing: [Link].] Sub-Package ; Description ] Cluster algorithms are used to vector 1. | [Link] quantization/ Kmeans 2. | [Link] It represents physical and mathematical constants. 3. | scipysftpack Ttis used for Fourier transform 4, |[Link] Integration routines 5. | [Link] =} Interpolation Itis used for linear algebra routine. 6. | scipylinalg 7. | scipyio Itis used for data input and output 8. | [Link] Itis used for the n-dimension image Pe [Link] Orthogonal distance regression 10. | scipycoptimize Itis used for optimization 11. | scipysignal Itis used in signal processing 12. PV scpvsparse Sparse matrices and associated routines 3. [scevspai Spatial data structures and algorithms 14. | [Link] Special Function 15. | [Link] | statistics — 16. | [Link] Itis a tool for writing bowels Result Thus, we study about Pandas, NumPy. Matplotlib, SciPy applications, installation procedure and also implement the sample program successfully. Ri Handling program to Implement copy from one file to another, word count and find } word using File handling andling operation for performing Jo write a python program for implementing the file h t of one file into another. word countin the file, longest word in thefile and copy the content rithm J; Start the program “Step 2: Create a text file as text txt and type content in it. Step 3: Open the file fl (“text txt’) in the read mode. Step 4: Create the file f2 (“[Link]’) in the write mode. Step 5: Read the content from the file and write into file2. Step 6: Close the two files f1 and f2. xt”) in the read mode. - Step 7: Open the file f3 (“text1.0 method read().split() and stor’ .e contents from the file £3 using the ed it in the Step 8: Read thi variables “words’ "Step 9: Print the word count in the file. loop and if statement, print the longest word in the file. Step 10: Using fo! Step 11: Stop the program. text [Link] hello this is my python programming ™ Pronven Sov AND PYTHON Proc, Program fl=open("text!.txt7r") f2=open(e:\\[Link]/w’) str=flread() f2write(str) print("Content of File1(f1) is read and it will be write to File2(f2)") [Link])) [Link]() £3=open("text!.txt’7’r”) words=[Link]().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) #[Link]() Output Content of File1(f1) is read and it will be write to File2(f2) The word count in the file(f3) is 6 The Longest Word in the file(f3) is programming Result Thus the Python program for implementing the file handling operation for performing word count in the file, longest word in the file and copy the content of one file into another was implemented successfully. n Handling ‘a Python program to implement Divide by zero error using Exception 9 write a Python program to implement Divide by zero error using Exception handling » 1: Start the program. Get the dividend and divisor values from the user. 3: Calculate the quotient value using Try Block. » 4: Check the Divide by zero error in Catch Block 5: Print the Exception handling output 6: Stop the Program. paint(input(“Enter the value of divident(n):")) _deint(input(“Enter the value of divisor(d):”)) input("Enter the value of divisor(c):")) ceint print(“Quotient:q) ‘except ZeroDivisionError: print(“Division by Zero") put "Enter the value of divident(n):6 Enter the value of divisor(d):3 Enter the value of divisor(c):3 Division by Zero Mt "Thus the Python program for successfully. Divide by zero error using Exception handling was implemented (sc) Professional WZ) Publishers ey 10 b) Write a Python program to check the voter's age validity. Aim ” lidity. To write a Python program to check the voter's age validity. Algorithm Step 1: Start the program. Step 2: Get the Voter's name and age from tne ee Step 3: Calculate the eligibility of voter's age in Try Block. th Block ‘Step 4: Check the Value Error in Cate! i ea Step 5: Print the eligibility status of voter’s age using Exception handling, Step 6: Stop the Program. Program name=input(“Enter the Voter Name:”) try: age=int(input(“Enter your age”)) ifage>18: Print("Eligible to vote”) else: Print(“Not eligible to vote”) #display exception’s default error message except ValueEtror as err: print(err) else: # code to be excuted when there i Print("Thank you, Output 1 Enter the Voter Name: Karthick Enter your age: 28 Eligible to vote Thank you, you have Successfully checked the voting eligibility 2 Sno exception you have successfully checked the Voting eligibility”) Enter the Voter Name: Ram Enter your, ageithiry invalid literal for int with base 10:'thiry’ Prostem Sotving AND PYTHON PROGR — sthe Python program for voter’ r voter's age validity using Exception handling was implemented and checked successfully. e Learning (NumpPy, has Machin Game development jelds suc and Python has vast libraries for various fi ch, TensorFlow), Matplotlib), Artificial intelligence (Pytor Pygame isa cross-platform set of Python modules. Itis mainly used to create video games. It consists of computer graphics and sound libraries designed to be used with the Python programming language. ySDL. yy Pete Shinners to replace P' n be potentially wrapped Pygame was officially written by Pygame is suitable to create client-side applications that ca! ina standalone executable. Procedure Pygame Installation Python, we should Insti After installing ~ There are two ways fo install Pygame: 1. Installing through pip: 9 through on IDE: all pygame in Windows __2uinstallin 1. Installing through pip: The one way to install Pygame is packages). with the pip tool (which is what python uses to install 4 command py-m pip install -U py: ee eel game —uset > Pronten SOLYNG AND PYTHON Proce, (oo eet (tase i) 2. Installing through an IDE: The second way is to install it through an IDE and using Pycharm ee PyCharm is a cross-platform IDE that provides consistent experience on the Winga,,. macOS, and Linux operating systems. Use the following steps: Open the File tab and click on the Settings option. Select the Project Interpreter and click on the + icon. * _ Itwill display the search box. Search the Pygame and click on the install package button, * Tocheck whether the Pygame is properly installed or not, in the IDLE interpreter, type the following command and press Enter: command import pygame Some Basic Syntax of Pygame 1. import pygame This provides access to the pygame framework and imports all functions of pygame, 2. [Link]() This is used to initialize all the required module of the pygame. 3. Pygame.displayset_mode((width, height)) This is used to display a window of the desired size. The return value is a Surface object which s the object where we will perform graphical operations, 4. [Link]() This is used to empty the event queue. If we do Not call this, the window Messages will start to pile up and, the game will become unresponsive in the opinion of the Operating System. 5. [Link] EXPERIENCES Sample Program import pygame [Link]() screen = [Link].set_mode((400, 300)) done = False while not done for event in [Link]() if [Link] == [Link] done = True 60 [Link](screen, (0, 125 55), pygame Rect(30, 30, 60, 60 [Link] flip) Output Result Thus, we study about py9} program successfully. ame tool applications, instalation procedure and also imp the sample - _ ten ied ree Prosten SLING AND PYTHON PRocta uy —— = Game Activity Using Pygame 12.) Develop a bouncing ball game activity using Pygame. Aim To Develop a bouncing ball game activity using Pygame. Algorithm Step 1: Start the program Step 2: Download the ball image and save it in the corresponding folder. Step 3: Import necessary pygame Module. Step 4: Initialize the values such as speed, color, width and height. Step 5: Read and load the image using pygame procedure. Step 6: Give the Bounce Speed within the while loop. Step 7: Bounce the ball using the loop and conditional statements. Step 8: Display the bouncing ball output in screen. Step 9: Stop the program. Program import os osenviron['PYGAME_HIDE_SUPPORT_PROMPT’] =“hide” import sys, pygame from [Link] import * [Link]() speed = [1, 1] color = (255, 250, 250) width = 550 height = 300 Screen = [Link].set_mode((width, height)) [Link].set_caption(‘Pygame bouncing ball”) ball = [Link]("ball png’) rect_boundry = ball. get_rect() while 1: for eventin [Link]): Re : Fect_boundry = rect_boundry move(speed) ifrect_boundry left < 0 or rect_boundry,ight > width: speed(0] = -speed{o} if rect_boundry.top < 0 or Tect_boundry.bottom > height: speed(1] = -speed{} screen fill(color) [Link](ball, rect_boundry) [Link]() if event:type == QUIT: [Link]() [Link]() uted. Thus the bouncing ball game activity using Pygame was successfully exec —" —— him ere To Develop a game activity using Pygame Algorithm acon? eae a aol daaveninhecoresPerin oc, : Download the image such as i Shep 3: Import necessary Module. ; i a Step 5: Read and load the image using pygame PO Shep 6: Declare def functions forall the activity ; Step 7: Start the Car Racing with the! [Link]: : [Link]() [Link] = False [Link] = [Link]('\\ima\\[Link]) 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 = [Link](‘\\img\\enemy_car1.png’) self.enemy_car_startx = [Link](310, 450) self.enemy_car_starty = -600 self.enemy_car_speed = 5 self.enemy_car_width = 49 self.enemy_car_height = 100 # Background selfibgimg = [Link]("\\img\\back_groundjpg’) selfibg_x1 = (self.display_width / 2) - (360/2) self.bg_x2 = (self-display_width / 2) - (360 / 2) self.bg_y1 =0 self.bg_y2 = -600 selfibg_speed = 3 [Link] = 0 def car(self, car_x_coordinate, [Link]([Link], def racing_window(self): ; self gameDisplay = pygal DS ygame _display.set_caption(‘Car Game) self.run_car() run_car(self): car, _y_coordinate): (car_x_coordinate, car_y_coordinate)) [Link]. mode(self.display_width, self.display_height)) ae . Prosiem Souving Ano PytHon PRocns,, Ty Ret 1 for event in [Link](): if [Link] == [Link]: [Link] = True [Link]() quit() # print(event) if ([Link] ¥ygame, KEYDOWN): ygame.K_LEFT): self.car_x_coordinate -= 50 if ([Link] Print (“CAR X COORDINATES: %S"% se elf.car_x_coordinate) if (eventkey =: = pygame.K_RIGHT): self.car_x_coordinate += 50 Print (“CAR X COORDINATES: %s"% self.car_ Print ("x y:(y)"formatix=: selfgameDisplay fll seltblack) selftback_ground_raod() X_coordinate) self.car_x_coordinate, y=self.car_y_coordinate)) selfrun_enemy car(selfenemy car_startx, self'enemy_car_starty += selfenemy_car_starty) selfienemy_car_speed if selfienemy_car_starty > self.display_height: selfenemy_car_starty =0- selfenemy_car_height selfenemy_car_startx = [Link](310, 450) [Link](self.car_x_coordinate, self.car_y coordinate) Self highscore(self count) [Link] += 1 if ([Link] % 100 == 0): selfenemy car_speed +=1 selflbg_speed += 1 if [Link] '_Y_coordinate < selfenemy car_starty + selfenemy_car_height: a ater @; ‘+ riemlad ro if (self.car_x_co‘ re > self.enemy_ca x and sel ae {car_x_coordinate > [Link] ; a ¥y_car_startx and self.car_x coordin inate < sel self.enemy_cé ith or sel my _car_width or selfcar_x_coordinate + self.car_width > self idth > selfene y startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx + selfenes starts + self-enemy car_width): [Link] = True self.display_message("Game Over !!!") if self.car_x_coordinate < 310 or self.car_x_coordinate > 460: [Link] = True self.display_messa: [Link]) [Link](60) def display_messagelself msg): font = pygamefontsysFont‘omisansm™s 72, text = [Link](ms9, True, (255, 255, 255)) [Link], (400- text.get_width)) self.display_credit() [Link] selfclockstick(60) sleep(1) car_racinginitialize car racing acing_window def pack ground raodtse: cetigameDislaybitsettban® setigamenislayinseha™s (selfibg_x2, selfibg_y! += [Link]. selfbg_y2*+= selfbg_speed ifselftbg_y’ pz seltdisplay_helght ge("Game Over w’) True) 12,240- textget_height0 //2) (eeltbg x1 seta yt) selfbg_y2)) Proaten SOLvING AND Pyriow p, self.bg_y1 = -600 ifselfbg_y2 >= selfdisplay_height selfbg_y2=-600 def run_enemy_car(sel, thingx, thingy) [Link](self. enemy_car, (thingx, thingy)) def highscore(self, count) font = pygame font SysFont(‘arialt 20) ‘ext [Link](“Score:* + st(count), True, selfwhite) self.g [Link](text, (0, 0)) def display_credit(seif) font = [Link]. SysFont(“lucidaconsole” 14) text = [Link]("Thanks for Playing - Madhu, Ramya’ [Link], blit(text, (500, 420) if__name_ True, [Link]) —Main__': Cat_tacing = CarRacing() ar_racing.racing_window() Output Result

You might also like