GE3171 -PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
LIST OF EXPERIMENTS:
1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
(Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar,
compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in library/
Components of a car/ Materials required for construction of a building –operations of list &
tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets
& Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries
(pandas, numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
(Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar,
compute Electrical Current in Three Phase AC Circuit, etc.)
Write a program to calculate the electricity bill, we must understand electricity charges and rates.
/*
1 - 100 unit - 1.5/=
101-200 unit - 2.5/=
201-300 unit - 4/=
300 - 350 unit - 5/=
above 300 - fixed charge 1500/=
for example
*/
This program can explain as follows
Declare total unit consumed by the customer using the variable unit.
If the unit consumed less or equal to 100 units, calculates the total amount of consumed
=units*1.5
If the unit consumed between 100 to 200 units, calculates the total amount of
consumed=(100*1.5)+(unit-100)*2.5)
If unit consumed between 200 to 300 units ,calculates total amount
ofconsumed=(100*1.5)+(200-100)*2.5+(units-200)*4
If unit consumed between 300-350 units ,calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-350)*5
If the unit consumed above 350 units, fixed charge – 1500/=
additional charges
if units<=100 – 25.00
if 100< units and units<=200 – 50.00
if 200 < units and units<=300 – 75.00
if 300<units and units<=350 – 100.00
if units above 350 – No additional charges
#program for calculating electricity bill in Python
units=int(input("please enter the number of units you consumed in a month"))
if(units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
fixedcharge=75.00
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
fixedcharge=100.00
else:
payAmount=0
fixedcharge=1500.00
Total=payAmount+fixedcharge;
print("\nElecticity bill=%.2f" %Total)
i) Electricity bill calculation – with and operator
Program 2
#program for calculating electricity bill in Python using and operator
units=int(input("Number of unit consumed: "))
if(units>0 and units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units>100 and units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units>200 and units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
fixedcharge=50.00
elif(units>300):
payAmount=2500;#fixed rate
fixedcharge=75.00
else:
payAmount=0;
Total= payAmount+fixedcharge
print("\nElecticity bill pay=%.2f: " %Total);
ii) sin x = x - x3/3! + x5/5! - x7/7! + x9/9! ........
x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
sum = 0
while i<=n:
p=1
fact = 1
for j in range(1,i+1):
p = p*x
fact = fact*j
sign = -1*sign
sum = sum + sign* p/fact
i = i+2
print("sin(",x,") =",sum)
Using function in python
# Import Module
import math
# Create sine function
def sin( x, n):
sine = 0
for i in range(n):
sign = (-1)**i
pi = 22/7
y = x*(pi/180)
sine += ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
# driver nodes
# Enter value in degree in x
x = 10
# Enter number of terms
n = 90
# call sine function
print(round(sin(x,n),2))
i) compute Electrical Current in Three Phase AC Circuit
#pg 200
#calculate the line current, power factor and power supplied
# Given data
from math import cos,acos,sqrt
R = 20.;# in ohm
X_L = 15.;# in ohm
V_L = 400.;# in V
f = 50.;# in Hz
#calculations
V_Ph = V_L/sqrt(3);# in V
Z_Ph = sqrt( (R**2) + (X_L**2) );# in ohm
I_Ph = V_Ph/Z_Ph;# in A
I_L = I_Ph;# in A
print "The line current in A is",round(I_L,2)
# pf = cos(phi) = R_Ph/Z_Ph;
R_Ph = R;# in ohm
phi= acos(R_Ph/Z_Ph);
# Power factor
pf= cos(phi);# in radians
print "The power factor is : ",pf,"degrees lag."
P = sqrt(3)*V_L*I_L*cos(phi);# in W
print "The power supplied in W is",P
The line current in A is 9.24
The power factor is : 0.8 degrees lag.
The power supplied in W is 5120.0
Weight of a steel Bar
steel bar weight formula D²L/162
Weight of a Bike
The horizontal position of a motorcycle’s CG can be easily found by using two scales and
finding how much of the motorcycle’s weight is on each wheel.
x=horizontal position of cg from front axle
Wf=front weight
Wr=rear weight
WB=wheelbase
X =Wr*WB/ Wf+Wr
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
#Python program to demonstrate
# swapping of two variables
x = 10
y = 50
# Swapping of two variables
# using arithmetic operations
x=x+y
y=x-y
x=x-y
print("Value of x:", x)
print("Value of y:", y)
Program to circulate the values of n variables
from collections import deque
lst=[1,2,3,4,5]
d=deque(lst)
print d
d.rotate(2)
print d
Output:[3,4,5,1,2]
(OR)
list=[10,20,30,40,50]
n=2 #Shift 2 location
list[n:]+list[:n]
Output: [30,40,50,10,20]
3. Distance between two points
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns,pyramid pattern)
NUMBER SERIES
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
Python Program to compute sum of following series: 12+22+32.....102
sum=0
for i in range(12, 103, 10) :
print(i,end="")
if(i<102) :
print("+",end="")
sum = sum + i
print("\nSum is : ",sum)
Output :
12+22+32+42+52+62+72+82+92+102
Sum is : 570
# Python Program to calculate Sum of Series 1²+2²+3²+….+n²
number = int(input("Please Enter any Positive Number : "))
total = 0
total = (number * (number + 1) * (2 * number + 1)) / 6
for i in range(1, number + 1):
if(i != number):
print("%d^2 + " %i, end = ' ')
else:
print("{0}^2 = {1}".format(i, total))
# Python Program to calculate Sum of Series 1³+2³+3³+….+n³
import math
number = int(input("Please Enter any Positive Number : "))
total = 0
total = math.pow((number * (number + 1)) /2, 2)
print("The Sum of Series upto {0} = {1}".format(number, total))
# Python Program to calculate Sum of Series 1³+2³+3³+….+n³
import math
def sum_of_cubes_series(number):
total = 0
total = math.pow((number * (number + 1)) /2, 2)
for i in range(1, number + 1):
if(i != number):
print("%d^3 + " %i, end = ' ')
else:
print("{0}^3 = {1}".format(i, total))
num = int(input("Please Enter any Positive Number : "))
sum_of_cubes_series(num)
# This is the example of print simple pyramid pattern
n = int(input("Enter the number of rows"))
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of columns
# values is changing according to outer loop
for j in range(0, i + 1):
# printing stars
print("* ", end="")
# ending line after each row
print()
Output:
*
**
***
****
*****
# This is the example of print simple reversed right angle pyramid pattern
rows = int(input("Enter the number of rows:"))
k = 2 * rows - 2 # It is used for number of spaces
for i in range(0, rows):
for j in range(0, k):
print(end=" ")
k = k - 2 # decrement k value after each iteration
for j in range(0, i + 1):
print("* ", end="") # printing star
print("")
Output:
*
**
***
****
*****
Pattern - 3: Printing Downward half - Pyramid
Code -
rows = int(input("Enter the number of rows: "))
# the outer loop is executing in reversed order
for i in range(rows + 1, 0, -1):
for j in range(0, i - 1):
print("*", end=' ')
print(" ")
Output:
Enter the number of rows: 5
*****
****
***
**
*
Pattern - 4: Printing Triangle Pyramid
Code -
n = int(input("Enter the number of rows: "))
m = (2 * n) - 2
for i in range(0, n):
for j in range(0, m):
print(end=" ")
m = m - 1 # decrementing m after each loop
for j in range(0, i + 1):
# printing full Triangle pyramid using stars
print("* ", end=' ')
print(" ")
Output:
Enter the number of rows: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Pattern - 5: Downward Triangle Pattern
Code -
rows = int(input("Enter the number of rows: "))
# It is used to print space
k = 2 * rows - 2
# Outer loop in reverse order
for i in range(rows, -1, -1):
# Inner loop will print the number of space.
for j in range(k, 0, -1):
print(end=" ")
k=k+1
# This inner loop will print the number o stars
for j in range(0, i + 1):
print("*", end=" ")
print("")
Output:
***********
**********
*********
********
*******
******
*****
****
***
**
*
Pattern - 6: Diamond Shaped Pattern
Code -
rows = int(input("Enter the number of rows: "))
# It is used to print the space
k = 2 * rows - 2
# Outer loop to print number of rows
for i in range(0, rows):
# Inner loop is used to print number of space
for j in range(0, k):
print(end=" ")
1. # Decrement in k after each iteration
k=k-1
# This inner loop is used to print stars
for j in range(0, i + 1):
print("* ", end="")
print("")
# Downward triangle Pyramid
# It is used to print the space
k = rows - 2
# Output for downward triangle pyramid
for i in range(rows, -1, -1):
# inner loop will print the spaces
for j in range(k, 0, -1):
print(end=" ")
# Increment in k after each iteration
k=k+1
# This inner loop will print number of stars
for j in range(0, i + 1):
print("* ", end="")
print("")
Output:
Enter the number of rows: 8
*
**
***
****
*****
******
*******
********
*********
********
*******
******
*****
****
***
**
*
Pattern - 7: Print two pyramid in a single pattern
Code -
rows = input("Enter the number of rows: ")
# Outer loop will print the number of rows
for i in range(0, rows):
# This inner loop will print the stars
for j in range(0, i + 1):
print("*", end=' ')
# Change line after each iteration
print(" ")
# For second pattern
for i in range(rows + 1, 0, -1):
for j in range(0, i - 1):
print("*", end=' ')
print(" ")
Output:
Enter the number of rows: 7
*
**
***
****
*****
******
*******
*******
******
*****
****
***
**
*
Pattern - 8: Hourglass Pattern
Code -
rows = int(input("Enter the number of rows: "))
k = rows - 2
# This is used to print the downward pyramid
for i in range(rows, -1 , -1):
for j in range(k , 0 , -1):
print(end=" ")
k=k+1
for j in range(0, i+1):
print("* " , end="")
print()
# This is used to print the upward pyramid
k = 2 * rows - 2
for i in range(0 , rows+1):
for j in range(0 , k):
print(end="")
k=k-1
for j in range(0, i + 1):
print("* ", end="")
print()
Output:
Enter the number of rows: 5
******
*****
****
***
**
*
*
**
***
****
*****
******
Pattern - 1: Number Pattern
Code -
rows = int(input("Enter the number of rows: "))
# Outer loop will print number of rows
for i in range(rows+1):
# Inner loop will print the value of i after each iteration
for j in range(i):
print(i, end=" ") # print number
# line after each row to display pattern correctly
print(" ")
Output:
Enter the number of rows: 5
1
22
333
4444
55555
Explanation -
In the above code, we have printed the numbers according to rows value. The first row prints a
single number. Next, two numbers, prints in the second row, and the next three number prints on
the third row and so on. In the
Pattern - 2: Half pyramid pattern with the number
Code -
rows = int(input("Enter the number of rows: "))
# This will print the rows
for i in range(1, rows+1):
# This will print number of column
for j in range(1, i + 1):
print(j, end=' ')
print("")
Output:
Enter the number of rows: 5
1
12
123
1234
12345
In the above code, we have printed the column value j in the inner for loop.
Pattern - 3: Inverted Pyramid Pattern
Code -
rows = int(input("Enter the number of rows: 5"))
k=0
# Reversed loop for downward inverted pattern
for i in range(rows, 0, -1):
# Increment in k after each iteration
k += 1
for j in range(1, i + 1):
print(k, end=' ')
print()
Output:
Enter the number of rows: 5
11111
2222
333
44
5
Explanation:
In the above code, we have used the reversed loop to print the downward inverted pyramid where
number reduced after each iteration.
Pattern - 4: Same number Inverted Pyramid
Code -
rows = int(input("Enter the number of rows: "))
# rows value assign to n variable
n = rows
# Download reversed loop
for i in range(rows, 0, -1):
for j in range(0, i):
# this will print the same number
print(n, end=' ')
print()
Output:
Enter the number of rows: 6
666666
66666
6666
666
66
6
Pattern - 5: Descending Order of Number
Code -
rows = int(input("Enter the number of rows: "))
# Downward loop for inverse loop
for i in range(rows, 0, -1):
n = i # assign value to n of i after each iteration
for j in range(0, i):
# print reduced value in each new line
print(n, end=' ')
print("\r")
Output:
Enter the number of rows: 6
666666
55555
4444
333
22
1
Pattern - 6: Print 1 to 10 numbers in Pattern
Code -
current_Number = 1
stop = 2
rows = 3 # Number of rows to print numbers
for i in range(rows):
for j in range(1, stop):
print(current_Number, end=' ')
current_Number += 1
print("")
stop += 2
Output:
1
234
56789
Pattern - 7: Reverse Pattern from 10 to 1
Code -
rows = int(input("Enter the number of rows: "))
for i in range(0, rows + 1):
# inner loop for decrement in i values
for j in range(rows - i, 0, -1):
print(j, end=' ')
print()
Output:
Enter the number of rows: 6
654321
54321
4321
321
21
1
Pattern - 8: Print Odd Numbers
Code -
rows = int(input("Enter the number of rows: "))
i=1
# outer file loop to print number of rows
while i <= rows:
j=1
# Check the column after each iteration
while j <= i:
# print odd values
print((i * 2 - 1), end=" ")
j=j+1
i=i+1
print()
Output:
Enter the number of rows: 5
1
33
555
7777
99999
Pattern - 9: Square Pattern using with number
Code -
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(1, rows + 1):
# Check condition if value of j is smaller or equal than
# the j then print i otherwise print j
if j <= i:
print(i, end=' ')
else:
print(j, end=' ')
print()
Output:
Enter the number of rows: 5
12345
22345
33345
44445
55555
Pattern - 10: Multiplication Number in Column
rows = int(input("Enter the number of rows: "))
for i in range(1, rows):
for j in range(1, i + 1):
# It prints multiplication or row and column
print(i * j, end=' ')
print()
Output:
Enter the number of rows: 8
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Pattern - 1: Right-angled pattern with characters
Code -
print("The character pattern ")
asciiValue = 65 #ASCII value of A
for i in range(0, 5):
for j in range(0, i + 1):
# It will convert the ASCII value to the character
alphabate = chr(asciiValue)
print(alphabate, end=' ')
asciiValue += 1
print()
Output:
The character pattern
A
BC
DEF
GHIJ
KLMNO
Explanation -
In the above code, we have assigned the integer value 65 to asciiValue variable which is an
ASCII value of A. We defined for loop to print five rows. In the inner loop body, we converted
the ASCII value into the character using the char() function. It will print the alphabets, increased
the asciiValue after each iteration.
Pattern - 2: Right-angled Pattern with Same Character
Code -
print("The character pattern ")
asciiValue = int(input("Enter the ASCII value to print pattern: "))
# User - define value
if (asciiValue >= 65 or asciiValue <=122):
for i in range(0, 5):
for j in range(0, i + 1):
# It will convert the ASCII value to the character
alphabate = chr(asciiValue)
print(alphabate, end=' ')
print()
else:
print("Enter the valid character value")
Output:
The character pattern
Enter the ASCII value to print pattern: 75
K
KK
KKK
KKKK
KKKKK
Pattern - 3: Display letter of the word in Pattern
Code -
str1 = "JavaTpoint"
x = ""
for i in str1:
x += i
print(x)
Output:
J
Ja
Jav
Java
JavaT
JavaTp
JavaTpo
JavaTpoi
JavaTpoin
JavaTpoint
We can use any word to print the characters.
Pattern - 5: Equilateral triangle pattern with characters
Code -
print("Print equilateral triangle Pyramid with characters ")
s=5
asciiValue = 65
m = (2 * s) - 2
for i in range(0, s):
for j in range(0, m):
print(end=" ")
# Decreased the value of after each iteration
m=m-1
for j in range(0, i + 1):
alphabate = chr(asciiValue)
print(alphabate, end=' ')
# Increase the ASCII number after each iteration
asciiValue += 1
print()
Output:
Print equilateral triangle Pyramid with characters
A
BC
DEF
GHIJ
KLMNO
Write a Python program to get unique values from a list.
my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
#Set only takes unique values
my_set = set(my_list)
#Converting into list
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
Original List : [10, 20, 30, 40, 20, 50, 60, 40]
List of unique numbers : [40, 10, 50, 20, 60, 30]
Write a Python program to replace last value of tuples in a list
Answer:
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (100,) for t in l])
Implementing real-time/technical applications using Sets, Dictionaries.
Create a dictionary to print square of keys.
Answer:
n=int(input("Input a number "))
#Creating an empty dictionary
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Input a number 5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Write a Python program to find maximum and the minimum value in a set.
Answer:
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
Output
20
Exercise 4:
4. Implementing real-time/technical applications using Lists, Tuples
Items present in library using Lists operations(concatenation and repetitions)
#Items present in library
myList =["books","periodicals",'newspapers','manuscripts','CDs','DVDs','e-
books','student_databases']
#append
myList.append(4)
myList.append(5)
myList.append(6)
for i in range(7, 9):
myList.append(i)
print(myList)
#extend
myList.extend([4, 5, 6])
for i in range(7, 9):
myList.append(i)
print(myList)
#insert
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
#remove
myList.remove('manuscripts')
myList.insert(4, 'CDs')
myList.insert(5, 'DVDs')
myList.insert(6, 'e-books')
print(myList)
#pop
myList.pop(4)
myList.insert(4, 'CDs')
myList.insert(5, 'DVDs')
myList.insert(6, 'e-books')
print(myList)
#slice operations
print(myList[:4]) # prints from beginning to end index
print(myList[2:]) # prints from start index to end of list
print(myList[2:4]) # prints from start index to end index
print(myList[:]) # prints from beginning to end of list
#reverse
print(myList[::-1]) # does not modify the original list
myList.reverse() # modifies the original list
print(myList)
#length
print(len(myList))
#min and max
print(min([1, 2, 3]))
print(max([1, 2, 3]))
#count
print(myList.count(3))
#concatenation
yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)
#repetition
print(myList*2)
#sort
yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
#myList.sort()
#print(myList)
Components of a car using operations of list
T1=(10,50,30,40,20)
T2=('clutch','gearbox','propellershaft','axles','Chassis','Engine','TransmissionSystem','Body')
print (len(T1))
print ('max of T1', max(T2))
print ('min of T1', min(T2))
print ('sum of T1', sum(T1))
print ('T1 in sorted order', sorted(T1))
L1=(110,150,130,140,120)
T1=tuple(L1)
print (T1)
s1=('clutch','gearbox','propellershaft','axles','Chassis','Engine','TransmissionSystem','Body')
T2=tuple(s1)
print ('string to tuple', T2)
#positive indices
print(T1[2:4])
#negative indexing
print(T1[:-2])
#sorted funtion
sorted(T1)
#len() function
print (len(T1))
#index()
print(T2.index('Chassis'))
#count()
print(T2.count(2))
#Membership operator
print('a' in tuple("string"))
#Concatenation
print( (1,2,3)+(4,5,6))
#Logical
print((1,2,3)>(4,5,6))
# Identity
a=(1,2)
print((1,2) is a)
#Addition
t = (2, 5, 0) + (1, 3) + (4,)
print (t);
#SLICING
print(t[2:4])
#MULTIPLICATION
print (t*3);
#DELETING
del (T1);
3) Materials required for construction of a building operations of tuples
TComponents=('Bamboo','Wood','Bricks','Cementblocks','Buildingstone','GravelSand','Cementco
ncrete','Reinforcedconcrete')
LWeight=[300,500,1500,950,2000,1900,2300,2700]
print ('max of T1', max(LWeight))
print ('min of T1', min(LWeight))
print ('sum of T1', sum(LWeight))
#len() function
print (len(TComponents))
#index()
print(TComponents.index('Bricks'))
#count()
print(TComponents.count('Cementconcrete'))
5. Implementing real-time/technical applications using Sets, Dictionaries.
Language operations of Sets & Dictionaries
Components of an automobile
Elements of a civil structure
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
FACTORIAL OF A GIVEN NUMBER
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))
LARGEST NUMBER IN A LIST
def large(arr):
maximum = arr[0]
for ele in arr:
if(ele > maximum):
maximum= ele
return maximum
list1 = []
n=int(input("enter the number of elements"))
for i in range(0,n):
n1=input("enter the elements")
list1.append(n1)
for i in range(0,n):
print(list1[i])
result = large(list1)
print("largest number",result)
AREA OF SHAPE
def square(l):
area=l*l
return area
def rectangle(l,w):
area=l*w
return area
print("Please enter a number to calculate the area of shape")
print("Square = 1")
print("Rectangle = 2")
i = int(input("Enter your choice: "))
if (i==1):
print("calculate the area of Square")
length = int(input("Length: "))
S=square(length)
print("Area of Square is: ", S)
if (i==2):
print("Let's calculate the area of Rectangle")
length = int(input("Length: "))
width = int(input("Width: "))
R=rectangle(length, width)
print("Area of Rectangle is: ", R)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
REVERSE A STRING
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:]) + text[:1]
print(reversed_string("Python Programming!"))
PALINDROME
def isPalindrome(s):
return s == s[::-1]
s = input("enter any string :")
ans = isPalindrome(s)
if ans:
print(s,"Yes it's a palindrome")
else:
print(s,"No it's not a palindrome")
CHARACTER COUNT
def count_chars(txt):
result = 0
for char in txt:
result += 1 # same as result = result + 1
return result
text=input("enter any string")
print("no.of characters in a string",count_chars(text))
REPLACING CHARACTERS
string = "python is a programming language is powerful"
print(string.replace("p", "P",1))
print(string.replace("p", "P"))
8. Implementing programs using written modules and Python Standard Libraries
(pandas, numpy. Matplotlib, scipy)
PANDAS
import pandas as pd
df = pd.read_csv('Data.csv')
print(df.to_string())
NUMPY
import numpy
arr = numpy.array([4, 5,7,8])
print(arr)
Matplotlib
from matplotlib import pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
scipy
from scipy import constants
print(constants.liter)
import numpy as np
from scipy.sparse import csr_matrix
arr = np.array([0, 0, 0, 0, 0, 1, 1, 0, 2])
print(csr_matrix(arr))
9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
#Python Program to copy the contents of one file into another
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
print("copied to out file :",line)
Word count
with open("test.txt") as f:
for line in f:
print("The original string is : " + line)
# using split() function
wordcount = len(line.split())
# total no of words
print ("The number of words in string are : " + str(wordcount))
Longest word
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'))
10. Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)
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
Enter a=4
Enter b=4
a/b result in 0
Voter’s age validity
a=int(input("Enter your age"))
try:
c=a
#Raising Error
if c<18:
raise ValueError
#Handling of error
except ValueError:
print ("not eligible for voting - enter above 18")
else:
print (c)
Student mark range validation
a=int(input("Enter any marks"))
try:
c=a
#Raising Error
if c>0 and c>100:
raise ValueError
#Handling of error
except ValueError:
print ("not correct students mark range value btween 1-100")
else:
print (c)
11. Exploring Pygame tool.
Pygame
o Pygame is a cross-platform set of Python modules which is used to create video games.
o It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
o Pygame was officially written by Pete Shinners to replace PySDL.
o Pygame is suitable to create client-side applications that can be potentially wrapped in a
standalone executable.
Pygame Installation
Install pygame 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:
1. 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:
o Open the File tab and click on the Settings option.
o 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()
12. Developing a game activity using Pygame like bouncing ball, car race etc.
SIMULATE BOUNCING BALL USING PYGAME
To write a python program to simulate bouncing ball using pygame.
PROGRAM/SOURCE CODE :
import sys, pygame
pygame.init()
size = width, height = 800, 600
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
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()
OUTPUT
RESULT:
Thus the program to simulate bouncing ball using pygameis executed and the output is
obtained.
12. Developing a game activity using Pygame like car race .
PROGRAM/SOURCE 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
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:
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__':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT