100% found this document useful (5 votes)
9K views48 pages

GE3171 Python Programming Lab Manual

This document provides a lab manual for the course GE3171 - Problem Solving and Python Programming Laboratory (REG-2021). It contains 6 sections that cover various Python programming concepts and applications including: 1. Developing flow charts and Python programs for simple problems. 2. Python programming using simple statements and expressions. 3. Scientific problems using conditionals and iterative loops. 4. Implementing applications using lists and tuples. 5. Implementing applications using sets and dictionaries. 6. Implementing programs using functions. Each section contains multiple sub-sections with examples and sample code. The document was compiled by Ramprakash.S, a teaching faculty member in the
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
9K views48 pages

GE3171 Python Programming Lab Manual

This document provides a lab manual for the course GE3171 - Problem Solving and Python Programming Laboratory (REG-2021). It contains 6 sections that cover various Python programming concepts and applications including: 1. Developing flow charts and Python programs for simple problems. 2. Python programming using simple statements and expressions. 3. Scientific problems using conditionals and iterative loops. 4. Implementing applications using lists and tuples. 5. Implementing applications using sets and dictionaries. 6. Implementing programs using functions. Each section contains multiple sub-sections with examples and sample code. The document was compiled by Ramprakash.S, a teaching faculty member in the
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction to Problem Solving with Python
  • Electricity Billing Problem
  • Python Programming Basics
  • Scientific Problems Using Loops
  • Applications Using Data Structures

GE3171 - PROBLEM SOLVING

AND
PYTHON PROGRAMMING
LABORATORY
(REG-2021)

LAB MANUEL

Compiled By:

Ramprakash.S
Teaching Faculty / CSE
University College of Engineering Thirukkuvalai
Nagapattinam -610204, Tamilnadu
[Link] and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.

a) Electricity Billing

Aim: Develop a flow chart and write the program for Electricity billing

Procedure:
From Unit To Unit Rate (Rs.) Prices

From Unit To Unit Rate (Rs.) [Link]


1 100 0 100
101 200 2 200
201 500 3 500-
- 101 -200 3.5 >500
201-500 4.6 >500
>500 606 >500

Flow Chart :
1b) Reatil Shop billing

Flow-Chart:
1c) Sin series

Flow Chart:
1d) To compute Electrical Current in Three Phase AC Circuit

Flow Chart :

Result :
2.a) Python programming using simple statements and expressions -exchange the values
of two variables)

Aim:
Write a python program to exchange the values of two variables

Procedure:

Code:

>>> a=10
>>> b=20
>>> a,b=b,a
>>>print(a)
>>>print(b)

output:

Result:
2b) Python programming using simple statements and expressions - circulate the values
of n variables)

Aim:
Write a python program to circulate the values of n variables

Procedure:

Code:

>>>list=[10,20,30,40,50]

>>>n=2

>>> print(list[n:]+list[:n])

output:

Result:
2 C) Python programming using simple statements and expressions ( Calculate the
distance between two points)

Aim:

Write a python program to calculate the distance between two numbers

Procedure:

Program:

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+d**2
result=[Link](d)
print(result)

Output:

Result:
3 a) Scientific problems using Conditionals and Iterative loops.- Number series

Aim:
Write a Python program with conditional and iterative statements for
Number Series.

Procedure:

Program:
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
[Link](i)
print("=",sum(a))
print()

output:

Result:
3 b) Scientific problems using Conditionals and Iterative loops. -Number Patterns

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

Procedure:

Program:
rows = 6
rows = int(input('Enter the number of rows'))
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('')

output:

Result:
3 c) Scientific problems using Conditionals and Iterative loops. -Pyramid Patterns

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

Procedure:

Program:

def pypart(n):

for i in range(0, n):

for j in range(0, i+1):

print("* ",end="")

print("\r")

n=5
pypart(n)

output:

Result:
4 a) Implementing real-time/technical applications using Lists, Tuples -Items present in a
library)

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

Procedure:

Code:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)

Tuple:

tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ------- Not assigned in tuple
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)
Output:

Result
:
4 b) Implementing real-time/technical applications using Lists, Tuples -Components of a
car

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

Procedure:

Code:
cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]
new_list = []
for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)

Tuple:

cars=("Ferrari", "BMW", "Audi", "Jaguar")


print(cars)
print(cars[0])
print(cars[1])
print(cars[3])
print(cars[3])
print(cars[4])

output:

Result:
4 C) 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

Procedure:

Code:
materialsforconstruction = ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
[Link](“ Tiles”)
[Link](3,"Aggregates")
[Link]("sand")
materialsforconstruction[5]="electrical"
print(materialsforconstruction)

Tuple:

materialsforconstruction = ("cementbags", "bricks", "sand", "Steelbars", "Paint")


print(materialsforconstruction)
del(materialsforconstruction)
print (After deleting materialsforconstruction)
print(materialsforconstruction)
print (“materialsforconstruction[0]:”, materialsforconstruction [0])
print (“materialsforconstruction [1:5]: ", materialsforconstruction [1:5])

output:

Result:
5a) Implementing real-time/technical applications using Sets, Dictionaries. - Language

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

Procedure:

Code:
import re
ulysses_txt = open("books/james_joyce_ulysses.txt").read().lower()
words = [Link](r"\b[\w-]+\b", ulysses_txt)
print("The novel ulysses contains " + str(len(words)))
for word in ["the", "while", "good", "bad", "ireland", "irish"]:
print("The word '" + word + "' occurs " + \
str([Link](word)) + " times in the novel!" )
diff_words = set(words)
print("'Ulysses' contains " + str(len(diff_words)) + " different words!")

output:

Result:

Ref: [Link]
5b) Implementing real-time/technical applications using Sets, Dictionaries. – Components
of an automobile

Aim:
Write a python program to implement Components of an automobile using Sets and
Dictionaries

Procedure:

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

output:

Result:

[Link]
6a. Implementing programs using Functions – Factorial

Aim:
Write a python program to implement Factorial program using functions

Procedure:

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

output:

Result:
6b. Implementing programs using Functions – largest number in a list

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

Procedure:

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:
6c. Implementing programs using Functions – area of shape

Aim:
Write a python program to implement area of shape using functions

Procedure:

Code:

def calculate_area(name):\

name = [Link]()

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}.")

elif name == 'parallelogram':


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is
{para_area}.")

else:
print("Sorry! This shape is not available")

if __name__ == "__main__" :

print("Calculate Shape Area")


shape_name = input("Enter the name of shape whose area you want to find: ")

calculate_area(shape_name)

Output:

Result:
7 a. Implementing programs using Strings –Reverse

Aim:
Write a python program to implement reverse of a string using string functions

Procedure:

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

output:

Result:
7 b. Implementing programs using Strings -palindrome

Aim:
Write a python program to implement palindrome using string functions

Procedure:

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

output:

Result:
7 c. Implementing programs using Strings - character count

Aim:
Write a python program to implement Characters count using string functions

Procedure:

Code:
test_str = "Countthethesisthirdtime"
count = 0
for i in test_str:
if i == 't':
count = count + 1
print ("Count of e in Countthethesisthirdtim is : " + str(count))

output:

Result:
7.d) Implementing programs using Strings – Replacing Characters

Aim:
Write a python program to implement Replacing Characetrs using string functions

Procedure:

Code:

string = "geeks for geeks geeks geeks geeks"


print([Link]("e", "a"))
print([Link]("ek", "a", 3))

output:

Result:
8.a) Implementing programs using written modules and Python Standard Libraries –pandas

Aim:

Write a python program to implement pandas [Link] are denote


python datastructures.

Procedure:

Code:
In command prompt install this package
pip install pandas

import pandas as pd
df = [Link](
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)

print(df)
print(df[“Age”])
ages = [Link]([22, 35, 58], name="Age")
print(ages)
df["Age"].max()
print([Link]())
print([Link]())

output:

Result:
8.b) Implementing programs using written modules and Python Standard Libraries – numpy

Aim:

Write a python program to implement numpy module in python .Numerical


python are mathematical calculations are solved here.

Procedure:

Code: In command prompt install this package


pip install numpy

import numpy as np
a = [Link](6)
a2 = a[[Link], :]
[Link]

output:

Array Creation and functions:

a = [Link]([1, 2, 3, 4, 5, 6])
a = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
[Link](2)
[Link](2)
[Link](4)
[Link](2, 9, 2)
[Link](0, 10, num=5)
x = [Link](2, dtype=np.int64)
print(x)
arr = [Link]([2, 1, 5, 3, 7, 4, 6, 8])
[Link](arr)
a = [Link]([1, 2, 3, 4])
b = [Link]([5, 6, 7, 8])
[Link]((a, b))

Array Dimensions:

array_example = [Link]([[[0, 1, 2, 3],


... [4, 5, 6, 7]],
...
... [[0, 1, 2, 3],
... [4, 5, 6, 7]],
...
... [[0 ,1 ,2, 3],
... [4, 5, 6, 7]]])

array_example.ndim
array_example.size
array_example.shape
a = [Link](6)
print(a)
b = [Link](3, 2)
print(b)
[Link](a, newshape=(1, 6), order='C')

outputs:

Result:
8.c) Implementing programs using written modules and Python Standard Libraries –matplotlib

Aim:

Write a python program to implement matplotolib module in python. .Matplotlib


python are used to show the visualization entites in python.

Procedure:

Code: In command prompt install this package


pip install matplotlib

import [Link] as plt


import numpy as np
[Link]('_mpl-gallery')
x = [Link](0, 10, 100)
y = 4 + 2 * [Link](2 * x)
fig, ax = [Link]()
[Link](x, y, linewidth=2.0)
[Link](xlim=(0, 8), xticks=[Link](1, 8),
ylim=(0, 8), yticks=[Link](1, 8))
[Link]()

output:
import [Link] as plt
import numpy as np
[Link]('_mpl-gallery')
[Link](1)
x = 4 + [Link](0, 1.5, 200)
fig, ax = [Link]()
[Link](x, bins=8, linewidth=0.5, edgecolor="white")
[Link](xlim=(0, 8), xticks=[Link](1, 8),
ylim=(0, 56), yticks=[Link](0, 56, 9))

[Link]()

output

Result:
8.d) Implementing programs using written modules and Python Standard Libraries – scipy

Aim:

Write a python program to implement scipy module in python. .Scipy python


are used to solve the scientific calculations.

Procedure:

Code: In command prompt install this package

pip install scipy

1-D discrete Fourier transforms¶

from [Link] import fft, ifft


x = [Link]([1.0, 2.0, 1.0, -1.0, 1.5])
y = fft(x)
y
array([ 4.5 +0.j , 2.08155948-1.65109876j,
-1.83155948+1.60822041j, -1.83155948-1.60822041j,
2.08155948+1.65109876j])
yinv = ifft(y)
>>> yinv

Output:
from [Link] import fft, fftfreq
>>> # Number of sample points
>>> N = 600
>>> # sample spacing
>>> T = 1.0 / 800.0
>>> x = [Link](0.0, N*T, N, endpoint=False)
>>> y = [Link](50.0 * 2.0*[Link]*x) + 0.5*[Link](80.0 * 2.0*[Link]*x)
>>> yf = fft(y)
>>> xf = fftfreq(N, T)[:N//2]
>>> import [Link] as plt
>>> [Link](xf, 2.0/N * [Link](yf[0:N//2]))
>>> [Link]()
>>> [Link]()

Output:

Result:
9.a) Implementing real-time/technical applications using File handling - copy from one file
to another.

Aim:
Write a python program to implement File Copying

Procedure:

Code:

import shutil
original = r'original path where the file is currently stored\file [Link] extension'
target = r'target path where the file will be copied\file [Link] extension'
[Link](original, target)

Steps to follow:
Step 1: Capture the original path
To begin, capture the path where your file is currently stored.
For example, I stored a CSV file in a folder called Test_1:
C:\Users\Ron\Desktop\Test_1\[Link]
Where the CSV file name is „products„ and the file extension is csv.
Step 2: Capture the target path

Next, capture the target path where you‟d like to copy the file.

In my case, the file will be copied into a folder called Test_2:

C:\Users\Ron\Desktop\Test_2\[Link]

Step 3: Copy the file in Python using [Link]

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\[Link]'
target = r'C:\Users\Ron\Desktop\Test_2\[Link]'

[Link](original, target)
Ref :[Link]

Result:
9.b ) Implementing real-time/technical applications using File handling word count

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

Procedure:

Code:

Create file [Link] with the following input

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

file = open("C:\[Link]", "rt")


data = [Link]()
words = [Link]()
print('Number of words in text file :', len(words))

output:

Result:
9.c ) Implementing real-time/technical applications using File handling - Longest word

Aim:
Write a python program to implement longest word in File operations

Procedure:

Code:

Create a file [Link] and give the longest word

(e.x) hi I have pendrive


def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('[Link]'))

output:

Result:
10. a. Implementing real-time/technical applications using Exception handling.- divide by
zero error.

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

Procedure:

Code:
(i) marks = 10000

a = marks / 0

print(a)

(ii) program
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

output:

Result:
10. C. Implementing real-time/technical applications using Exception handling.- Check
voters eligibility

Aim:
Write a exception handling program using python to depict the voters eligibility

Procedure:

Code:
try:
#this program check voting eligibility
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()

output:

Result:
11. Exploring Pygame tool.

Aim:
Write a python program to implement pygame

Procedure:

Code:
To install Pygame in command prompt

Pip install pygame


PIP install pygame

import pygame

from [Link] import *

class Square([Link]):
def __init__(self):
super(Square, self).__init__()
[Link] = [Link]((25, 25))
[Link]((0, 200, 255))
[Link] = [Link].get_rect()

[Link]()

screen = [Link].set_mode((800, 600))


square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
gameOn = True

while gameOn:

for event in [Link]():


if [Link] == KEYDOWN:
if [Link] == K_BACKSPACE:
gameOn = False
elif [Link] == QUIT:
gameOn = False

[Link]([Link], (40, 40))


[Link]([Link], (40, 530))
[Link]([Link], (730, 40))
[Link]([Link], (730, 530))
[Link]()

Output:

Result:
12.a ) Developing a game activity using Pygame like bouncing ball.

Aim:

Write a python program to implement bouncing balls using pygame tool

Procedure:

Code:

import sys, pygame

[Link]()

size = width, height = 800, 400

speed = [1, 1]

background = 255, 255, 255

screen = [Link].set_mode(size)

[Link].set_caption("Bouncing ball")

ball = [Link]("[Link]")

ballrect = ball.get_rect()

while 1:

for event in [Link]():

if [Link] == [Link]:

[Link]()

ballrect = [Link](speed)

if [Link] < 0 or [Link] > width:

speed[0] = -speed[0]
if [Link] < 0 or [Link] > height:

speed[1] = -speed[1]

[Link](background)

[Link](ball, ballrect)

[Link]()

output:

Result:
12.b ) Developing a game activity using Pygame like Car race

Aim:

Write a python program to implement car race using pygame tool

Procedure:

Code:

import pygame, random, sys ,os,time


from [Link] import *

WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3

def terminate():
[Link]()
[Link]()

def waitForPlayerToPressKey():
while True:
for event in [Link]():
if [Link] == QUIT:
terminate()
if [Link] == KEYDOWN:
if [Link] == K_ESCAPE: #escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if [Link](b['rect']):
return True
return False

def drawText(text, font, surface, x, y):


textobj = [Link](text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
[Link] = (x, y)
[Link](textobj, textrect)

# set up pygame, the window, and the mouse cursor


[Link]()
mainClock = [Link]()
windowSurface = [Link].set_mode((WINDOWWIDTH, WINDOWHEIGHT))
[Link].set_caption('car race')
[Link].set_visible(False)

# fonts
font = [Link](None, 30)

# sounds
gameOverSound = [Link]('music/[Link]')
[Link]('music/[Link]')
laugh = [Link]('music/[Link]')

# images
playerImage = [Link]('image/[Link]')
car3 = [Link]('image/[Link]')
car4 = [Link]('image/[Link]')
playerRect = playerImage.get_rect()
baddieImage = [Link]('image/[Link]')
sample = [car3,car4,baddieImage]
wallLeft = [Link]('image/[Link]')
wallRight = [Link]('image/[Link]')

# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) -
30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT /
3)+30)
[Link]()
waitForPlayerToPressKey()
zero=0
if not [Link]("data/[Link]"):
f=open("data/[Link]",'w')
[Link](str(zero))
[Link]()
v=open("data/[Link]",'r')
topScore = int([Link]())
[Link]()
while (count>0):
# start of the game
baddies = []
score = 0
[Link] = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
[Link](-1, 0.0)

while True: # the game loop


score += 1 # increase score

for event in [Link]():

if [Link] == QUIT:
terminate()

if [Link] == KEYDOWN:
if [Link] == ord('z'):
reverseCheat = True
if [Link] == ord('x'):
slowCheat = True
if [Link] == K_LEFT or [Link] == ord('a'):
moveRight = False
moveLeft = True
if [Link] == K_RIGHT or [Link] == ord('d'):
moveLeft = False
moveRight = True
if [Link] == K_UP or [Link] == ord('w'):
moveDown = False
moveUp = True
if [Link] == K_DOWN or [Link] == ord('s'):
moveUp = False
moveDown = True

if [Link] == KEYUP:
if [Link] == ord('z'):
reverseCheat = False
score = 0
if [Link] == ord('x'):
slowCheat = False
score = 0
if [Link] == K_ESCAPE:
terminate()

if [Link] == K_LEFT or [Link] == ord('a'):


moveLeft = False
if [Link] == K_RIGHT or [Link] == ord('d'):
moveRight = False
if [Link] == K_UP or [Link] == ord('w'):
moveUp = False
if [Link] == K_DOWN or [Link] == ord('s'):
moveDown = False

# Add new baddies at the top of the screen


if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =30
newBaddie = {'rect': [Link]([Link](140, 485), 0 - baddieSize, 23,
47),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link]([Link](sample), (23, 47)),
}
[Link](newBaddie)
sideLeft= {'rect': [Link](0,0,126,600),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link](wallLeft, (126, 599)),
}
[Link](sideLeft)
sideRight= {'rect': [Link](497,0,303,600),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link](wallRight, (303, 599)),
}
[Link](sideRight)

# Move the player around.


if moveLeft and [Link] > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and [Link] < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and [Link] > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and [Link] < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)

for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
[Link](b)

# Draw the game world on the window.


[Link](BACKGROUNDCOLOR)

# Draw the score and top score.


drawText('Score: %s' % (score), font, windowSurface, 128, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)
drawText('Rest Life: %s' % (count), font, windowSurface,128, 40)

[Link](playerImage, playerRect)

for b in baddies:
[Link](b['surface'], b['rect'])

[Link]()

# Check if any of the car have hit the player.


if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
g=open("data/[Link]",'w')
[Link](str(score))
[Link]()
topScore = score
break

[Link](FPS)

# "Game Over" screen.


[Link]()
count=count-1
[Link]()
[Link](1)
if (count==0):
[Link]()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT
/ 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) -
80, (WINDOWHEIGHT / 3) + 30)
[Link]()
[Link](2)
waitForPlayerToPressKey()
count=3
[Link]()

Output:

Result:
Refrences:

 [Link]/

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

Common questions

Powered by AI

The program uses conditional statements (`if`, `elif`, `else`) to determine the shape for which the area is to be calculated based on user input. It uses specific formula implementations depending on whether the input corresponds to a rectangle, square, triangle, circle, or parallelogram. This exemplifies the use of conditional logic to handle multiple cases in a program where the flow depends on variable input values, showcasing decision-making based on evaluations .

The program uses both lists and tuples to manage library items. Lists are mutable, allowing dynamic changes such as adding or removing items, while tuples are immutable, which makes them suitable for fixed collections of items. Using these structures supports efficient data management by leveraging the dynamism of lists for frequent modifications and the static nature of tuples for data integrity when changes aren't needed .

The Set data structure in Python is suitable for describing components of an automobile due to its characteristics: it stores unordered, unique items, which is useful for ensuring there are no duplicate entries for car components. Python handles set operations efficiently; for instance, using `add()` to insert new elements and `discard()` to remove elements without causing an error if the item is not present. These characteristics make sets particularly advantageous for inventory and unique item list tracking .

In Python, recursion refers to a function calling itself to solve smaller instances of a problem, demonstrated in calculating factorials with a base case (e.g., if `n==0: return 1`) and recursive step (e.g., `else: return n * factorial(n-1)`). This method's advantages include elegant code for naturally recursive tasks and clear logical flow for divided problem-solving. However, challenges include high memory usage and stack overflow risks due to excessive recursive depth and inefficiencies compared to iterative approaches in some scenarios .

Exception handling enhances the robustness of a Python program by allowing it to manage errors without crashing. In the voter eligibility checking program, the use of `try` and `except` blocks captures potential input errors (e.g., entering non-numeric data) and provides a user-friendly message ('age must be a valid number'). This approach ensures that unexpected errors do not terminate the program abruptly, maintaining its stability .

Modules like Pandas and Numpy play a critical role in expanding Python's functionality for data analysis and mathematical computations. Pandas provide versatile data structures (DataFrames, Series) facilitating data manipulation and analysis, while Numpy offers robust functions for numerical operations, enabling efficient array processing and mathematical modeling. These modules significantly enhance Python's capabilities for complex data-driven tasks, supporting both simple and sophisticated computations .

Iterative loops, such as `for` and `while`, are essential in generating number and pyramid patterns by repetitively executing a block of code for a specified range or condition. These loops utilize the computational principle of iteration, allowing certain actions to be repeated until a desired pattern is achieved. For example, nested loops enable the printing of tiered patterns, and conditionals within loops enhance control over pattern sequences. This approach exemplifies structured programming and algorithmic processes .

Python checks for palindromes by comparing a string to its reverse, accomplished using slicing (`string[::-1]`). This method highlights several fundamental properties of strings, including their immutability and sequence nature, allowing easy application of operations like slicing for reversed order. The process demonstrates Python's efficient handling of character sequences and its adaptability for logical operations such as comparisons .

In managing file operations, Python reads text data from files using methods such as `read()` for full file content retrieval. It utilizes `split()` to parse the content into words, allowing tasks like word counting by simply evaluating the length of the resulting word list. This process demonstrates Python's ability to manipulate file data efficiently and highlights techniques in text processing and data extraction .

The Python program uses the `replace()` method of strings to handle character replacement. For instance, given a string like 'geeks for geeks', the program replaces occurrences of 'e' with 'a'. The implications of this are that strings in Python are immutable, meaning the program creates a new string with the desired modifications instead of altering the original string .

GE3171 -   PROBLEM SOLVING    
                              AND  
            PYTHON PROGRAMM
1.Identification and solving of simple real life or scientific or technical problems, and 
developing flow charts for the
1b)  Reatil Shop billing 
 
 
   Flow-Chart:
 
 
 
1c)   Sin series 
 
 
 
 
                                               Flow Chart:
 
 
 
 
1d)  To  compute Electrical Current in Three Phase AC Circuit 
 
 
Flow Chart : 
 
Result :
2.a)  Python programming using simple statements and expressions -exchange the values 
of two  variables) 
 
Aim:
2b)  Python programming using simple statements and expressions  - circulate the values 
of n variables) 
 
Aim:
2 C)  Python programming using simple statements and expressions ( Calculate the 
distance between two points) 
 
Aim:
3 a) Scientific problems using Conditionals and Iterative loops.-  Number series 
 
 
Aim: 
                Write a Pyt
3 b) Scientific problems using Conditionals and Iterative loops. -Number Patterns 
 
 
Aim: 
                Write a Py

You might also like