Pythonpgm23 230124063755 E98b40d2
Pythonpgm23 230124063755 E98b40d2
Prepared by,
1. NITHIYA.K, AP/CSE
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:
SYLLABUS
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
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.
Procedure:
From Unit To Unit Rate (Rs.) Prices
Flow-Chart:
Result :
Thus the flowchart of electric bill ,sine series was successfully verified
AIM:
Write a python program to exchange the values of two variables
PROCEDURE:
a=10
b=20
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)
OUTPUT:
The swapping of a value is= 20
The swapping of b value is= 10
RESULT:
Thus the swapping of two numbers python program was executed successfully and verified.
EXPT.NO.2b Python Programming Using Simple Statements And Expressions - Circulate The
DATE: Values Of N Variables
AIM:
Write a python program to circulate the values of n variables
PROCEDURE:
list1 = []
list1.append(ele)
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values : 4
Enter integer : 87
Enter integer : 58
Enter integer : 98
Enter integer : 52
Circulating the elements of list [87, 58, 98, 52]
[58, 98, 52, 87]
[98, 52, 87, 58]
[52, 87, 58, 98]
[87, 58, 98, 52]
RESULT:
Thus the python program to circulate the values of n variables was executed successfully and verified
PROCEDURE:
OUTPUT:
enter the value of x1=34
enter the value of x2=56
enter the value of y1=34
enter the value of y2=54
29.732137494637012
RESULT:
Thus the distance between of two points was successfully executed and verified
PROCEDURE:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1,x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.
OUTPUT:
enter the number of terms for the series 5
1
3
7
15
31
RESULT:
Thus the python program to print numbers patterns is executed and verified
AIM:
Write a Python program with conditional and iterative statements for Number Pattern.
PROCEDURE:
Step 1: Start the program
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to i
Step 6: Set j in inner loop using range function and i integer will be initialized to j;
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.
OUTPUT:
RESULT:
Thus the python program to print numbers patterns is executed and verified
Write a Python program with conditional and iterative statements for Pyramid Pattern.
PROCEDURE:
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
print(“*”,end=” “)
print(“\r”)
O/P:
enter the no. of rows 5
*
**
***
****
*****
RESULT:
Thus the python program to print numbers pyramid patterns is executed and verified.
AIM :
To Write a python program to implement items present in a library
PROCEDURE:
STEP 1: Start the program
STEP 2: Create the variable inside that variable assigned the list of elements based on the library
using List and tuple
STEP 3:Using array index to print the items using list and tupel
STEP 4:To print the result using output statement
STEP 5: Stop the program
TUPLE:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ------- Not assigned in tuple # So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)
OUTPUT:
ramayanam
['ramayanam', 'valmiki', 123987, 234]
TUPLE:
(12134, 250000, 'books', 'totalprice')
RESULT:
Thus the Python Program is executed successfully and the output is
Verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.4 b Implementing Real-Time/Technical Applications Using Lists, Tuples -Components
DATE: Of a Car
AIM:
To Write a python program to implement components of a car
PROCEDURE:
STEP 2: Create the variable inside that variable assigned the list of elements based on the car
STEP 3:Using array index to print the items using list and tuple
OUTPUT:
LIST:
TUPLE:
Ferrari
BMW
Jaguar
Jaguar
RESULT:
Thus the Python Program is executed successfully and the output is verified.
AIM:
To Write a python program to implement materials required for construction of building
PROCEDURE:
OUTPUT:
LIST:
['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical']
TUPLE:
('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
list of element is= ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
materials[0]: cementbags
materials[1:3]: ('bricks', 'sand')
RESULT:
Thus the Python Program is executed successfully and the output is verified.
AIM:
To write a python program to implement Components of an automobile using
Sets and Dictionaries
PROCEDURE:
OUTPUT:
Empty Dictionary:
{}
Dictionary after adding 3 elements: {0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
PROCEDURE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number
to compute the factiorial : "))
print(factorial(n))
OUTPUT:
RESULT:
Thus the program was executed and verified successfully
AIM:
To Write a Python program to get the largest number from a list.
PROCEDURE:
OUTPUT:
2
RESULT:
Thus the program was executed and verified successfully
AIM:
To Write a python program to implement area of shape using functions
PROCEDURE:
Step 1:Get the input from the user shape’s name.
Step 2:If it exists in our program then we will proceed to find the entered shape’s area according to
their respective formulas.
Step 3:If that shape doesn’t exist then we will print “Sorry!
Step 4:Stop the program
OUTPUT:
RESULT:
Thus the python program to implement area of shape using functions was successfully
executed and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.7 (A) Implementing programs using Strings –Reverse
DATE
AIM:
PROCEDURE:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearece"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))
OUTPUT:
RESULT:
Thus the reverse of a string function python program was executed and successfully
verified
AIM:
PROCEDURE:
Step 1: start by declaring the isPalindrome() function and passing the string
argument.
Step 2:Then, in the function body,
Step 3:To get the reverse of the input string using a slice operator – string[::-1].
Step 4: -1 is the step parameter that ensures that the slicing will start from the
end of the string with one step back each time.
Step 5:if the reversed string matches the input string, it is a
palindrome Or else, it is not a palindrome.
def is Palindrome(s):
return s == s[::-1]
# Driver code
ans = isPalindrome(s)
if ans:
OUTPUT:
Enter a string:madam
The string is a palindrome
RESULT:
Thus the program of palindrome by using function in python executed successfully and verified
AIM:
PROCEDURE:
Step 1: user to enter the string. Read and store it in a variable.
Step 2: Initialize one counter variable and assign zero as its value.
Step 3: increment this value by 1 if any character is found in the string.
Step 4: Using one loop, iterate through the characters of the string one by one.
Step 5: Check each character if it is a blank character or not. If it is not a blank
character, increment the value of the counter variable by ’1‘.
Step 6: After the iteration is completed, print out the value of the counter.
Step 7: This variable will hold the total number of characters in the string.
OUTPUT:
RESULT:
Thus the program of character count in string in python was executed successfully and verified
AIM:
PROCEDURE:
OUTPUT:
RESULT:
Thus the program was executed and successfully verified
AIM:
To write a python program to implement pandas modules. Pandas are
denote python data structures.
PROCEDURE:
import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],
}
)
print(df)
print(df[“Age”])
ages = pd.Series([22, 35, 58], name="Age”)
print(ages)
df[“Age”].max()
print(ages.max())
print(df.describe())
RESULT:
AIM:
To Write a python program to implement numpy module in python .
Numerical python are mathematical calculations are solved here.
PROCEDURE:
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
OUTPUT:
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
RESULT:
AIM:
To write a python program to implement matplotolib module in python. .Matplotlib
python are used to show the visualization entities in python.
PROCEDURE:
PROGRAM 2:
RESULT:
Thus the python program to implement matplotolib module in python.
Matplotlib python are used to show the visualization entites in python was
successfully executed and verified.
Step 3:To import the package of np in a program and create x,x1,y,y1 identifier
Step 4: SciPy provides interp1d function that can be utilized to produce univariate
interpolation
RESULT:
Thus the python program to implement Scipy module in python.
Scipy python are used to show the visualization entites in python was
successfully executed and verified.
PROCEDURE:
AIM:
PROCEDURE:
Step 1: Open and create the txt file with some statements
step 2: To save that file with the extension of txt file
step3 : Now to count the the lenghth of word in a file.
step 4: To display the word count in a target file
file =open(r"C:\Users\Administrator\Desktop\count2.txt","rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
OUTPUT:
Number of words in text file : 4
RESULT:
Thus the python program to implement word count in File operations in python was
executed successfully and verified
AIM:
def longest_word(count):
with open(count, '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('count.txt'))
OUTPUT:
['welcome', 'program']
RESULT:
Thus the python program to implement longest word in File operations was executed
successfully verified.
AIM:
To Write a exception handling program using python to depict the divide by zero
error.
PROCEDURE:
program
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
OUTPUT:
Entre a=4
Entre b=6
-5.0
RESULT:
Thus the exception handling program using python to depict the divide by zero
error. was successfully executed and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 10 (b)
DATE: Implementing real-time/technical applications using Exception
handling.- Check voters eligibility
AIM:
To Write a exception handling program using python to depict the voters eligibility
PROCEDURE:
Step 1: Start the program
Step 2:Read the input file which contains names and age by using try catch exception handling
method
Step 3:To Check the age of the person. if the age is greater than 18 then write the name into voter
list otherwise write the name into non voter list.
Step 4: Stop the program
def main():
#get the age
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()
OUTPUT:
Enter your age43
Eligible to vote
RESULT:
Thus the exception handling program using python to depict the voters eligibility
was successfully executed and verified.
AIM:
To Implementing real-time/technical applications using Exception handling.- student mark
range validation
PROCEDURE:
Step 1: Start the program
Step 2:By using function to get the input from the user
Step 3:Using Exception handling in that cif statement can be used to check the mark range in the
program
Step 4:Given data is not valid it will throw the IOexception in the process
Step 5: Stop the program
OUTPUT:
Enter your mark 69
Pass and your mark is valid
RESULT:
Thus the real-time/technical applications using Exception handling.- student mark
range validation was successfully executed and verified
AIM:
To Write a python program to implement pygame
PROCEDURE:
step 1: start the program
step 2: when Key presses, mouse movements, and even joystick movements are
some of the ways in which a user can provide input
step 3: To sets up a control variable for the game loop. To exit the loop and the
game, you set running = False. The game loop starts on line 29.
step 4: starts the event handler, walking through every event currently in the event
queue. If there are no events, then the list is empty, and the handler won’t do
anything.
step 5:check if the current event.type is a KEYDOWN event. If it is, then the
program checks which key was pressed by looking at the event.key attribute. If the
key is the Esc key, indicated by K_ESCAPE, then it exits the game loop by setting
running = False.
step 6: do a similar check for the event type called QUIT. This event only occurs
when the user clicks the window close button. The user may also use any other
operating system action to close the window.
step 7:The window won’t disappear until you press the Esc key, or otherwise trigger
a QUIT event by closing the window.
RESULT:
Thus the python program to implement pygame was successfully executed and
verified.
AIM:
To Write a python program to implement bouncing balls using pygame tool
PROCEDURE:
Step1: Start the program
Step 2:The pygame.display.set_mode() function returns the surface object for the window.
This function accepts the width and height of the screen as arguments.
Step 3:To set the caption of the window, call the pygame.display.set_caption() function.
opened the image using the pygame.image.load() method and set the ball rectangle area boundary
using
the get_rect() method.
Step 4:The fill() method is used to fill the surface with a background color.
Step 5:pygame flip() method to make all images visible.
Step 6: Stop the program
RESULT:
Thus the python program to implement bouncing balls using pygame tool was
executed successfully and verified