Ge3171 Lab Manual
Ge3171 Lab Manual
GE3171-Lab Manual
EX NO. 1
ELECTRICITY BILLING
DATE:
AIM:
To write algorithm, pseudocode and to draw the flowchart for calculating the electricity bill.
ALGORITHM:
STEP1: Start the program
STEP2: Read the number of unit consumed
STEP3: if unit <= 100
STEP4: else if unit<=200
Calculate Bill = (100*10) + (unit-100) *15
STEP5: else if unit<=300
Calculate Bill = (100*10) + (unit*15) + (unit-200) *20
STEP6: else
Calculate Bill = (100*10) + (100*15) + (100*20) + (unit-300) *25
STEP7: Print the value of Bill
STEP8: Stop the program
PSEUDOCODE:
BEGIN
READ the number of unit consumed
IF units<=100
COMPUTE Bill=units*10
ELSE IF unit<=200
COMPUTE Bill = (100*10) + (unit-100) *15
ELSE IF unit<=300
COMPUTE Bill= (100*10) + (unit*15) + (unit-200) *20
ELSE
COMPUTE Bill = (100*10) + (100*15) + (100*20) + (unit-300) *25
PRINT the value of Bill
END
FLOWCHART:
RESULT:
The algorithm, pseudocode was been written and flow chart have been drawn for calculating
electricity bill.
AIM:
To implement the python program for swapping the two number with temporary variable and
without using temporary variable.
PROGRAM:
a=int(input(“Enter the value for a:”))
b=int(input(“Enter the value for b:”))
temp=a
a=b
b=temp
print(a,b)
OUTPUT:
Enter the value for a: 80
Enter the value for b: 90
(90,80)
STEP1: Start
STEP2: Read the value of a,b
STEP3: a=a-b
b=a+b
a=b-a
STEP4: print a,b
STEP5: Stop
PROGRAM:
a=int(input(“Enter the value for a:”))
b=int(input(“Enter the value for b:”))
a=a-b
b=a+b
a=b-a
print(a,b)
OUTPUT:
RESULT:
Thus the python program for swapping the two numbers with and without using temporary variable
was implemented and output was verified.
AIM:
To implement Python program for calculating the distance between two points.
ALGORITHM:
STEP 1: Start
STEP 2: Take two points as an input from the user.
STEP 3: Calculate the difference between the corresponding X-coordinates i.e X2-X1 and
Y - coordinates i.e Y2-Y1 of two points.
STEP 4: Apply the formula derived from Pythogorean theorem i.e sqrt((X2-X1)^2+(Y2-Y1)^2).
STEP 5: Print distance.
STEP 6: End
PROGRAM:
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:”))
distance= ((((X2-X1)**2+((Y2-Y1)**2))**0.5)
print(“The distance between the two points is:”,distance)
OUTPUT:
Enter the value of X1:6
Enter the value of X2:5
Enter the value of Y1:9
Enter the value of Y2:2
The distance between the two points is: 7.0710678118654755
RESULT:
Thus the python program for calculating the distance between two points has been implemented
and output was verified.
AIM:
To implement Python program for circulating the values of n variables of a list.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Assign the list of elements in A.
STEP 3: Read the value of number of circulation.
STEP 4: Call function circulate().
STEP 5: Initialize i=1 to n+1.
STEP 6: Concatenate A[i:] and A[:i] and store it in B.
STEP 7: Print the value of B.
STEP 8: Return
STEP 9: Stop the main function
PROGRAM:
def circulate(A,n):
for i in range(1,n+1):
B=A[i:] + A[:i]
Print(“Circulation”,i,“=”,B)
return
A=[1,2,3,4,5,6,7,8,9]
n=int(input("Enter number of times to be circulated: "))
circulate(A,n)
OUTPUT:
Enter number of times to be circulated: 5
Circulation 1 = [2, 3, 4, 5, 6, 7, 8, 9, 1]
Circulation 2 = [3, 4, 5, 6, 7, 8, 9, 1, 2]
Circulation 3 = [4, 5, 6, 7, 8, 9, 1, 2, 3]
Circulation 4 = [5, 6, 7, 8, 9, 1, 2, 3, 4]
Circulation 5 = [6, 7, 8, 9, 1, 2, 3, 4, 5]
RESULT:
Thus the Python program for circulating the values of n variables of a list has been implemented
and the output was verified.
AIM:
To implement Python program for printing the number Series (Fibonacci).
ALGORITHM:
STEP 1: Start
STEP 2: Take an integer variable n1, n2, n3 and num
STEP 3: Set n1=0 and n2=0.
STEP 4: Display n1 and n2.
STEP 5: n3=n1+n2.
STEP 6: Display n3.
STEP 7: Start n1=n2, n2=n3.
STEP 8: Repeat from 5-7, for n times.
STEP 7: Stop
PROGRAM:
num = int(input("Enter the Number:"))
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=",")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
print()
OUTPUT:
Enter the Number: 8
Fibonacci Series: 0 1, 1 2 3 5 8 13
10
RESULT:
Thus the Python program for printing the Fibonacci number series has been implemented and the
output was verified.
11
EX NO. 3. (b)
DATE:
NUMBER PATTERN
AIM:
To implement Python program for printing the number pattern.
ALGORITHM:
STEP 1: Start.
STEP 2: Input the number of rows.
STEP 3: Create the outer loop for number of rows.
STEP 4: Create a nested loop for columns.
STEP 5: Display the numbers.
STEP 6: Stop
PROGRAM:
rows = int(input('Enter the number of rows(-1): '))
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('')
OUTPUT:
Enter the number of rows(-1):5
1
22
333
4444
12
RESULT:
Thus the Python program for printing the number pattern has been implemented and the output was
verified.
13
EX NO. 3. (c)
DATE:
PYRAMID PATTERN
AIM:
To implement Python program for printing the pyramid pattern.
ALGORITHM:
STEP 1: Start
STEP 2: Read the height of the pyramid.
STEP 3: Initialize k=0
STEP 4: Set the first loop to iterate rows.
STEP 5: Create the nested loop.
STEP 6: Repeat the steps until k!=(2*i-1) by incrementing k to 1
STEP 7: Stop
PROGRAM:
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
14
OUTPUT:
Enter number of rows: 5
*
***
*****
*******
*********
RESULT:
Thus the Python program for printing the pyramid pattern has been implemented and the output
was verified.
15
EX NO. 4 (a)
ITEMS PRESENT IN A LIBRARY USING LIST
DATE:
AIM:
To implement the real time or technical applications using Lists.
ALGORITHM:
Step 1: Start
Step 2: Read no_items
Step 3: Create an empty list L
Step 4: Repeat Step 5 until no_items
Step 5: Read items and append into L
Step 6: Print L
Step 7: Repeat Step 8 until True
Step 8: Read choice ch
Step 9: If ch == 1 then
Read element e1 and index ind
Insert el into L at ind
Print L
Step 10: If ch == 2 then
Read element e1
Remove el from L
Print L
Step 11: If ch == 3 then
Read index ind and new element new_e1
Modify L with new_e1 at ind
Print L
Step 12: If ch == 4 then
Read Search element search_e1
If search_e1 in L then
Print Found
else
Print Not Found
16
PROGRAM:
print("Items in a Library")
no_item = int(input("Enter Number of Items: "))
L=[]
for i in range(no_item):
e=input()
L.append(e)
print(L)
print("List of Operations")
print("1.Insert\n2.Remove\n3.Modify\n4.Search\n5.Exit")
while True:
ch=int(input("Enter your choice : "))
if ch==1:
e1=input("Enter an Item to Insert : ")
ind=int(input("Where to insert an item? Give index : "))
L.insert(ind,e1)
print("List of Items after insertion\n",L)
if ch==2:
e1=input("Enter an Item to delete : ")
L.remove(e1)
print("List of Items after deletion\n",L)
if ch==3:
ind=int(input("Enter an item's index to be modify: "))
new_e1=input("Enter an new Item: ")
if(len(L) > ind):
L[ind]=new_e1
print("List of Items after modification\n",L)
else:
OUTPUT:
RESULT:
18
EX NO. 4 (b)
COMPONENTS OF A CAR USING TUPLES.
DATE:
AIM:
To implement the real time or technical applications using Tuples.
ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Create an empty list list1
Step 4: Repeat step5 until n
Step 5: Read items and append into list1
Step 6: Create a tuple1 and assign it to tuple(list1)
Step 7: Repeat step8 until True
Step 8: Read choice ch
Step 9: If ch==1 then
Assign t2 to (“accelerator”, “horn”, “steering”)
Print tuple1 + t2
Step10: If ch==2 then
Print tuple1 * 4
Step11: If ch==3 then
Read object from user
Print tuple1.index(object)
Step 12: If ch==4 then
Read start and end from user
Print tuple1[start: end]
Step13: If ch==5 then
Read element from user
Print tuple1.count(element)
Step14: If ch==6 then
Step15: if ch == 7 then
Print len(tuple1)
Step16: If ch==8 then
Quit
Step17: Stop
PROGRAM:
n = int(input("enter number of items:"))
list1 = []
for i in range(n):
list1.append(items)
tuple1 = tuple(list1)
print("1.concatenation\n2.repetition\n3.indexing\n4.slicing\n5.count\n6.membership\n
7.length\n8.exit")
while True:
if ch == 1:
print(tuple1 + t2)
if ch == 2:
print("Repetition")
print(tuple1 * 4)
if ch == 3:
print(tuple1.index(obj))
20
if ch == 4:
print("slicing operation")
print(tuple1[start:end])
if ch == 5:
print(tuple1.count(element))
if ch == 6:
if ch == 7:
len(tuple1))
if ch == 8:
print("Exit")
quit()
21
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
22
EX NO. 4 (c)
ELEMENTS OF A CIVIL STRUCTURE USING
DATE: TUPLES
AIM:
ALGORITHM:
Step 1: Start
Step 6: Print L
Print L
Read element e1
Remove e1 from L
Print L
Print L
23
Print count_number
Quit()
PROGRAM:
L=[]
for i in range(no_items):
e=input()
L.append(e)
print(L)
print("List of Operations")
print("1.Insert\n2.Remove\n3.Append\n4.Count\n5.Sort\n6.Reverse\n7.Exit")
while True:
24
if ch==1:
L.insert(ind,e1)
if ch==2:
L.remove(e1)
if ch==3:
L.append(new_e1)
if ch==4:
count_number=L.count(count_n)
print(count_number)
if ch==5:
Sort=sorted(L)
if ch==6:
Reverse=list(reversed(L))
print(Reverse)
if ch==7:
print("Exit")
quit()
25
OUTPUT:
26
EX NO. 5 (a)
ELEMENTS OF A CIVIL STRUCTURE
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read n
Step 4: If ch==1
Step 5: If ch==2
Step 6: If ch==3
Step 7: If ch==4
Step 8: If ch==5
Step 9: If ch==6
27
PROGRAM:
elif ch == 7:
print("Popping the last item")
dictionary.popitem()
print("Dictionary: ", dictionary)
elif ch == 8:
print("Clearing the dictionary")
dictionary.clear()
print("Dictionary: ", dictionary)
elif ch == 9:
print("Exit")
quit()
29
OUTPUT:
30
RESULT:
Thus the Python program was written and executed successfully.
31
EX NO. 5(b)
COMPONENTS OF AN AUTOMOBILE
DATE:
AIM:
To implementing real-time/technical application using sets.
ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Create an empty set
Step 4: Repeat step 5 until n
Step 5: Read cars and add them into the set
Step 6: Print L
Step 7: Repeat step 8 until true
Step 8: Read choice ch
Step 9: If ch==1 then
Read e1 and add that element into the set.
Step 10: If ch==2 then
Read e1 and discard that element from the set
Step 11: If ch==3
If e1 in L
Print Found.
Step 12: If ch==4
Print exit
Step 13: Stop
32
PROGRAM:
33
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
34
EX NO. 6 (a)
FACTORIAL OF A NUMBER USING FUNCTION
DATE:
AIM:
ALGORITHM:
Function
recur_factorial(n)
35
PROGRAM:
def
recur_factoria
l(n):if n == 1:
retur
nn
else:
return n*recur_factorial(n-1)
print("FACTORIAL OF A NUMBER")
num = int(input("Enter a number:
"))if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is
1")else:
print("The factorial of",num,"is",recur_factorial(num))
OUTPUT:
Enter a number: 5
The factorial of 5 is 120
RESULT:
Thus the Python program was written and executed successfully.
36
EX NO. 6 (b)
LARGEST NUMBER IN A LIST USING FUNCTION
DATE:
AIM:
To write a program in python to find the largest number in list using function.
ALGORITHM:
Step 1: Start
Step 2: Read the total number of elements in the list.
Step 3: Read the elements of the list
Step 4: Call the function max_num_in list with list as the input argument
Step 5: Print the largest element in the list.
Step 6: Stop
Function max_num_in_list:
Step 1: Start the function
Step 2: Assign max=list[0] first element of the list
Step 3: For each element in list compare it with max, replace max with the largest value.
Step 4: Return the value of max
Step 5: Stop the function
PROGRAM:
list1=[]
37
OUTPUT:
LARGEST NUMBER IN THE LIST
Enter number of elements in the list: 5
Enter elements: 25
Enter elements: 1
Enter elements: 99
Enter elements: 56
Enter elements: 33
The largest number in the list is 99
RESULT:
Thus the Python program was written and executed successfully.
38
EX NO. 6 (c)
AREA OF SHAPE USING FUNCTION
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read the shape for which area is to be calculated.
Step 3: Call the function calculate_area, with shape name has input argument
Step 4: Stop
Function calculate_area:
Step 1: Start
Step 2: If shape is rectangle read the value of length, breath. Calculate and print the area.
Step 3: If shape is square read the value of side length. Calculate and print the area.
Step 4: If shape is triangle read the value of height breath. Calculate and print the
area.
Step 5: If shape is circle read the value of radius then calculate and print area
Step 6: If shape is parallelogram read the value of length,height then calculate and print the area.
Step 7: Else print shape is not available
Step 8: Stop the function
39
PROGRAM:
def rectangle(l,b):
R=l*b
return R
def square(s):
sq=s*s
return sq
def triangle(b,h):
tri=0.5*b*h
return tri
def circle(r):
pi=3.14
c=pi*r*r
return c
def parallelogram(b,h):
para=b*h
return para
def shape(name):
name=name.lower()
if name =="rectangle":
l=int(input("enter the length value"))
b=int(input("enter the base value"))
R=rectangle(l,b)
print(R)
elif name=="squre":
s=int(input("enter the side value"))
sq=squre(s)
print(sq)
elif name=="triangle":
b=int(input("enter the base value"))
h=int(input("enter the hight value"))
tri=triangle(b,h)
print(tri)
elif name=="circle":
40
OUTPUT:
enter the shape name: rectangle
enter the length value5
enter the base value6
30
enter the shape name: square
enter the side value2
4
enter the shape name: triangle
enter the base value2
enter the hight value4
4
enter the shape name: circle
enter the base value3
28.26
Enter the shape name: parallelogram
enter the base value5
enter the hight value2
10
RESULT:
Thus the Python program was written and executed successfully.
41
EX NO. 7(a)
STRING REVERSE
DATE:
AIM:
To write a program in python for reversing the given string.
ALGORITHM:
STEP 1: Start the program
STEP 2:Get the str
STEP 3: Call the function check_palindrome
STEP 4: if true print It is palindrome
STEP 5: else print It is not palindrome
STEP 6: Stop the program.
FUNCTION check_palindrome:
STEP 1: Start the function
STEP 2: Assign rev_str = reverse of the string
STEP 3: if rev_str is equal to str do
Return True
Else
Return False
STEP 4: Stop the function
PROGRAM:
def check_palindrome(str):
rev_str=str[::-1]
if rev_str==str:
return True
else:
return False
string = input("Enter the string : ")
str = check_palindrome(string)
42
if str:
print("it is palindrome")
else:
print("it is not palindrome")
OUTPUT:
Enter the string: Tenet
It is not palindrome
Enter the string: tenet
It is palindrome
RESULT:
Thus the Python program was written and executed successfully.
43
EX NO. 7(b)
STRING PALINDROME
DATE:
AIM:
To write a program in python to check whether the given number is palindrome or not.
ALGORITHM:
STEP 1: Start the program
STEP 2:Get the string
STEP 3: Call the function check_palindrome
STEP 4: if status == 0 print It is palindrome
STEP 5: else print It is not palindrome
STEP 6: Stop the program.
FUNCTION check_palindrome:
STEP 1: Start the function
STEP 2: Assign length = length of the string, first = 0 , last = length – 1, status = 1
STEP 3: while first<last do
If string[first] is equal to string[last] do
First = first + 1
Last = last - 1
Else
status=0
break the loop
return status
STEP 4: Stop the function
44
PROGRAM:
def check_palindrome(string):
length=len(string)
first=0
last=length-1
status=1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status=0
break
return int(status)
string=input ("Enter the string: ")
status=check_palindrome (string)
if status:
print ("It is palindrome")
else:
print ("It is not palindrome")
OUTPUT:
Enter the string: Tenet
It is not palindrome
Enter the string: tenet
It is palindrome
RESULT:
This is a python program to check whether the given number is palindrome or not has been
executed successfully and output got verified.
45
EX NO. 7(c)
CHARACTER COUNT
DATE:
Aim:
To write a program in python for finding the count of a character in the given string
Algorithm:
Step 4: For each character in the string, if it is equal to the read character increment sum by 1.
Program:
print("CHARACTER COUNT\n")
text = input()
char = input()
textLen = len(text)
sum = 0
for i in range(textLen):
if char==text[i]:
sum = sum+1
print(sum)
46
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
47
AIM:
To implement a python program using written modules and python standard libraries.
ALGORITHM:
Step 1: Start the program
Step 2: Import pandas, matplotlib
Step 3: Read excel file that contains employee details
Step 4: Plot histogram using hist() for the Age field.
Step 5: Display the plot
Step 6: Stop
PROGRAM:
import pandas as pd
df=pd.read_excel("D:/emp.xlsx", "Sheet1")
fig=plt.figure()
ax = fig.add_subplot(1,1,1)
ax.hist(df['AGE'],bins = 5)
plt.title('Age distribution')
plt.xlabel('Age')
plt.ylabel('Employee')
plt.show()
“emp.xlsx”
48
E007 F 45 121
E008 M 23 122
E009 M 34 134
E010 M 12 176
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
49
EX NO. 8 (b)
DATE: IMPLEMENTING PROGRAM USING PANDAS
AIM:
ALGORITHM:
Step 1: Start the program
Step 2: Import numpy library
Step 3: Create alias for numpy
Step 4: Create an array of list
Step 5: Print the array
Step 6: Print the shape of array
Step 7: Stop the program
PROGRAM:
importnumpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array
b = a[1:, 2:]
print(b)
OUTPUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]
RESULT:
Thus the program was written and executed successfully.
50
EX NO. 8(c)
DATE: IMPLEMENTING PROGRAM USING MATPLOTLIB
AIM:
ALGORITHM:
Step 1: Install Matplotlib
Step 2: Import pyplot and create alias for it.
Step 3: Define the x-axis and corresponding y-axis values as lists.
Step 4: Plot and name them using plt.xlabel () and plt.ylabel () functions
Step 5: Give a title to your plot using .title () function.
Step 6: Finally to view your plot using show () function.
PROGRAM:
from matplotlib import pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='r',width=.1)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Audi", color='b',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()
51
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
52
EX NO. 9(a)
COMMAND LINE ARGUMENTS (WORD COUNT)
DATE:
AIM:
To write a python program that take command line arguments (word count).
ALGORITHM:
Step 1: Open Python IDLE, open a new editor window
Step 2: Write a comment line to describe about the program
Step 3: Import the module sys
Step 4: Check the length of the command line argument. If it is less than 2, give a message that the
user has to enter a file name and exit the program.
Step 5: Else, take the second argument as file name and open the file.
Step 6: Read the lines one by one and split the line based on spaces between words.
Step 7: Count the number of words and print the result.
Step 8: Save the file (ctrl+s) with .py extension and Run the module through command
prompt, by executing the command “python filename.py sample.txt.”
PROGRAM:
import sys
iflen(sys.argv)<2:
print("You must enter the file name to count the number of words")
exit
else:
fname=sys.argv[1]
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
53
OUTPUT:
python countwords.py sample.txt
Number of words:
49
RESULT:
Thus the python program to find the word count using command line arguments was written and
executed successfully.
54
EX NO. 9(b)
COPY FROM ONE FILE TO ANOTHER FILE
DATE:
AIM:
To write a python program to copy from one file to another.
ALGORITHM:
Step 1: Open Python IDLE, open a new editor window.
Step 2: Import the module sys
Step 3: Open one file called test.txt in read mode.
Step 4: Open another file out.txt in write mode.
Step 5: Read each line from the input file and write it into the output file.
Step 6: Save the file (ctrl+s) with .py extension and Run the module through command prompt, by
executing the command “python filename.py sample.txt.”
PROGRAM:
import sys
file_name = open(sys.argv[2],"w")
with open(sys.argv[1]) as filename:
for line in filename:
file_name.write(line.lower)
print("Files Copied")
OUTPUT:
(Run as C:\Python34>Python Try.py test.txt out.txt)
Files Copied
C:\Python34>
RESULT:
Thus the python program to copy from one file to another file was written and executed
successfully.
55
56
EX NO. 10 (a)
DIVIDE BY ZERO
DATE:
AIM:
To implement the real-time/technical applications using Exception handling.
ALGORITHM:
Step 1: Start the program
Step 2: Start a try block, get the dividend and divisor as input.
Step 3: Calculate the result.
Step 4: Create a except block to handle ZeroDivisionError if divisor is zero.
Step 5: Display the result.
PROGRAM:
try:
Dividend = int(input("Enter the dividend"))
Divisor = int(input("Enter the divisor"))
Result=Dividend/Divisor
print("Answer :",Result)
except ZeroDivisionError:
print("Divisor is zero")
OUTPUT:
RESULT:
Thus to implement the real-time/technical applications using Exception handling was written and
executed successfully.
57
EX NO. 10(b)
MARK RANGE VALIDATION
DATE:
AIM:
ALGORITHM:
PROGRAM:
try:
mark=int(input("Enter your mark"))
if mark < 0 or mark > 100 :
raise ValueError("Enter a Valid Mark")
except ValueError as err:
print(err)
else:
print("Input Mark is Valid ")
OUTPUT:
RESULT:
Thus to implement the real-time/technical applications using Exception handling was written and
executed successfully.
58
EX NO. 11
EXPLORING PYGAME TOOL
DATE:
What is Pygame?
Something that can be tricky for new developers to understand is that programming languages
seldom exist in a vacuum. When making an Android app for example, you will not only have to
use Java or Kotlin (the two primary programming languages supported by Google) but also
the Android SDK. This is the “software development kit” and it contains a host of different
libraries, classes, and tools that make Java code work on Android and give it access to the features
that are exclusive to mobile platforms.
Syntax and Parameters of Python Pygame
import
pygame
from pygame.locals
import *
PyGame Concepts:
Pygame and the SDL library are portable across different platforms and devices, they
both need to define and work with abstractions for various hardware realities. Understanding
those concepts and abstractions will help you design and develop your own games.
Initialization and Modules
Displays and Surfaces
Images and Rects
Attributes
There are a few attributes in case of Pygame window that we can update. Let’s dive a little into
so that we know about all the options that we have.
Update the title
Updating the icon
Updating the background color
59
Eg : pygame.Rect attribute
myRect.height Integer value of the height of the rectangle
myRect.size A tuple of two integers: (width, height)
myRect.topleft A tuple of two integers: (left, top)
myRect.topright A tuple of two integers: (right, top)
60
61
At the top, you’ll see Scripts written; right click on Scripts and
select Copy address as text.
Go to the Start menu again and open Command Prompt by typing cmd.
62
Now type cd followed by space and then paste the copied address / location.
63
Now type pip install pygame like you see on the screen.
64
Wait for the successful installation message and your PyGame installation is done.
You can test if PyGame has been installed on your Windows OS by typing import
pygame in your IDLE.
65
66
EX NO. 12
DEVELOPING A GAME ACTIVITY USING PYGAME
DATE:
AIM:
To write a python program to simulate bouncing ball using pygame.
ALGORITHM:
Step 1: Import the necessary files for the implementation of this Pygame.
Step 2: Set the display mode for the screen
usingwindowSurface=pygame.display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bounce pygame.display.set_caption(“Bounce”)
Step 4: Develop the balls with necessary colors. BLACK=(0,0,0) WHITE=(255,255,255)
RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255)
Step 5: Set the display information info=pygame.display.Info()
Step 6: Set the initial direction as down.
Step 7: Change the direction from down to up.
Step 8: Then again change the direction from up to down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.
67
PROGRAM:
import sys, pygame
pygame.init()size =
width, height = 800,
400 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.Q
UIT:
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()
68
OUTPUT:
RESULT:
Thus the Python program was written and executed successfully.
69