Nothing Special   »   [go: up one dir, main page]

PSP Final For Print

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM – 637303

DEPARTMENT OF ELECTRONICS AND COMMUNICATIONENGINEERING

Regulation R2023

I YEAR/I SEMESTER

23CS104 PROBLEM SOLVING USING PYTHON LABORATORY

PREPARED BY APPROVED BY

Mr V. SAKTHIVEL AP/ECE Dr T C KALAISEVI


Mr D S MYDHEESWARAN AP/ECE HoD/ECE
TABLE OF CONTENTS

Page
Ex. Date Name of the Experiment Marks Sign
No No
Write a algorithm & draw flowchart for simple
1
computational problems
Write a program to perform different arithmetic
2
operations on numbers in python.
Write a python program to implement the various
3
control structures
Write a python program for computational problems
4
using recursive function.

5 Demonstrate use of list for data validation.

Develop a python program to explore string


6
Functions

7 Implement linear search and binary search.

Develop a python program to implement sorting


8
Methods
Develop python programs to perform operations on
9
dictionaries

10 Write a python program to read and write into a file

11 Create a game activity using Pygame like bouncing


ball, car race etc.
EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM

VISION AND MISSION STATEMENTS OF INSTITUTE

VISION

To create competitive human resource in the fields of engineering for the


benefit of society to meet global challenges.

MISSION

 To provide a conducive ambience for better learning and to bring creativity


in the students
 To develop sustainable environment for innovative learning to serve the
needy
 To meet global demands for excellence in technical education
 To train young minds with values, culture, integrity, innovation and
leadership
EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

VISION AND MISSION STATEMENTS

VISION

To impart quality technical education in the field of Electronics and


Communication Engineering in the young minds for serving the Society and
Industry in a globally challenging environment.

MISSION

 To provide sound technical knowledge on Electronics and Communication


Engineering to the students
 To prepare the students for working in global challenges existing in the
industries
 To instill competencies in the students for working in interdisciplinary work
culture
 To create desire for undertaking lifelong learning and entrepreneurship
initiatives
EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO 1. To educate the students for acquiring sound knowledge in the field of
Electronics and Communication Engineering and interdisciplinary field, so as to meet
the needs in the field of Electronics and Communication industries.

PEO 2. To provide knowledge and skills for developing new products in the
field of Electronics and communication.

PEO 3. To offer excellent academic learning environment in department of


Electronics and Communication for facilitating students to become eminent team
players.

PEO 4. To facilitate the students with necessary knowledge in the field of


Electronics and Communication Engineering so as to succeed in competitive
examination for pursuing higher studies.

PEO 5. To expose the students on professional, ethical and social skills to shape them
with leadership quality for analyzing and solvingengineering and social issues.
EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

PROGRAMME OUTCOMES [Pos]

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals and an engineering specialization to the solution of complex
engineering problems.

2. Problem Analysis: Identify, formulate, review research literature, and analyze


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

3. Design / Development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods, including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling of complex
engineering activities with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional
engineering solutions to societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and


responsibilities and norms of the engineering practice.

9. Individual and team work: Function effectively as an individual and as a member or


leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of


the engineering management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.

12. Lifelong learning: Recognize the need for and have the preparation and ability to
engage in independent and lifelong learning in the broadest context of technological
change.
EXCEL ENGINEERING COLLEGE

(Autonomous)

KOMARAPALAYAM

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

PROGRAMME SPECIFIC PROGRAMME OUTCOMES

1. ECE fundamental concepts: To analyze, design and develop solutions by


applying foundational concept of electronics and communication engineering.

2. Design Principles and Best practices: To apply design principles and best practices
fordeveloping quality products for science and business applications.

3. Innovations through ICT: To adapt to emerging information and communication


technologies (ICT) to innovate ideas and solutions to existing/novel problems.
Exp No.1 Write a algorithm & draw flowchart for simple computational problems

1a. find the square root of a number


Aim:
To find the square root of a number (Newton’s method)

Algorithm:
1. Read one input value using input function
2. Convert it into float
3. Find the square root of the given number using the formula input value ** 0.5
4. Print the result
5. Exit.

Flow Chart:

Start

Read an Input value


A

X=float(A)

C=X**0.5

Print the Result

Stop
Program:

number = float(input("enter a number: "))


sqrt = number ** 0.5
print("square root:", sqrt)

Output:
enter a number: 676
square root: 26.0

Using Math Function:


import math
print(math.sqrt(1024))

Output:
32.0

Result

Thus the Flowchart for to find square root of a number is executed successfully
and output is verified.
1b. Compute the GCD of two numbers

Aim:

To compute the GCD of two numbers

Algorithm:

1. Read two input values using input function

2. Convert them into integers

3. Define a function to compute GCD

a. Find smallest among two inputs

b. Set the smallest


c. Divide both inputs by the numbers from 1 to smallest+1
d. If the remainders of both divisions are zero Assign that number to gcd

e. Return the gcd

4. Call the function with two inputs

5. Display the result

Flow Chart:
Finding HCF of a number:

n1 = int(input("Enter the first number: "))


n2 = int(input("Enter the second number: "))

GCD = 1

for i in range(2,n1+1):
if(n1%i==0 and n2%i==0):
GCD = i

print("First Number is: ",n1)

print("Second Number is: ",n2)


print("HCF of the numbers is: ",GCD)

Output:

first Number is: 12


Second Number is: 18
HCF of the numbers is:6

Result:
Thus the flowchart for compute GCD of two numbers is executed successfully and output is verified.
1C Compute to find Odd natural Numbers

Aim:
To compute odd natural numbers

Algorithms:

Step 1: Start
Step 2: Declare x as an integer variable.
Step 3: Set x=0
Step 4: Determine the value of n in integers.
Step 5: While (x<=n), repeat steps 5–7.
Step 6: if (x%2 != 0)
Step 7: then print x
Step 8 : x=x+1
Step 9: Stop

Flowchart:
Programs:

n=int(input("enter a number: "))


i=1
while(i <= n):
print(2 * i-1 )
i=i+1

Output:
Enter a number:10 1
3
5
7
9
11
13
15
17
19

Result:
Thus the flowchart for compute odd natural numbers is executed successfully and output is verified.
1D . To find the sum of any five integers

Aim :
To find the sum of any five integers

Algorithms:

Step 1: Start
Step 2: Read number n
Step 3: Declare sum to 0 and i to 1
Step 4: Repeat steps 5 to 7 until i<=n
Step 5: update sum as sum = sum + i
Step 6: increment i
Step 7: Print sum
Step8: Stop Output: sum

Flowchart:
Programs :

number = int(input("enter a number" ))


sum=0
for i in range(number+1):
sum+=i
print(sum)

Output:

Enter a number: 1055

Viva Questions:

1. What is an algorithm?
2. What is the need for an algorithm?
3. What is the Complexity of Algorithm?
4. What are the building blocks of an algorithm?
5. Classify the three types of statements.

Result:
Thus the flowchart for Sum of n natural numbers is executed successfully and output is verified.
Exp No.2 Write a program to perform different arithmetic operations on numbers in python

Aim:

To write a program to perform different arithmetic operations on numbers in python.

Algorithm:

Step1: Start
Step2: Read the input num1, num2
Step3: calculate the addition, subtraction, multiplication, division from Inputs
Step4: Display the Result
Step6: Stop

Example 1
num1 = float(input(" Please Enter the First Value Number 1: "))
num2 = float(input(" Please Enter the Second Value Number 2: "))

# Add Two Numbers


add = num1 + num2

# Subtracting num2 from num1


sub = num1 - num2

# Multiply num1 with num2


multi = num1 * num2

# Divide num1 by num2


div = num1 / num2

# Modulus of num1 and num2


mod = num1 % num2
# Exponent of num1 and num2
expo = num1 ** num2

print("The Sum of {0} and {1} = {2}".format(num1, num2, add))


print("The Subtraction of {0} from {1} = {2}".format(num2, num1, sub))
print("The Multiplication of {0} and {1} = {2}".format(num1, num2, multi))
print("The Division of {0} and {1} = {2}".format(num1, num2, div))
print("The Modulus of {0} and {1} = {2}".format(num1, num2, mod))
print("The Exponent Value of {0} and {1} = {2}".format(num1, num2, expo))

Output:

Please Enter the First Value Number 1: 10


Please Enter the Second Value Number 2: 30
The Sum of 10.0 and 30.0 = 40.0
The Subtraction of 30.0 from 10.0 = -20.0
The Multiplication of 10.0 and 30.0 = 300.0
The Division of 10.0 and 30.0 = 0.3333333333333333
The Modulus of 10.0 and 30.0 = 10.0
The Exponent Value of 10.0 and 30.0 = 1e+30

Example 2:
num = int (input("enter a number:"))

num = (num * 4)+6


print (“The number is”, num)

Output:
num = 10
The number is 46
Example 3:

num = int(input("enter a number:"))

num = num%3 *5
print(“The number is”, num)

Output:
num = 5
The number is 10

Example 4:

num = int(input("enter a number:"))

num =(num+3*5)-4
print(“The number is”, num)

Output:

num = 15
The number is 24

Viva Questions:
1. What is an Operator in general?

2. What is meant by an Operator in Python?


3. Classify the types of operators in Python.
4. Classify the arithmetic operators.
5. List the Python Comparison Operators.
6. Name the Python logical Operators.
7. Mention the Python Bitwise operators.

Result:
Thus the program to perform different arithmetic operations on numbers is executed
successfully and output is verified.
Exp No.3 Write a python program to implement the various control structures

Aim:
To find a maximum value in a given list using python program

Algorithm:
STEP 1 Start the program
STEP 2 Read the no of terms in the list as n
STEP 3 Read the list values from 1 to n
STEP 4 Initialize max =0
STEP 5 Initialize i=1 repeat step 6 until n
STEP 6 If list[i]> max
STEP 7 Set max = list[i]
STEP 8 Print Maximum numbers as max
STEP 9 Stop the program.

Program:
#input size and elments of an array
n=int(input("Enter no of terms:"))
list1=[]
print("Enter the Numbers\n")
for i in range(n):
list1.append(int(input ()))
#initialize the greatest value
Max =0
#Find the greatest value
for i in range(n):
if list1[i]>Max:
Max=list1[i]
# Print the greatest Number
print("Greatest Number is ", Max)
Output

Result:
Thus the program to find the maximum value in a list is executed successfully and
output is verified
Example 2

Aim :

To Find Odd or Even of a Given numbers

Algorithms:

Step 1: Start
Step 2: Declare a Input a num
Step 3 : if num %2==0
Step 4 : print Even number
Step 5 : Else
Step 6: Print Odd Numbers
Step 7: Stop

Programs:

num = int(input("enter a number:"))


if (num%2==0):
print("Even numbers")
else:
print("Odd numbers")

Output:

Enter a number : 6

Even Number

Viva Questions:

1. What are all the control flow statements in Python?


2. How many important control structures are there in Python?
3. Name the abbreviation of elif.
4. Which statement is generally used as a placeholder?
5. Which is the most comfortable loop?

Result :

Thus the odd or even of given numbers is executed and verified Successfully
Exp No.4 Write a python program for computational problems using recursive function

Example 1

Aim:
To write python program to find Factorial of Number using recursion.

Algorithm:
1. Start the program.
2. Read the number to find the factorial.
3. Get a number for a user for num.
4. Check if the number is negative, positive or zero,ie.:num<0
5. If num is equal to zero print a factorial of 0 is1,
6. now check given number is factorial for i in range(1,num+1)
7. factorial = factorial*i
8. print factorial of num

Program:

# Python program to find the factorial of a number provided by the user.

# To take input from the user


num = int (input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print ("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:

Example 2:

Aim:
To write python program to find sum of natural Number using recursion.

Algorithm:

1. Start a programs
2. Initialize the required variables.
3. Define a recursive function with base case as number ==0.
4. Set the step recursive call as number + recursum( number – 1 ).
5. Call the recursive function recursum() and print the returned value.
6. End of Program
Program:

def recursum(number):
if number == 0:
return number
return number + recursum(number-1)
number = int(input("enter a number :"))

sum= 0
result = recursum(number)
print("The Recursive sum of Natural number is", result)

Output:
Enter a number : 6
The Recursive sum of Natural number is 21

Viva Questions:

1. What is Recursion?
2. List the need of Recursion.
3. Name the Properties of Recursion.
4. How the recursive functions stored in memory?
5. What is the base condition in recursion?

Result:
Thus the program for computational problems using recursive function is executed
successfully and output is verified.
Exp No.5 Demonstrate use of list for data validation

Aim:
To demonstrate use of list for data validation.

Program:
Adding Element to a List

# animals list
animals = ['cat', 'dog', 'rabbit']
# 'guinea pig' is appended to the animals list
animals.append('guinea pig')

# Updated animals list


print('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']

Adding List to a List

# animals list
animals = ['cat', 'dog', 'rabbit']
# list of wild animals
wild_animals = ['tiger', 'fox']
# appending wild_animals list to the animals list
animals.append(wild_animals)
print('Updated animals list: ', animals)
Output

Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]


Count Tuple and List Elements Inside List

# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
# count element ('a', 'b')
count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
# print count
print("The count of [3, 4] is:", count)

Output

The count of ('a', 'b') is: 2


The count of [3, 4] is: 1

Find the index of the element

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Output

The index of e: 1
The index of i: 2

Viva Questions:

1. Define data validation.


2. Classify the types of Validation in Python.
3. List the Challenges in Data Validation.
4. Name the Methods for Data Validation.
5. State Length Check.

Result:
Thus the program for the use of list for data validation is executed successfully and
output is verified.
Exp No.6 Develop a python program to explore string functions to print reverse words of string

Aim:
To develop a python program to explore string functions to print reverse words of string.

Algorithm:
1. Initialize the string.
2. Split the string on space and store the resultant list in a variable called word.
3.Reverse the list words using reversed function.
4. Convert the result to list.

Program:

# Function to reverse words of a string


def rev_sentence(sentence):
# First, split the string into words
words = sentence.split(' ')

# Then, reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))

# Finally, return the joined string


return reverse_sentence

if __name__ == "__main__":
input_str = 'geeks quiz practice code'
print(rev_sentence(input_str))
Output:

Viva Questions:

1. What is a String in Python?


2. How to access characters in Python String.
3. State String Slicing.
4. How to reverse a Python String.
5. Mention the method of creating a String in Python.

Result:
Thus the program for the use of list for data validation is executed successfully and
output is verified.
Exp No.7a Implement linear search and binary search

Aim:

To write a Python Program to perform Linear Search.

Algorithm:

1. Read n elements into the list

2. Read the element to be searched

3. If a list[pos]==item, then print the position of the item

4. Else increment the position and repeat step 3 until pos reaches the length of the list

Program:

lst = []

# Number of elements as input


n = int(input("Enter number of elements: "))

# Iterating to get elements from the user


for i in range(0, n):
ele = int(input("Enter an element: "))
lst.append(ele) # Adding the element to the list

print("List:", lst)

x = int(input("Enter your number: "))

i = flag = 0

while i < len(lst):


if lst[i] == x:
flag = 1
break
i=i+1

if flag == 1:
print(f"The number {x} is found at index {i}.")
else:
print(f"The number {x} is not in the list.")
Output:

Enter number of elements: 7

Enter an element: 21

Enter an element: 34

Enter an element: 57

Enter an element: 98

Enter an element: 34

Enter an element: 56

Enter an element: 79

List: [21, 34, 57, 98, 34, 56, 79]

Enter your number: 21

The number 21 is found at index 0.

Result:

Thus the Python Program to perform linear search is executed successfully and the
output is verified.
Exp No.7b Implement binary search

Aim:

To write a Python Program to perform binary search.

Algorithm:

1. Read the search element

2. Find the middle element in the sorted list

3. Compare the search element with the middle element

i. if both are matching, print element found


ii. else then check if the search element is smaller or larger than the middle element
4. If the search element is smaller than the middle element, then repeat steps 2 and 3 for
the left sublist of the middle element
5. If the search element is larger than the middle element, then repeat steps 2 and 3
for the right sublist of the middle element
6. Repeat the process until the search element if found in the
list
7. If element is not found, loop terminates

Program:
def search(list1, key):
low = 0
high = len(list1) - 1
found = False

while low <= high and not found:


mid = (low + high) // 2
if key == list1[mid]:
found = True
elif key > list1[mid]:
low = mid + 1
else:
high = mid - 1

if found:
print("Key is found.")
else:
print("Key is not found.")

list1 = [23, 1, 4, 2, 3]
list1.sort()
print(list1)
key = int(input("Enter a key element: "))
search(list1, key)

Output:

[1, 2, 3, 4, 23]
Enter a key element: 3
key is found

Viva Questions:

1. Define Linear Search.


2. Mention the complexity in linear Search.
3. State binary search in Python.
4. Classify the two types of binary search.
5. List the advantages of binary search.

Result:
Thus the Python Program to perform binary search is executed successfully and the
output is verified.
Exp No.8 Develop a python program to implement sorting methods

Example 1
Aim:

To write a Python Program to perform selection sort.

Algorithm:

1. Create a function named selection sort

2. Initialise pos=0

3. If alist[location]>alist[pos] then perform the following till i+1,

4. Set pos=location

5. Swap alist[i] and alist[pos]

6. Print the sorted list

Program:

list1=[23,1,4,2,3]

print(list1)

for i in range(len(list1)):

min_val = min(list1[i:])

min_ind = list1.index(min_val)

temp= list1[i]

list1[i]=list1[min_ind]

list1[min_ind]=temp

print(list1)
Output:
[23, 1, 4, 2, 3]
[1, 23, 4, 2, 3]
[1, 2, 4, 23, 3]
[1, 2, 3, 23, 4]
[1, 2, 3, 4, 23]
[1, 2, 3, 4, 23]
[1,2,3,4,23]

Viva Questions:
1. Define sorting in python.
2. How do you sort marks in Python?
3. What is sort () and sorted () in Python?
4. How does Python sort words?
5. Classify the types of sorting.

Result:

Thus the Python Program to perform selection sort is successfully executed and the
output is verified.
Example 2
Aim:

To write a Python Program to perform Insertion sort.

Algorithm:

1. Consider the first element to be sorted and the rest to be unsorted..


2. Take the first element in the unsorted part(u1) and compare it with sorted part elements(s1).
3. If u1 < sl then insert u1 in the correct index , else leave it as it is.
4. Take next element in the unsorted part and compare with sorted elements.
5. Repeats 3 and 4 until all the elements are sorted

Program:

def Insertion(my_list):
for index in range(1, len(my_list)):
current_element = my_list[index]
pos = index

while current_element < my_list[pos - 1] and pos > 0:


my_list[pos] = my_list[pos - 1]
pos = pos - 1

my_list[pos] = current_element

list1 = [2, 4, 3, 5, 1]
Insertion(list1)
print("The Insertion Sorted elements are", list1)

Output:

The Insertion Sorted elements is [1,2,3,4,5]

Result:
Thus the Python Program to perform Insertion sort is successfully executed and theoutput is verified
Exp No.9 Develop python programs to perform operations on dictionaries

Aim:
To develop python programs to perform operations on dictionaries.

Program:

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}

Viva Questions:

1. What is a dictionary in Python?


2. How many types of dictionary are there in Python?
3. What are the 2 ways to create dictionary in Python?
4. What is a Python dictionary key?
5. What are the two elements of a dictionary?

Result:
Thus the program to perform operations on dictionaries is executed successfully and
output is verified.
Exp No.10 Write a python program to read and write into a file

Aim:

To write a Python program to find the most frequent words in a text read from a file.

Algorithm:

1. Read the filename

2. Open the file in read mode

3. Read each line from the file to count the words

4. Write each line from the file to replace the punctuations

5. Close the file

6. Print the words

Program:

# Program to show various ways to read and


# write data in a file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close()
#to change file access modes
file1 = open("myfile.txt","r+")
print ("Output of Read function is ")
print (file1.read())
print
# seek(n) takes the file handle to the nth # bite from the beginning.
file1.seek(0)
print ("Output of Readline function is ")
print (file1.readline())
print
file1.seek(0)
# To show difference between read and readline
print ("Output of Read(9) function is ")
print (file1.read(9))
print
file1.seek(0)
print ("Output of Readline(9) function is ")
print (file1.readline(9))
file1.seek(0)
# readlines function
print ("Output of Readlines function is ")
print (file1.readlines() )
print
file1.close()

Output:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Read line function

is Hello

Output of Read(9) function is

Hello

Th

Output of Readline(9) function is

Hello

Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Viva Questions:

1. How do you read a Python file?


2. Mention the process of writing to a Python file.
3. How to open and read a file?
4. How to create and modify a file?
5. How to close a file?

Result:
Thus the program to perform operations on dictionaries is executed successfully and
output is verified.
Exp No.11 Create a game activity using Pygame like bouncing ball, car race etc.

Aim:

To create a game activity using Pygame.


Algorithm:

1. Import the Pygame library (pip install pygame –pre)


2. Initialize Pygame.
3. Define the width and height of the game window.
4. Set the window's title to "GFG Bouncing game."
5. Create the game window with the specified dimensions.
6. Define color constants, particularly red and black.
7. Create a red ball by drawing a circle on the screen surface and store it in a variable
ball_obj. The circle is positioned at coordinates (100, 100) with a radius of 40 pixels.
8. Define the initial speed of the ball as speed = [1, 1], representing the movement of one
pixel in both the X and Y directions.
9. Enter the game loop:
 Check for events in the event queue using pygame.event.get().
 If a "QUIT" event is detected (e.g., the user closes the window), exit the game loop
and quit the application.
 Fill the screen with black to clear it using screen.fill(black).
 Update the position of the ball by moving it based on the current speed. This
simulates the ball's movement.
 Check if the ball has hit the left or right boundaries of the window (0 or width):
 If yes, reverse the horizontal speed component (speed[0]) to make the ball bounce
off the wall.
 Check if the ball has hit the top or bottom boundaries of the window (0 or height):
 If yes, reverse the vertical speed component (speed[1]) to make the ball bounce off
the ceiling or floor.
 Redraw the ball at its new position on the screen using pygame.draw.circle.
 Update the display to show the changes using pygame.display.flip().
10. End the game loop.
11. Close the Pygame window and release resources.
Program:
import pygame
# initialize pygame
pygame.init()
# define width of screen
width = 1000
# define height of screen
height = 600
screen_res = (width, height)
pygame.display.set_caption("GFG Bouncing game")
screen = pygame.display.set_mode(screen_res)
# define colors
red = (255, 0, 0)
black = (0, 0, 0)
# define ball
ball_obj = pygame.draw.circle(surface=screen, color=red, center=[100, 100], radius=40)
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]
# game loop
while True:
# event loop
for event in pygame.event.get():
# check if a user wants to exit the game or not
if event.type == pygame.QUIT:
exit()
# fill black color on screen
screen.fill(black)
# move the ball
# Let center of the ball is (100,100) and the speed is (1,1)
ball_obj = ball_obj.move(speed)
# Now center of the ball is (101,101)
# In this way our wall will move

# if ball goes out of screen then change direction of movement


if ball_obj.left <= 0 or ball_obj.right >= width:
speed[0] = -speed[0]
if ball_obj.top <= 0 or ball_obj.bottom >= height:
speed[1] = -speed[1]
# draw ball at new centers that are obtained after moving ball_obj
pygame.draw.circle(surface=screen, color=red,center=ball_obj.center, radius=40)
# update screen
pygame.display.flip()
Output:

Viva Questions:
1. What is Pygame?
2. How does Pygame is related to game development in Python?
3. Mention the way of Pygame initialization.
4. What is the game loop?
5. Why game loop is essential in game development with Pygame?

Result:

Thus the program to perform to create a game activit y using Pygames is executed successfully
and output is verified.

You might also like