0% found this document useful (0 votes)
3 views

Ge3171 – Problem Solving and Python Programming Laboratory Manual (2)

The document is a lab manual for the GE3171 Problem Solving and Python Programming Laboratory at A.R.J College of Engineering and Technology for the academic year 2022-2023. It outlines the course objectives, experiments, and expected outcomes, emphasizing the development of programming skills in Python through practical applications. Additionally, it includes the vision and mission statements of the institution and department, along with program educational objectives and outcomes for graduates in Computer Science and Engineering.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Ge3171 – Problem Solving and Python Programming Laboratory Manual (2)

The document is a lab manual for the GE3171 Problem Solving and Python Programming Laboratory at A.R.J College of Engineering and Technology for the academic year 2022-2023. It outlines the course objectives, experiments, and expected outcomes, emphasizing the development of programming skills in Python through practical applications. Additionally, it includes the vision and mission statements of the institution and department, along with program educational objectives and outcomes for graduates in Computer Science and Engineering.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

A.R.

J COLLEGE OF ENGINEERING AND TECHNOLOGY,


MANNARGUDI.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(Regulations 2021)

GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

LAB MANUAL

Academic Year : : 2022 – 2023 (ODD Semester)

Compiled By:

Mr.P.SURESH KUMAR M.E,

AP/CSE,

A.R.J College of Engineering and Technology,

Mannargudi,Thiruvarur Dt,

Tamilnadu.
A.R.J COLLEGE OF ENGINEERING AND TECHNOLOGY,
MANNARGUDI.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INSTITUTE

VISION

Emerging as a technical institution of high standard and excellence to produce quality


Engineers, Researchers, Administrators and Entrepreneurs with ethical and moral values
tocontribute the sustainable development of the society.

MISSION

We facilitate our students

MI1:To have in-depth domain knowledge with analytical and practical skills in cutting
edgetechnologies by imparting quality technical education.

MI2:To be industry ready and multi-skilled personalities to transfer technology to


industries and rural areas by creating interests among students in Research and
Development and Entrepreneurship.

DEPARTMENT:

VISION

 To evolve as a Centre of Excellence to produce the most competent software


professionals, researchers, entrepreneurs and academicians with ethical values in
ComputerScience and Engineering.

MISSION

 Imparting quality education through latest technologies to prepare students as


software developer and system analyst.

 Inculcating the technological transformations for the sustainable development of


society.

 Promoting excellence towards higher education, research, employability and


entrepreneurship.
A.R.J COLLEGE OF ENGINEERING AND TECHNOLOGY,
MANNARGUDI.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

Graduates of Computer Science and Engineering will

PEO-1: Be capable of design by applying the concepts of science, mathematics,


engineering fundamentals and computing for the rapid change of society
requirements.

PEO-2: Demonstrate ethical values, effective communication and team skills in


theirprofession and adapt to current trends through lifelong learning.

PEO-3: Be expert in profession, higher education, research and entrepreneurship.

PROGRAM SPECIFIC OUTCOMES (PSOs)

Graduates of the program will be able to

PSO-1: Understand, analyze and develop computer applications in data Mining/


Analytics, Cloud Computing, Networking, Security, etc. to meet the requirements of
industry and society.

PSO-2: Enrich the ability to design and develop software and qualify for Employment
Higher studies and Research.

PROGRAM OUTCOMES (PO)

Engineering Graduates will be able to:

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 to
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 in 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


responsibilitiesand norms of the engineering practice.

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


member orleader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities


withthe 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


theengineering and 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. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of
technologicalchange.
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY L T P C
0 0 4 2
COURSE OBJECTIVES:
 To understand the problem solving approaches.
 To learn the basic programming constructs in Python.
 To practice various computing strategies for Python-based solutions to real world problems.
 To use Python data structures - lists, tuples, dictionaries.
 To do input/output with files in Python.

EXPERIMENTS:
Note: The examples suggested in each experiment are only indicative. The lab instructor is
expected to design other problems on similar lines. The Examination shall not be restricted
to the sample experiments listed here.

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 a
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.

TOTAL : 60 PERIODS
COURSE OUTCOMES:
On completion of the course, students will be able to:
CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
TEXT BOOKS:

1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition,
O’Reilly Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.

REFERENCES:

1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition,
2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers
and Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python: With
Applications to Computational Modeling and Understanding Data”, Third Edition, MIT Press,
2021.
4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to
Programming”, 2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
EX. NO: 1 SOLVING AND DEVELOPING FLOW CHARTS FOR THE SIMPLE REAL
LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: (EXCHANGE THE VALUES OF TWO VARIABLES)

AIM:
To Draw flow chart for Addition of two numbers, Swapping the values of two variables, Finding
factorial of the number, Biggest of three numbers, Number is ODD or Even etc.,

1.1 ADDITION OF TWO NUMBERS USING FUNCTION

ALGORITHM
Main function
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

FLOWCHART:
1.2. SIN SERIES
FLOWCHART FOR ELECTRICITY BILLING
COMPUTING FACTORIAL OF GIVEN NUMBER
ALGORITHM
Start
Read N
Initializei = 1 and Fact = 1
While i<=N
Fact=Fact* i
i=i+1 //Increase the value of i by 1
ENDWHILE
Display Fact
End

FLOWCHART
BIGGEST OF THREE NUMBERS:

ALGORITHM:

Step 1: Initialise three numbers a, b, c.

Step 2: If a is higher than b and c then, print a.

Step 3: Else if b is greater than c and a then, print b.

Step 4: Else if c is greater than a and b then, print c.

FLOWCHART

PRINT ALL NATURAL NUMBERS UP TO N

ALGORITHM
Step 1: Start
Step 2: Get value of n.
Step 3: initialize i=1
Step 4: While(i<=n)
Print i value
increment i value by 1
Step 5: Stop
FLOWCHART FOR PRINTING ‘N’ NATURAL NUMBER

SWAPPING ALGORITHM:

Step 1 : Start
Step 2 : Read the value of a, b
Step 3 : Swap the values without using a temporary variable.
a=a+b
b=a-b
a=a-b
Step 4 : Print the value of a, b
Step 5 : Stop

FLOWCHART:

RESULT

Thus the Python program for exchanging the values of two variables using simple
statements and expressions was executed successfully.
EX. NO: 2 (A) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (EXCHANGE THE VALUES OF TWO VARIABLES)

AIM:
To write a Python program to exchange the values of two variables

ALGORITHM:
Step 1: Start the program
Step 2: Read two numbers
Step 3: Assign the second variable to the first variable
Step 4: Assign the first variable to the second variable
Step 5: After assigning of values print the two variables
Step 6: Stop the program

PROGRAM:

a=10
b=20
print("Before Swapping the values are")
print(“Value of a”,a)
print(“Value of b”,b)
a,b=b,a
print("After Swapping the values are ")
print(“Value of a”,a)
print(“Value of b”,b)

OUTPUT:
Before Swapping the values are
Value of a 10
Value of b 20
After Swapping the values are
Value of a 20
Value of b 10

RESULT

Thus the Python program for exchanging the values of two variables using simple
statements and expressions was executed successfully.
EX. NO: 2 (B) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (CIRCULATE THE N NUMBER OF VARIABLES)

AIM:

To write a Python program to circulate the n number of variables.

ALGORITHM:

Step 1: Start the Program

Step 2: Read the input values as list

Step 3: Get the length of the list using len Function

Step 4: Circulate the ‘n’ number of variables using for Loop and Print the list values

Step 5: Stop the Program

PROGRAM:

a=list(input("Enter the list"))

b=len(a)

for i in range(b):

print(a[i:]+a[:i])

OUTPUT:

Enter the list 45678


['4', '5', '6', '7', '8']
['5', '6', '7', '8', '4']
['6', '7', '8', '4', '5']
['7', '8', '4', '5', '6']
['8', '4', '5', '6', '7']

RESULT:

Thus the python program to circulate the n number of variables was executed successfully
EX. NO: 2 (C) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (DISTANCE BETWEEN TWO POINTS)

AIM:

To write a python program to find the distance between the two points.

ALGORITHM:

Step 1: Start the program


Step 2: Read the input Variables x1,y1,x2 and y2
Step 3: Calculate the Distance using the formula:
dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
Step 4: Print the Distance as Output
Step 5: Stop the program

PROGRAM :

import math
print("Enter value of x1")
x1=int(input())
print("Enter value of x2")
x2=int(input())
print("Enter value of y1")
y1=int(input())
print("Enter value of y2")
y2=int(input())
dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print("The distance between two points is: ",dist)

OUTPUT:

Enter value of x1 6
Enter value of x2 3
Enter value of y1 9
Enter value of y2 8
Distance between two points is: 3.16

RESULT:

Thus the python program to find distance between the two points are executed successfully.
EX. NO: 3 (A) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (NUMBER SERIES)

AIM:
To write a python program to print the number series.

ALGORITHM:

Step 1: Start the program


Step 2: Get the input and initialize value of i=1
Step 3: Use While loop to iterate the values upto n.
Step 4: Print the values of ‘i’ upto i value less than or equal to the value of n.
Step 5: After printing, Increment i value and iterate the loop.
Step 6: Stop the program

PROGRAM: Print upto ‘n’ natural numbers

print("Enter value of n")


n=int(input())
i=1
while i<=n:
print(i)
i=i+1

OUTPUT:
Enter value of n 5
1
2
3
4
5

RESULT:
Thus the python program to print the number series has been printed successfully.
EX. NO: 3 (B) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (NUMBER PATTERN)

AIM:
To write a python program to print the number pattern.

ALGORITHM:

Step 1: Start the program


Step 2: Read the value of ‘n’ as input
Step 3: Initialize the num value to 1
Step 4: Use the nested for loop for accessing the values for i n range(n):and j in range(i+1).
Step 5: Printing the values in number pattern after the loop is nested
Step 6: Stop the program.

PROGRAM:

n = int(input("ENTER THE INPUT"))


for i in range(n):
num = 1
for j in range(i+1):
print(num, end=" ")
num = num + 1
print("\r")

OUTPUT:

ENTER THE INPUT 5

1
12
123
1234
12345

RESULT:
Thus the python program for printing the number pattern is printed successfully.
EX. NO: 3 (C) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (PYRAMID PATTERN)

AIM:
To write a python program to print the pyramid pattern.

ALGORITHM:
Step 1: Start the program
Step 2: Read the value of ‘n’ as input
Step 3: Use the nested for loop for accessing the values for i in range(n)and j in range(i+1).
Step 5: Printing the * pattern after the loop is nested
Step 6: Stop the program .

PROGRAM:

n = int(input("ENTER THE INPUT"))

for i in range(n):

for j in range(i+1):

print("* ",end="")

print("\r")

OUTPUT:
ENTER THE INPUT 5

*
**
***
****
*****

RESULT:
Thus the program to print pyramid pattern was printed successfully.
EX. NO: 4 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING LIST AND TUPLES
DATE: (ITEMS PRESENT IN A LIBRARY)

AIM: To write a Python program to print the items present in the library

ALGORITHM:
Step 1: Start the program
Step 2: Create a list and enter some values
Step 3: append a new value and another value in the list
Step 4: Pop one element from the list
Step 5: Convert the popped element as a tuple
Step 6: Print the tuple
Step 7: Stop the program

PROGRAM:

# Lists
l = ["War And Peace","Kanavu Kannugal","Turning Point"]
ind=l.index("Turning Point")
print("Element is present",ind)
# Adding Element into list
l.append("Rich And Poor")
l.append("Indian Girl")
print("Adding New Books", l)
# Popping Elements from list
l.pop()
print("Popped one element from list", l)
print()
# Tuple
t = tuple(l)
# Tuples are immutable
print(" Book Tuples are:", t)
print()

OUTPUT:

Element is present 2
Adding New Books
['War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor', 'Indian Girl']
Popped one element from list
['War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor']
Book Tuples are: ('War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor')

RESULT: Thus, Python program for showing Library items using LIST & TUPLES is executed.
EX. NO: 4 (B) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
LIST AND TUPLES
DATE: (COMPONENTS OF A CAR)

AIM To write a Python program to print Components of automobile.

ALGORITHM:

Step 1: Start the program


Step 2: Create a list and enter some values
Step 3: Get length of list and print
Step 4: Extend the list and get the length and print
Step 5: Convert list into tuple
Step 6: Sort the list according to alphabet
Step 7: Print the tuple and Stop

PROGRAM :

l1 = ["Engine","Radiator","Alternator","Brakes"]
c=len(l1)
print (l1)
print("Before Extending",c)
l1.extend(["Steering","Suspension"])
print (l1)
c1 = len(l1)
print ("After Extending",c1)
#converting list to tuple
tu = tuple(l1)
print("Afetr Converting Into Tuple",tu)
sor = sorted(tu)
print ("After Sorting: Components are")
print (sor)
OUTPUT:

['Engine', 'Radiator', 'Alternator', 'Brakes']


Before Extending 4
['Engine', 'Radiator', 'Alternator', 'Brakes', 'Steering', 'Suspension']
After Extending 6
Afetr Converting Into Tuple
('Engine', 'Radiator', 'Alternator', 'Brakes', 'Steering', 'Suspension')
After Sorting: Components are
['Alternator', 'Brakes', 'Engine', 'Radiator', 'Steering', 'Suspension']

RESULT: Thus, the python program for showing Components of automobile using LIST
and TUPLES was executed successfully.
EX. NO: 4 (C) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING LIST AND TUPLES
DATE: (MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING)

AIM:

To write a Python program to print the Materials required for construction of a building

ALGORITHM:

Step 1: Start
Step 2: Create a list and enter some values
Step 3: Print the reversed list using the index number
Step 4: Print the length of the list using built-in len function in python
Step 5: Stop the program

PROGRAM:

Items=["Cement","Sand","Bricks","Tiles","Paint"]
print("The reverse of the list is:",Items[::-1])
del Items[2]
print("The list after deleting an element is:",Items)

OUTPUT:

The reverse of the list is: ['Paint', 'Tiles', 'Bricks', 'Sand', 'Cement']
The list after deleting an element is: ['Cement', 'Sand', 'Tiles', 'Paint']

RESULT:

Thus, the python program for showing Materials required for construction of a building
using SETS was executed successfully.
EX. NO: 5 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE: (COMPONENTS OF AUTOMOBILE USING SETS)

AIM:

To write a Python program to print the Components of an automobile using sets

ALGORITHM:

Step 1: Start
Step 2: Create a set and enter some values
Step 3: Search for a key value in the set
Step 4: If the key value is present in the list, Print true
Step 5: Otherwise Print False
Step 6: Stop the program

PROGRAM:

s = {"Chase", "Engine", "Clutch", "Gearbox", "Brake"}


print("Components of a Car:")
print(s)
key = "Clutch"
x = key in s
print("Key Item Clutch is Present or not: ",x)
key = "Gear"
y = key in s
print("Key Item Gear is Present or not: ",y)

OUTPUT:

Components of a Car:
{'Clutch', 'Brake', 'Chase', 'Engine', 'Gearbox'}
Key Item Clutch is Present or not: True
Key Item Gear is Present or not: False

RESULT:

Thus, the python program for showing Components of automobile using sets was
executed successfully.
EX. NO: 5 (B) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE: (COMPONENTS OF AN AUTOMOBILE USING DICTONARIES)

AIM:

To write a Python program to print the Components of an automobile using Dictionary.

ALGORITHM:

Step 1: Start
Step 2: Create a Dictionary and enter some values
Step 3: Search for a key value in the Dictionary
Step 4: If the key value is present in the Dictionary, Print the value in the dictionary
Step 5: Re-assign the value in the dictionary
Step 6: Print the reassigned value in the dictionary
Step 7: Stop the program

PROGRAM:

dict ={'Gearbox' : "5 Speed",'Brakingsystem' : "ABS", 'Chassis': "10x10 Chassis",'Engine' : "200 CC"}

# retrieving value by using key


x = dict['Gearbox']
print("The retrived value is",x)

# reassigning value
dict['Engine'] = "350 CC"
print("The reassinged value is",dict)

OUTPUT:

The retrived value is 5 Speed


The reassinged value is
{'Gearbox': '5 Speed', 'Braking system': 'ABS', 'Chassis': '10x10 Chassis', 'Engine': '350 CC'}

RESULT:

Thus, the python program for showing Components of an automobile using dictionary
was executed successfully.
EX. NO: 5 (C) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE : (ELEMENTS OF A CIVIL STRUCTURE USING SETS AND DICTIONARIES)

AIM:

To write a Python program to print the Elements of a civil structure using sets

ALGORITHM:

Step 1: Start
Step 2: Create a set and enter some values
Step 3: Create another set and enter some values in it.
Step 4: Print the Union of the two sets
Step 5: Print the intersection of the two sets
Step 6: Stop the program

PROGRAM:

A={"Foundation","Floors","Beams"}
B={"Roofs","Stairs","Foundation"}
print("The Union is:",A|B)
print("The Intersection is:",A&B)

OUTPUT:

The union is: {'Stairs', 'Foundation', 'Floors', 'Beams', 'Roofs'}


The intersection is: {'Foundation'}

RESULT:

Thus, the python program for showing Elements of a civil structure using SETS was
executed successfully.
EX. NO: 6 (A) IMPLEMENTING PROGRAMS USING FUNCTIONS
(FACTORIAL)
DATE:

AIM: To Write a Python program, to implement factorial program using function.

ALGORITHM:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

PROGRAM:
def factorial(n):
if n==0:
return 1
else:
fact=n*factorial(n-1)
return fact
print("Enter a number :")
n=int(input())
print("Factorial of ",n," is ",factorial(n))

OUTPUT:
Enter a number :
5
Factorial of 5 is 120

RESULT:
Thus the given Python program for factorial program using function has been executed
successfully.
EX. NO: 6 (B) IMPLEMENTING PROGRAMS USING FUNCTIONS
(LARGEST NUMBER IN A LIST)
DATE:

AIM:
Write a Python program, to find largest number in a list program using function.

ALGORITHM:

Step 1: Start the program.


Step 2: Define a function along with parameter of the list.
Step 3: Initially assign the first value as the maximum value.
Step 4: Access the list using for loop.
Step 5: If any element is greater than the initial element set is as maximum element.
Step 6: Return the maximum value and print the maximum value.
Step 7: End the program.

PROGRAM:

def maxnum( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print("Largest number in the list :")
print(maxnum([1, 2, -8, 0, 6, 8]))

OUTPUT:

Largest number in the list:


8

RESULT:
Thus the given Python program to find the largest number in a list program
using function has been executed successfully.
EX. NO: 6 (C) IMPLEMENTING PROGRAMS USING FUNCTIONS
DATE: (AREA OF SHAPE)

AIM: Write a Python program, to find area of shape program using function.

ALGORITHM:
Step 1: Define two function as circle and rectangle
Step 2: Get the input of radius for circle function
Step 3: Calculate the Area of Circle and Print the Area of Circle as Output
Step 4: Get the input of Length and Breadth for rectangle function
Step 5: Calculate the Area of Rectangle and Print the Area of Rectangle as Output
Step 6: Stop the program

PROGRAM:
def circle():
print("Finding Area of circle")
print("Enter the radius of circle")
r=int(input())
a=3.14*r*r
print("Area of Circle",a)
def rectangle():
print("Finding area of Rectangle")
l=int(input("Enter the length of rectangle"))
b=int(input("Enter the breath of rectangle"))
a=l*b
print(”Area of Rectangle is”,a)
circle()
rectangle()
OUTPUT:

Finding Area of circle


Enter the radius of circle 2
Area of Circle 12.56
Finding area of Rectangle
Enter the length of rectangle 4
Enter the breath of rectangle 3
Area of Rectagle is 12

RESULT: Thus the given Python program to find the area of shape program using function has been
executed successfully.
EX. NO: 7 (A) IMPLEMENTING PROGRAMS USING STRINGS
(REVERSE THE STRING)
DATE:

AIM:

To write a python program to reverse the string

ALGORITHM:

Step 1: Start the program


Step 2: Define a Function
Step 3: Check the length of the string is equal to zero
Step 4: Else reverse the String
Step 5: Input a String
Step 6: Print the Original String
Step 7: Print the reversed String
Step 8: Stop the program

PROGRAM:
s = input("Enter a String:")
print ("The original string is : ",end="")
print (s)
print ("The reversed string is : ",end="")
print(s[::-1])

OUTPUT:

Enter a String: Python

The original string is: Python

The original string is: nohtyP

RESULT:
Thus the python program for reverse the string using simple statements and expressions
was executed successfully.
EX. NO: 7 (B) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (PALINDROME OR NOT)

AIM:

To write a Python program to Check Palindrome or not .

ALGORITHM:
Step 1: Start
Step 2: Input a String
Step 3: Compare String is equal to reversed string
Step 4: If the answer is yes
Step 5: Print It is a palindrome
Step 6: If the answer is no, Print It is not a Palindrome
Step 7: Stop the program

PROGRAM:

string=input(("Enter a string:"))

if(string==string[::-1]):

print("The string is a palindrome")

else:

print("Not a palindrome")

OUTPUT:

Enter a string: MADAM


The string is a palindrome

RESULT:

Thus the python program for check whether the string is palindrome using simple
statements and expressions was executed successfully.
EX. NO: 7 (C) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (TO FIND THE CHARACTER COUNT)

AIM:
To write a Python program to find the Character Count .

ALGORITHM:
Step 1: Start
Step 2: Input a String
Step 3: Get the char=0
Step 4: Using For loop add character values
Step 5: Print the number of Characters.

PROGRAM:

str=input("Enter String:")

char=0

for i in str:

char=char+1

print("Number of characters in the given string ",char)

OUTPUT:

Enter a String: Python


Number of characters in the given string 6

RESULT:

Thus the python program to find the character count using simple statements and
expressions was executed successfully.
EX. NO: 7 (D) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (REPLACING THE CHARACTERS IN THE STRING)

AIM: To write a Python program to replace the characters in the string .

ALGORITHM:

Step 1: Start the Program

Step 2: Get old_string = Puthon

Step 3: Get the old string in list

Step 4: Change the 1st Character in the string

Step 5: Join the Character in the list

Step 6: Print The new_string and Stop

PROGRAM:

string1 = "Puthon"

list1 = list(string1)

list1[1] = "y"

print("The new List is:",list1)

string1 = "".join(list1)

print("After Joining, The String is ",string1)

OUTPUT:
The new List is: ['P', 'y', 't', 'h', 'o', 'n']
After Joining, The String is Python

RESULT:

Thus the python program to replace the character count using simple statements and
expressions was executed successfully.
EX. NO: 8 (A) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (PANDAS)

AIM:

To write a Python program to use python library function

ALGORITHM:

Step 1: Start the program


Step 2: Import panda library function
Step 3: Create a dataset
Step 4: Enter some values in it
Step 5: Then arrange the data using panda built-in function
Step 6: Then print the element
Step 7: Stop the program

PROGRAM:

import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
print(myvar)

OUTPUT:

Cars Passings
0 BMW 3
1 Volvo 7
2 Ford 2

RESULT:

Thus, the python program for showing Library function (Pandas) was executed
successfully.
EX. NO: 8 (B) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (NUMPY)

AIM:

To write a Python program to use python library function

ALGORITHM:

Step 1: Start the program

Step 2: Import numpy library

Step 3: Create a array using the function numpy

Step 4: Then it will print the array within square brackets

Step 5: Stop the program

PROGRAM:

import numpy

arr = numpy.array([1, 2, 3, 4, 5])

print(arr)

OUTPUT:

[1 2 3 4 5]

RESULT:

Thus, the python program for showing Library function (Numpy) was executed
successfully.
EX. NO: 8 (C) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (MATPLOTLIB)

AIM: To write a Python program to use python library function

ALGORITHM:

Step 1: Start the program


Step 2: Import Matplotlib library
Step 3: Import numpy library
Step 4: Then point x and y points
Step 5: Plot the points using matplotlib function
Step 6: Print the Points in the Graph
Step 7: Stop the program

PROGRAM:

import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
plt.savefig(sys.stdout.buffer)

OUTPUT:

RESULT:
Thus, the python program for showing Liabrary function (Matplotlib) was executed
successfully.
EX. NO: 8 (D) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (SCIPY)

AIM:

To write a Python program to use python library function

ALGORITHM:

Step 1: Start
Step 2: Import Scipy library
Step 3: Import Scientific Constants
Step 4: Then print the constant of pi(𝜋)
Step 5: Stop the program

PROGRAM:

from scipy import constants

print(constants.pi)

OUTPUT:

3.141592653589793

RESULT:
Thus, the python program for showing Liabrary function (Scipy) was executed
successfully.
EX. NO: 9 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
FILE HANDLING
DATE: (COPY FROM ONE FILE TO ANOTHER)

AIM: To write a Python program to Copy one file from another

ALGORITHM:

Step 1: Start the program


Step 2: Open first file and second file
Step 3: Read the contents in the first file
Step 4: Append the contents of the first file to second
Step 5: Stop the program
PROGRAM 1:

f1=open("D:\GK\PYTHON\GK.txt","r")
f2=open("D:\GK\PYTHON\GK1.txt","w")
for line in f1:
f2.write("\n"+line)
f1.close( )
f2.close( )
OUTPUT:
Content of Source file:
I will try my best.
God is always with me!!
Content of Copied file:
I will try my best.
God is always with me!!

PROGRAM 2:
print("Content of Source file:")
f1=open("D:\GK\PYTHON\GK.txt","r")
print(f1.read( ))
print("Content of Copied file:")
f2=open("D:\GK\PYTHON\GK1.txt","r")
print(f2.read( ))

RESULT: Thus, Python program for copy from one file to another was executed successfully.
EX. NO: 9 (B) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING FILE HANDLING
DATE: (WORD COUNT)

AIM:

To write a Python program to find word count.

ALGORITHM:

Step 1: Start the Program


Step 2: Initialize a variable
Step 3: Open the file.
Step 4: Read the file
Step 5: Split into lines and Print the contents
Step 6: Stop the Program

PROGRAM:

n=0

f=open("GK.txt",'r')

for line in f:

words=line.split()

n=n+len(words)

print("Number of words:",n)

OUTPUT:

Number of words: 10

RESULT:

Thus, the python program for counting words in a file was executed successfully.
EX. NO: 9 (C) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING FILE HANDLING
DATE: (LONGEST WORD IN A FILE)

AIM:

To write a Python program to find Longest file.

ALGORITHM:

Step 1: Start
Step 2: Read a file
Step 3: Split the lines.
Step 4: Use len variable to find the length of each word
Step 5: Print the longest word.
Step 6: Stop the program

PROGRAM:

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 is",longest_word('GK.txt'))

OUTPUT:

Longest Word is 'always'

RESULT:
Thus, the python program for counting longest words in a file was executed successfully.
EX. NO: 10 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
EXCEPTION HANDLING.
DATE: (DIVIDE BY ZERO ERROR)

AIM: To write a Python program to handle exceptional cases (Divide by zero)

ALGORITHM:

Step 1: Start the Program


Step 2: Initialize a variable
Step 3: Divide the Variable with zero
Step 4: Print the divided variable
Step 5: Stop the Program

PROGRAM:
try :
a=int(input("Enter value of a: "))
b=int(input("Enter value of b: "))
c=a/b
except ValueError:
print("You have entered wrong data")
except ZeroDivisionError:
print("Divide by Zero Error!!!")
else:
print("The result: ",c)

OUTPUT:
Enter value of a: 5
Enter value of b: 0
Divide by Zero Error!!!

Enter value of a: 6
Enter value of b: 3
The result: 2.0

RESULT: Thus, the python program for handling exceptional cases (Divide by zero) was
executed successfully.
EX. NO: 10 (B) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING EXCEPTION HANDLING.
DATE: (VOTER’S AGE VALIDITY)

AIM: To write a Python program to handle exceptional cases (Voter’s age validity)

ALGORITHM:

Step 1: Start
Step 2: Define a Function
Step 3: Input a Variable
Step 4: Check the variable with if condition
Step 5: If it is true then print Eligible to vote
Step 6: Otherwise print Not eligible to vote
Step 7: If the given value is not an int throw error
Step 8: Stop the program

PROGRAM:
try :
age=int(input("Enter your age:"))
except ValueError:
print("You have entered wrong data")
else:
if age>=18:
print("Eligible to vote")
else:
print("Not eligible to vote")

OUTPUT:

Enter your age: 35


Eligible to vote

Enter your age:9


Not eligible to vote

Enter your age:thirty


You have entered wrong data

RESULT: Thus, the python program for handling exceptional cases (Voter’s age validity) was
executed successfully.
EX. NO: 10 (C) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING EXCEPTION HANDLING.
DATE: (STUDENT MARK RANGE VALIDATION)

AIM:

To write a Python program to handle exceptional cases (Student mark range validation)

ALGORITHM:

Step 1: Start
Step 2: Get the mark inputs
Step 3: Calculate Total and Average of Marks
Step 4: Print the Total and Average
Step 5: If Input mark is not valid Throwback error
Step 6: Stop the program

PROGRAM:
try :
print("Enter Marks Obtained in 5 Subjects: ")
M1 = int(input())
M2 = int(input())
M3 = int(input())
M4 = int(input())
M5 = int(input())
tot = M1+M2+M3+M4+M5
avg = tot/5
except ValueError:
print("You have entered wrong data")
else:
print("Total is",tot)
print("Average is",avg)
if avg>=90 and avg<=100:
print("Your Grade is A")
elif avg>=80 and avg<91:
print("Your Grade is B")
elif avg>=70 and avg<81:
print("Your Grade is C")
elif avg>=60 and avg<71:
print("Your Grade is D")
elif avg>=50 and avg<61:
print("Your Grade is E")
elif avg<50:
print("YOUR ARE FAIL")
OUTPUT:
Enter Marks Obtained in 5 Subjects:
96
52
36
98
89
Total is 371
Average is 74.2
Your Grade is C

Enter Marks Obtained in 5 Subjects:


x
You have entered wrong data

RESULT:

Thus, the python program for handling exceptional cases (Student mark range
validation) was executed successfully.
EX. NO: 11
EXPLORING PYGAME TOOL
DATE:

AIM: To write a Python program to Explore pygame tool

ALGORITHM:

Step 1: Start
Step 2: Install Pygame package
Step 3: Import Pygame package
Step 4: Use Certain functions to create a game
Step 5: Stop the program

PROGRAM:
# -- coding: utf-8 --
import time
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
pygame.display.set_caption('Hello World')
screen.fill([0, 0, 0])
pygame.display.flip()
time.sleep(5)

OUTPUT:

RESULT: Thus, the python program for exploring pygame was executed successfully.
EX. NO: 12
GAME DEVELOPMENT USING PYGAME
DATE: (CAR RACING GAME)

AIM:

To develop a game activity using Pygame like car racing game.

ALGORITHM:

Step 1: Start
Step 2: Install Pygame package
Step 3: Import Pygame package
Step 4: Use Certain functions to create a game
Step 5: Stop the program

PROGRAM:

import random
from time import sleep

import pygame

classCarRacing:
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()

definitialize(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

defcar(self,car_x_coordinate,car_y_coordinate):
self.gameDisplay.blit(self.carImg,(car_x_coordinate, car_y_coordinate))

defracing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width,self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()

defrun_car(self):

whilenotself.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
ifself.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
ifself.car_y_coordinate <self.enemy_car_starty +self.enemy_car_height:
ifself.car_x_coordinate >self.enemy_car_startx andself.car_x_coordinate
<self.enemy_car_startx +self.enemy_car_width orself.car_x_coordinate +self.car_width
>self.enemy_car_startx andself.car_x_coordinate +self.car_width <self.enemy_car_startx
+self.enemy_car_width:
self.crashed =True
self.display_message("Game Over !!!")

ifself.car_x_coordinate <310orself.car_x_coordinate >460:


self.crashed =True
self.display_message("Game Over !!!")

pygame.display.update()
self.clock.tick(60)

defdisplay_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()

defback_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

ifself.bg_y1 >=self.display_height:
self.bg_y1 =-600

ifself.bg_y2 >=self.display_height:
self.bg_y2 =-600
defrun_enemy_car(self,thingx,thingy):
self.gameDisplay.blit(self.enemy_car,(thingx, thingy))

defhighscore(self,count):
font = pygame.font.SysFont("arial",20)
text = font.render("Score : "+str(count),True,self.white)
self.gameDisplay.blit(text,(0,0))

defdisplay_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:

RESULT:

Thus, the development of game activity using Pygame (car race) was executed
successfully.

You might also like