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

python programs (1)-GE3181 LAB MANUAL

The document outlines various experiments aimed at developing flowcharts and Python programs for practical applications, such as electricity billing, retail shop billing, sine series calculation, motorbike weight estimation, steel bar weight calculation, and electrical current computation in AC circuits. Each experiment includes an aim, algorithm, pseudocode, and results demonstrating successful execution. Additionally, it covers Python programs for variable manipulation, distance calculation, number series generation, number patterns, pyramid patterns, and library functionality using lists.

Uploaded by

rmshaira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

python programs (1)-GE3181 LAB MANUAL

The document outlines various experiments aimed at developing flowcharts and Python programs for practical applications, such as electricity billing, retail shop billing, sine series calculation, motorbike weight estimation, steel bar weight calculation, and electrical current computation in AC circuits. Each experiment includes an aim, algorithm, pseudocode, and results demonstrating successful execution. Additionally, it covers Python programs for variable manipulation, distance calculation, number series generation, number patterns, pyramid patterns, and library functionality using lists.

Uploaded by

rmshaira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

EX.

NO:1A IDENTIFICATION AND SOLVING OF SIMPLE REAL


LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: AND DEVELOPING FLOW CHARTS FOR THE
ELECTRICITY BILLING

AIM:
To develop a flowchart for electricity billing.

ALGORITHM:

Step1: Start.

Step2: Read the previous unit and current unit.

Step 3: Calculate the used units by subtracting the current unit and previous unit.

Step4: Calculate the Electricity bill from the used units.

Step 5: Print the amount of electricity bill.

Step6: Stop.

PSEUDOCODE:

READ Previous unit, Current Unit

CALCULATE Used Unit = Current Unit – Previous Unit

ElectricityBill = Used Unit x 2

PRINT ElectricityBill
FLOWCHART:

RESULT:

Thus, the flowchart for the electricity billing was developed.


EX. NO:1B.
IDENTIFICATION AND SOLVING OF SIMPLE REAL
DATE: LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
AND DEVELOPING FLOW CHARTS FOR THE
RETAIL SHOP BILLING

AIM:
To develop a flowchart for the retail shop billing.

ALGORITHM:

Step1: Start.
Step2: Read the barcode of the product.
Step3: Display the product name and the amount.
Step 4: Check if more products is available, if available go to Step 2, otherwise go to
Step 5.Step5: Calculate the total cost of the products.
Step6: Print total cost
Step7: Stop.

PSEUDOCODE:

IF more products available THEN


READ bar code
DISPLAY Product name, amount
ELSE
CALCULATE Total
CostPRINT Total Cost
ENDIF
FLOWCHART:

RESULT:
Thus, the flowchart for retail shop billing was developed.
EX. NO:1C. IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
DATE: OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DEVELOPING FLOW CHARTS FOR THE SIN SERIES

AIM:

To develop a flowchart for the Sine Series.

ALGORITHM:

Step1: Start
Step2: Read x and n.
Step3: Print x and n.
Step 4: Convert x values into radian using formula x = x * 3.1412/180.
Step5: Substitute t=x and sum=x.
Step 6: Set the for loop for doing the calculation as initialize i to 1 and check i is less than n+1and
increment i by 1.
Step 7:Calculate t=(t*pow(-1),(2*i- 1))*x*x)/(2*i*(2*i+1).
Step8: Calculate sum = sum + t.
Step9: Print sum.
Step10: Stop

PSEUDOCODE:

READ x, n
PRINT x, n
CONVERT x =x * 3.1412/180 SUBSTITUTE t=x,
sum=x
FOR i=1;i<n+1;i++
t= (t*pow (-1), (2*i- 1))*x*x)/(2*i*(2*i+1).
sum = sum + t
END FOR
PRINT sum
FLOWCHART:

RESULT:

Thus, the flowchart for the sine series was developed.


EX. NO:1D IDENTIFICATION AND SOLVING OF SIMPLE REAL
LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: AND DEVELOPING FLOW CHARTS FOR THE
WEIGHT OF A MOTORBIKE

AIM:
To develop a flowchart for finding the weight of a motor bike.

ALGORITHM:
Step1: Start.
Step2: Read the size of the motor bile in cc.
Step3: Check whether the size of the motor bike is less than or equal to 300 cc, if so, Print
Average weight is 350pounds otherwise go to step 4.
Step4: Check whether the size of the motor bike is less than or equal to 500 cc, if so, Print
Average weight is 410pounds otherwise go to step 5.
Step5: Check whether the size of the motor bike is less than or equal to 900cc, if so, Print
Average weight is 430pounds otherwise go to step 6.
Step6: Check whether the size of the motor bike is equal to 1100 cc, if so, Print Average weight
is 500 pounds otherwise go to step 7.
Step 7: Print Average weight is 600 pounds.
Step 8: Stop.
PSEUDOCODE:
READ size in cc
IF size<=300 THEN
PRINT Average weight = 350 pounds
ELSE IF size <=500 THEN
PRINT Average weight = 410
pounds
ELSE IF size <=900 THEN
PRINT Average weight = 430 pounds
ELSE IF size =1100 THEN
PRINT Average
weight=500pounds
ELSE
PRINT Average weight=600 pounds
END IF
FLOWCHART:

RESULT:

Thus, the flowchart for finding the weight of the motor bike was developed.
EX. NO:1E
IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
DATE: OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DEVELOPING FLOW CHARTS FOR THE WEIGHT OF A
STEEL BAR

AIM:
To develop a flowchart for finding weight of a steel bar.

ALGORITHM:

Step1: Start.
Step2: Read the diameter in mm and length of the steel bar.
Step3: Check whether the length is in meter if so, calculate weight as diameter x diameter x length and
divide it by162, otherwise go to step4.
Step 4: calculate weight as diameter x diameter x length and divide it by 533.
Step5: Print the weight.
Step6: Stop.

PSEUDOCODE:

READ diameter, length


IF length in meter, THEN
Weight=diameter*diameter*length/162
ELSE
Weight=diameter*diameter*length/533
ENDIF
PRINT Weight
FLOWCHART:

RESULT:

Thus, the flowchart for finding the weight of a steel bar was developed.

.
EX. NO:1F
IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE
OR SCIENTIFIC OR TECHNICAL PROBLEMS AND
DATE: DEVELOPING FLOW CHARTS FOR THE COMPUTE
ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT

AIM:

To develop a flowchart to compute electrical current in three phase AC circuit.

ALGORITHM:

Step1: Start.
Step2: Get the value of voltage, resistance, current and power factor.
Step3: Compute the electric current by multiplying voltage, resistance, current and power factor with
3.
Step 4: Print the calculated electric current.
Step5: Stop.

PSEUDOCODE:

READ voltage, resistance, current and power factor


COMPUTE Electric Current = 3 x voltage x resistance x current x power factor
PRINT Electric Current

.
FLOWCHART:

RESULT:

Thus, the flowchart for computing the electric current in three phase AC circuit

was developed.

.
EXP NO:2A
EXCHANGE THE VALUES OF TWO VARIABLES
DATE:

AIM:
To write a python program for exchanging the values of two variables.

ALGORITHM:
STEP1: Start
STEP2: Initialize two variables, a and b, with some values.
STEP3: Print the values of a and b before swapping.
STEP4: Exchange the values of a and b using a temporary variable.
STEP5: Print the values of a and b after swapping.
STEP6: Stop

PROGRAM:

a = int(input("Enter the value of a::"))


b = int(input("Enter the value of b::"))
print("Before swapping:")
print("a =", a)
print("b =", b)
temp = a
a=b
b = temp
print("\nAfter swapping:")
print("a =", a)
print("b =", b)

.
OUTPUT:

RESULT:
Thus a python program for exchanging the values of two variables was written and verified
successfully.
.
EXP NO:2B
CIRCULATE THE VALUES OF N VARIABLES
DATE:

AIM:
To write a python program for circulating the values of n variables.
ALGORITHM:
STEP1: Start
STEP2: Initialize n variables with some values.
STEP3: Print the values of all variables before circulating.
STEP4: Circulate the values of the variables.
STEP5: Print the values of all variables after circulating.
STEP6: Stop

PROGRAM:

a = int(input("Enter the value of a: "))


b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
d = int(input("Enter the value of d: "))
print("Before circulating Swapping:")
print("a={},b={},c={},d={}".format(a,b,c,d))
t=a
a=b
b=c
c=d
d=t
print("\nAfter circulating Swapping:")
print("a={},b={},c={},d={}".format(a,b,c,d))

.
OUTPUT:

RESULT:

Thus a python program for circulating the values of n variables was written and
executed successfully.
.
Exp No:2c
CALCULATE DISTANCE BETWEEN TWO POINTS
Date:

AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
STEP1: Start
STEP2: Define the coordinates of two points.
STEP3: Calculate the distance using the distance formula.
distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
STEP4: Print the calculated distance.
STEP5: Stop

PROGRAM:

#Method 1
#----------
import math
# to get input 2points (x1,y1) & (x2,y2)
x1 = int(input("Enter a number: "))
y1 = int(input("Enter a number: "))
x2 = int(input("Enter a number: "))
y2 = int(input("Enter a number: "))
#process calculate distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
a=x1-x2
b=y1-y2
d=math.sqrt((a**2)+(b**2))
print("distance between 2 points=",d)
.
OUTPUT:

#Method 2
#------------
import math
#process calculate distance=sqrt(((x1 - x2)**2 + (y1 - y2)**2))
p1=[0,0]
p2=[0,0]
# to get input 2points p1(x1,y1) & p2(x2,y2) using List
#-----------------------------------------------------------------
p1[0]=int(input("Enter p1[x1] value:"))
p1[1]=int(input("Enter p1[y1] value:"))
p2[0]=int(input("Enter p2[x2] value:"))
p2[1]=int(input("Enter p2[y2] value:"))
a=p1[0]-p2[0]
b=p1[1]-p2[1]
d = math.sqrt((a**2)+(b**2))
print("distance between 2 points using List=",d)
.
OUTPUT:

RESULT:

Thus, a python program for calculating the distance between two points was written and
executed successfully.

.
EXP NO:3A
NUMBER SERIES
DATE:

AIM:
To write a python program for generating different number series using iterative loops and
conditionals.

ALGORITHM:
STEP1: Start
STEP2: Prompt the user to input the type of number series to generate (e.g., Fibonacci, prime,
square).
STEP3: Depending on the user's choice, generate the corresponding number series using iterative
loops and conditionals.
STEP4: Print the generated number series.
STEP5: Stop

PROGRAM:

print("Number Series Generation")


print("1.Fibannocci Series\n2.Prime Number Generation\n3.Square Number
Generation")
ch=int(input("Enter Ur Choice::"))
if ch==1:
print("Fibannocci Series")
f0=0
f1=1
n=int(input("Enter Length u want to print Fibo series::"))
print("The Series::")
print(f0,"",f1,end=" ")
.
for i in range(1,n-1):
fib=f0+f1
print(fib,end=" ")
f0=f1
f1=fib
elif ch==2:
print("Prime Number Generation")
num = int(input("Enter the number u want to stop Prime Series"))
print("Prime Numbers :")
for j in range(2,num):
prime=0
for i in range(2,j):
if (j % i) == 0:
prime=1
break
if prime==0:
print(j,end=" ")
elif ch==3:
print("Square Number Generation")
n=int(input("Enter Number upto u want to generate Square Number:"))
for i in range(1,n,1):
sq=i*i
print("{}^2={}".format(i,sq))
else:
print("Wrong Input")

.
OUTPUT:

..

.
RESULT:
Thus, the Python program number series has executed successfully and the output has
been verified.

.
EXP NO:3B
NUMBER PATTERNS
DATE:

AIM:
To write a python program for printing a number pattern using iterative loops and conditionals
ALGORITHM:

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.

PROGRAM:

rows = int(input("Enter the number of rows::"))

for i in range(1,rows+1):

for j in range(1,i+1):

print(i, end=" ")

print(" ")

.
Output:

RESULT:

Thus the python program to print numbers patterns was executed and verified successfully.
.
EXP NO:3C
PYRAMID PATTERN
DATE:

AIM:
To write a python program to print pyramid patterns

ALGORITHM:
Step 1 : Start the program.
Step 2 : Read the input values using input()
Step 3 : Perform the following. m = (2 * n) – 2
Step 4 : Decrementing m after each loop Perform the following.
Step 5 : m = m – 1
Step 6 : Print full Triangle pyramid using stars.
Step 7 : Print the value until the for loop ends.
Step 8: Stop the program.

PROGRAM:

n = int(input("Enter the number of rows for pyramid pattern::"))


m = (2 * n)
for i in range(0, n):
for j in range(0, m):
print(end=" ")
m=m-1
for j in range(0, i + 1):
print("*", end=" ")
print("\n")

.
OUTPUT:

RESULT:

Thus, the Python program to print Pyramid Pattern has executed successfully and the output
has been verified.

.
EXP NO:4A
LIBRARY FUNCTIONALITY USING LIST
DATE:

AIM
To write a python program to implement the library functionality using list.

ALGORITHM
Step 1 : Start the program

Step 2 : Initialize the book list

Step 3 : Get option from the user for accessing the library function
3.1. Add the book to list
3.2. Issue a book
3.3. Return the book
3.4. View the list of book
Step 4 : if choice is 1 then get book name and add to book list
Step 5 : if choice is 2 then issue the book and remove from book
list Step 6 : if choice is 3 then return the book and add the
book to list Step 7 : if choice is 4 then the display the book
list
Step 8 : otherwise exit from
menu Step 9 : Stop the
program.

Program:

booklist=["python","tamil","english"]
print("Welcome to library”")
while(1):
ch=int(input(" 1. add the book to list \n 2. issue a book \n 3. return the book
\n 4. view the book list \n 5. Exit \nEnter Ur Choice::"))
.
if(ch==1):
bk=input("enter the book name::")
booklist.append(bk)
print(booklist)
elif(ch==2):
ibk=input("Enter the book to issue::")
booklist.remove(ibk)
print(booklist)
elif(ch==3):
rbk=input("enter the book to return::")
booklist.append(rbk)
print(booklist)
elif(ch==4):
print(booklist)
else:
break

.
OUTPUT

RESULT
Thus the Python program to implement the library functionality using a list has executed
and the results are verified. .
EXP.NO : 4B
DATE: LIBRARY FUNCTIONS USING TUPLES

AIM
To write a python program to implement the library functionality using tuples.

ALGORITHM
Step 1 : Start the program
Step 2 : Create a tuple named as book.
Step 3 : Add a “NW” to a book tuple by using + operator.
Step 4 : Print book.
Step 5 : Slicing operations is applied to book tuple of the range 1:2 and print book.
Step 6 : Print maximum value in the tuple.
Step 7 : Print maximum value in the tuple.
Step 8 : Convert the tuple to a list by using list function.
Step 9 : Delete the tuple.
Step 10 : Stop the program.

PROGRAM

print("List of Library Function in Tuples!!!!!!")


book=("OS","MPMC","DS")
print(book)
book=book+("NW",)
print("after concatenation NW in book is ",book)
print("Slicing[1:2] in book is ", book[1:2])
print("After Slicing in Tuple of Book is ",book)
print("Max of Book is ",max(book))
print("Min of Book is ",min(book))
book1=("OOAD","C++","C")
.
print("The tuple of Book1 is ",book1)
new=list(book)
print("New List of book=",new)
print("Tuple of book1=",book1)
del(book1)
print("Book1 Deleted!!!!!!")
print("Tuple of book1=",book)
del(book)
print("Book Deleted!!!!!!!!!")
del(book)

.
OUTPUT

RESULT
Thus the python program to implement the library functionality using tuple has executed and
the results are verified .
EXP NO:5A IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING SETS, DICTIONARIES.
DATE:
LANGUAGES USING DICTIONARIES

AIM
To write a python program to implement the languages using dictionaries.

ALGORITHM
Step 1 : Start the program
Step 2 : Create a empty dictionary using {}
Step 3 : dict( ) is used to create a dictionary.
Step 4 : To add a value, update() is used in key value pair.
Step 5 : Calculate the total values in the dictionary using len( ) .
Step 6 : Remove the particular key in the dictionary by using pop( )
Step 7 : Print the keys in the dictionary by using key( )
Step 8 : Print the values in the dictionary by using values( )
Step 9 : Print the key value pair in the dictionary using items( )
Step 10 : Clear the the key value pair by using clear( )
Step 11 : Delete the dictionary by using del dictionary

PROGRAM
print("List of Library Function in Set,Dictionary!!!!!!")
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"}#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
.
print(" the length of the languages :",len(Language))
Language.pop(5)
print(" key 5 has been popped with value :",Language)
print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
Language.clear()
print(" The items are cleared in dictionary ",Language)
del Language
print(Language)

.
OUTPUT

Result:
Thus the python program to implement languages using dictionaries has executed
and verified.

.
EXP NO:5B
DATE: COMPONENTS OF AUTOMOBILE USING
DICTIONARIES

AIM
To write a python program to implement automobile using dictionaries.

ALGORITHM
Step 1: Start the program
Step 2: Create a empty dictionary using
{} Step 3: dict() is used to create a
dictionary.
Step 4: Get the value in the dictionary using get()
Step 5: adding [key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using popitem().
Step 7: To check whether key is available in dictionary by using membership operator
in. Step 8: Stop the program.

PROGRAM
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is ",auto_mobile.get(2))
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile)
print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile parts")
.
print(2 in auto_mobile)
OUTPUT

RESULT
Thus the python program to implement automobile
. using dictionaries was executed and verified
successfully.
EX NO: 5C
ELEMENTS OF A CIVIL STRUCTURE
DATE:

AIM
To write a python program to implement elements of a civil structure using dictionaries.

ALGORITHM

Step 1: Start the program


Step 2: Create a empty dictionary using
{} Step 3: Create a dictionary using dict(
).
Step 4: To access the value in the dictionary indexing is applied.
Step 5: adding [key] with value to a dictionary using indexing operation.
Step 6: A copy of original dictionary is used by copy ( ).
Step 7: The length of the dictionary is by len( ).
Step 8: Print the values of the dictionary by using for
loop Step 9: Stop the program

PROGRAM
civil_ele={ }
print("Civil_Ele=",civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print("Civil_Ele=",civil_ele)
new=civil_ele.copy( )
print(" The copy of civil_ele ",new)
print(" The length of Dictionary:: ",len(civil_ele))
print("Dictionary Elements:: ")
for i in civil_ele:
print(civil_ele[i])
.
OUTPUT

RESULT
Thus the python program to implement elements of a civil structure using dictionaries has
executed and verified successfully.

.
EXP NO:6A
FACTORIAL OF A NUMBER USING FUNCTION
Date:

AIM:
To write a python program for calculating the factorial of a given number using a function.

ALGORITHM:
STEP1: Start
STEP2: Define a function factorial(n) that takes an integer n as input.
STEP3: Initialize a variable result to 1.
STEP4: Use a for loop to iterate from 1 to n (inclusive).
STEP5: Multiply result by the current value of i.
STEP6: Return the value of result.
STEP7: Stop

PROGRAM:

def fact(n):
if(n==0):
return 1
else:
return n*fact(n-1)

n=int(input("enter n:"))
o=fact(n)
print("The Factorial of {} is {}".format(n,o))

.
OUTPUT:

RESULT:
Thus the python program to find the factorial of a given number by using function has executed
and the results are verified.
.
EXP NO:6B
LARGEST NUMBER IN A LIST USING FUNCTION
DATE:

AIM:
To write a python program for finding the largest number in a given list using a function.

ALGORITHM:
STEP1: Start
STEP2: Define a function find_largest(lst) that takes a list lst as input.
STEP3: Initialize a variable max_num to the first element of the list.
STEP4: Use a for loop to iterate through each element of the list.
STEP5: If the current element is greater than max_num, update max_num to the current element.
STEP6: Return the value of max_num.
STEP7: Stop

PROGRAM:

#Function Max to find Largest number in List


def max(a,s):
num=a[0]
for i in range(s):
if a[i] > num:
num = a[i]
return num
#main Program
li=[0,0,0,0,0,0,0,0,0,0,0] # List Declaration
s=int(input("Enter how many elements do u need:")) # Size of List
for i in range(s): #To Get Elements in List
li[i]=int(input("enter {} Element::".format(i+1)))
#Output Max find by function max
print("The largest number in the list is:",max(li,s))

OUTPUT:
.
RESULT:

Thus the python program to find the largest number in the list by using function is executed and
the results are verified.
.
EXP. NO : 6C
DATE: AREA OF SHAPES

AIM:
To write a python program for area of shape using functions.

ALGORITHM:

Step 1: Start the program.


Step 2: Read the value of l and b as positive integers in function call rect(l,b).
Step 3: Recursively call function(rect) will be computed as x*y and return the result to the
function call rect(l,b).
Step 4: Print area of the rectangle.
Step 5: Read the value of num as positive integers in function call circle(num).
Step 6: Recursively call the function circle) will be computed as PI*(r*r) and return the
result to the function call circle(num).
Step 7: Print area of the circle.
Step 8: Read the values in function call triangle as a parameters.
Step 9: Recursively call(triangle) will be computed with a,b,c as a parameter and print the
result. Step 10: Read the values as positive integers in function call parallelogram(base,height).
Step 11: Recursively call(parallelogram) will be computed as a*b and return the result to the
function call parallelogram(Base, Height).
Step 12: Print area of
parallelogram.
Step 13: Stop the program.

.
PROGRAM:
import math
#Function to find area of rectangle
def rect(x,y):
return x*y
#Function to find area of circle
def circle(r):
PI = 3.142
return PI * (r*r)
#function to find area of Traingle
def triangle(a, b, c):
Perimeter = a + b + c
s = (a + b + c) / 2
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print("The Perimeter of Triangle = %.2f" %Perimeter)
print("The Semi Perimeter of Triangle = %.2f" %s)
print("The Area of a Triangle is %0.2f" %Area)
#Main Program to Call Various Functions
# Python program to compute area of rectangle
print("1.Rectangle")
l = int(input("Enter the length of rectangle : "))
b = int(input("Enter the breadth of rectangle : "))
a = rect(l,b)
print("Area =",a)
# Python program to find Area of a circle
print("\n2.Circle")
num=float(input("Enter r value of circle:"))
print("Area of Circle is %.6f" % circle(num))
# python program to compute area of triangle
print("\n3.Triangle")
triangle(6, 7, 8)
OUTPUT:

RESULT:
Thus the python program for area of shapes using functions has executed and the
results are verified.
EXP NO:7A
REVERSING A STRING
DATE:

AIM:
To write a python program for reversing a given string.

ALGORITHM:
STEP1: Start
STEP2: Define a function reverse_string(s) that takes a string s as input.
STEP3: Use for to reverse the string.
STEP4: Return the reversed string.
STEP5: Stop

PROGRAM:

#Function for reverse a String


def revstring(s):
rev=""
for i in range(len(s)-1,-1,-1):
rev=rev+s[i]
return rev

# Main Program to call revstring function

str=input("Enter a string to reverse: ")


str1 = revstring(str)
print("Reversed string:", str1)
OUTPUT:

RESULT:

Thus the python program for reversing a .string has executed and the results are verified
EXP NO:7B
PALINDROME OR NOT
DATE:

AIM:
To write a python program for checking if the given string is a palindrome or not.

ALGORITHM:
STEP1: Take the input string from the user.
STEP2: Remove any non-alphanumeric characters from the input string and convert it to lowercase.
STEP3: Compare the cleaned string with its reverse.
STEP4: If the cleaned string is equal to its reverse, print "The string is a palindrome."
STEP5: Otherwise, print "The string is not a palindrome."

PROGRAM:

#Function for reverse a String


def revstring(s):
rev=""
for i in range(len(s)-1,-1,-1):
rev=rev+s[i]
return rev
# Main Program to call revstring function
str=input("Enter a string to reverse: ")
str1 = revstring(str)
print("Reversed string:", str1)

#Check for Palindrome


if str==str1:
print("The Entered String {} is Palindrome".format(str))
else:
print("The Entered String {} is not Palindrome".format(str))
OUTPUT:

RESULT:

Thus the python program for palindrome of a string is executed and the results
are verified
EXP NO : 7C
DATE: CHARACTER COUNT OF A STRING

AIM:
To write a python program for counting the characters of string.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a string.
Step 3: Define and initialize a variable count to 0.
Step 4: Iterate through the string till the end and for each character except spaces, increment
the count by 1.
Step 5: To avoid counting the spaces check the condition i.e. string[i] != ' '.

Step 6: Stop the program.

Program:
#Function for Counting a String
def count(s):
c=0
for i in range(0,len(s),1):
c=c+1
return c

# Main Program to call revstring function

str=input("Enter a string to Count: ")


num = count(str)
print("No.of. charactersin a given string:", num)
OUTPUT:

Result:

Thus the python program for counting the characters of string is executed and the results are
verified.
EXP.NO : 7D
REPLACE OF A STRING
DATE:

AIM:
To write a python program for replacing the characters of a string.

ALGORITHM:

Step 1: Start the program.


Step 2: Define a string.
Step 3: Determine the character 'ch' through which specific character need to be replaced.
Step 4: Use replace function to replace specific character with 'ch' character.
Step 5: Stop the program.

PROGRAM:

str=input("Enter a string to Replace: ")


ch=input("Enter a char to be replace:")
ch2=input("Enter specfic char to be placed:")
s1=str.replace(ch,ch2)
print("String after replacing with given character: ")
print(s1)

OUTPUT:

RESULT:
Thus the python program for replacing the given characters of string has executed and the
results are verified.
EXP.NO : 8A
DATE: CONVERT LIST IN TO A SERIES USING
PANDAS

AIM:
To write a python program for converting list in to a Series.

ALGORITHM:

Step 1: Start the program.


Step 2: import pandas library
Step 3: Create a object as pd for pandas.
Step 4: Define a list
Step 4: Convert the list into series by calling the series function
Step 4: print the result
Step 5: Stop the program.

PROGRAM:

#To use pandas first we have to import pandas


import pandas as pd
#Here pd just a object of pandas
#Defining a List
A=['a','b','c','d','e']
#Converting into a series
df=pd.Series(A)
print(df)

OUTPUT:
0 a
1 b
2 c
3 d
4 e
dtype: object

RESULT:
Thus the python program for converting list in to a series has executed and the results are
verified.
EXP.NO : 8B
DATE: FINDING THE ELEMENTS OF A GIVEN ARRAY IS
ZERO USING NUMPY

AIM:
To write a python program for testing whether none of the elements of a given array is zero.

ALGORITHM:

Step 1 : Start the program.


Step 2 : import numpy library
Step 3 : Create a object as np for numpy library
Step 4 : Define and initialize an array
Step 5 : to test if none of the elements of the said array is zero use all function
Step 6 : print the result
Step 7 : Stop the program.

PROGRAM:

import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))

OUTPUT:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero: True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero: False

RESULT:
Thus the python program for testing whether none of the elements of a given array is zero has
executed and the results are verified.
EXP.NO : 8C
DATE: GENERATE A SIMPLE GRAPH USING MATPLOTLIB

AIM:
To write a python program for generating a simple graph using matplotlib.

ALGORITHM:
Step 1: Start the program.
Step 2: from matplotlib import pyplot libaray
Step 3: Create a object as plt for pyplot
Step 4: Use plot function to plot the given values
Step 5: Plot the result using show function
Step 6: Stop the program.

PROGRAM:

from matplotlib import pyplot as plt


#Plotting to our canvas
plt.plot([1,2,3],[4,5,1])
#Showing what we plotted
plt.show()

OUTPUT:

RESULT:
Thus the python program for generating a simple graph using matplotlib zero has executed
and the results are verified.
EXP.NO : 8D
DATE: SOLVE TRIGONOMETRIC PROBLEMS USING SCIPY

AIM:
To write a python program for finding the exponents and solve trigonometric problems using
scipy.

ALGORITHM:

Step 1: Start the program.


Step 2: from scipy libaray import special function
Step 3: Use exponent,sin,cos functions to perform scientific calculatins
Step 5: Plot the result.
Step 6: Stop the program.

PROGRAM:

from scipy import special


a = special.exp10(3)
print(a)
b = special.exp2(3)
print(b)
c = special.sindg(90)
print(c)
d = special.cosdg(45)
print(d)

OUTPUT:

1000.0
8.0
1.0
0.707106781187

RESULT:
Thus the python program for finding the exponents and solve trigonometric problems using
scipy has executed and the results are verified.
EXP NO:9A
COPYING FROM ONE FILE TO ANOTHER
DATE:

AIM:
To write a python program for copying the contents of one file to another.

ALGORITHM:
STEP1: Open the source file in read mode and the destination file in write mode.
STEP2: Read the content from the source file.
STEP3: Write the read content to the destination file.
STEP4: Close both files after copying is completed.

PROGRAM:

def copy_file(soc, dest):


with open(soc, 'r') as source:
with open(dest, 'w') as destination:
destination.write(source.read())
print("Content copied successfully from", soc, "to", dest)

# Test the function


copy_file("soc.txt", "dest.txt")

INPUT:
Source file:

Destination file
OUTPUT:

Source file:

Destination file

RESULT:

Thus the python program for copying text from one file to another has executed and the results are
verified.
EXP NO:9B
COUNTING THE WORDS IN A FILE
DATE:

AIM:
To write a python program for counting the number of words in a file.

ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Count the number of words in the list of words.
STEP5: Close the file after counting is completed.
STEP6: Stop

PROGRAM:

def word_count(soc):
with open(soc, 'r') as file:
content = file.read()
words = content.split()
return len(words)

# Test the function


word_count_result = word_count("text.txt")
print("Word count:", word_count_result)
INPUT:

OUTPUT:

RESULT:
Thus the Python program for command line arguments is executed
successfully and the output is verified.
EXP NO:9C
FINDING THE LONGEST WORD IN A FILE
DATE:

AIM:
To write a python program for finding the longest word in a file.

ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Iterate over each word in the list of words and find the length of each word. STEP5: Keep
track of the longest word encountered.
STEP6: Close the file after finding the longest word.

PROGRAM:

def longest_word(soc):
with open(soc, 'r') as file:
content = file.read()
words = content.split()
longest = max(words, key=len)
return longest

# Test the function


longest = longest_word("text.txt")
print("Longest word:", longest)
INPUT:

OUTPUT:

RESULT:

Thus the Python program finding the longest words using file handling concepts is executed
successfully and the output is verified
EXP.NO : 10A
DATE: DIVIDE BY ZERO ERROR – EXCEPTION HANDING

AIM:
To write a Python program for finding divide by zero error.

ALGORITHM:

Step1: Start the program


Step2: Take inputs from the user, two numbers.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step6: Stop the program.

PROGRAM:

try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

OUTPUT:
Enter First Number: 12.5
Invalid Input Please Input Integer...
Enter First Number: 12
Enter Second Number: 0
division by zero

Enter First Number: 12


Enter Second Number: 2
6.0

RESULT:
Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
EXP.NO : 10B
DATE: VOTER’S AGE VALIDITY

AIM:
To write a Python program for validating voter’s age.
ALGORITHM:

Step1: Start the program


Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to 18, then display 'You are eligible to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: If the entered data is not integer, throw an exception value error.
Step 6: : If the entered data is not proper, throw an IOError exception
Step 7: If no exception is there, return the result.
Step 8: Stop the program.

PROGRAM:

def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except ValueError:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main( )
OUTPUT:
Enter your age20.3
age must be a valid number

Enter your age 12


Not eligible to vote

Enter your age 35


Eligible to vote

RESULT:
Thus the Python program for validating voter’s age is executed successfully and the output is
verified.
EXP.NO : 10C
STUDENT MARK RANGE VALIDATION
DATE:

AIM:
To write a python program for student mark range validation

ALGORITHM:

Step 1: Start the program


Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program.

PROGRAM:

def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")
main()
OUTPUT:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed

RESULT:
Thus the python program for student mark range validation is executed and verified.
EXP.NO : 11
EXPLORING PYGAME TOOL.
DATE:

Pygame :

Pygame is a set of Python modules designed to make games. It uses SDL


(Simple Direct Media Layer) which is a cross-platform library that abstracts the
multimedia components of a computer as audio and video and allows an easier
development of programs that uses these resources.

Steps for installing pygame package:

1. Open Windows command prompt by typing cmd in startup menu


2. C:\Users\admin>cd..
3. C:\Users>cd..
4. C:\>cd Portable Python 3.2.5.1
5. C:\Portable Python 3.2.5.1> py -m pip install -U pygame –user

RESULT:

Thus the Pygame module successfully installed


EXP.NO : 12A
SIMULATE BOUNCING BALL USING PYGAME
DATE:

AIM:
To write a Python program to simulate bouncing ball in pygame.

ALGORITHM:
Step1: Start

Step2: Import the necessary packages

Step3: Initialize the height, width and speed in which the ball bounce

Step4:Set the screen mode

Step5: Load the ball image

Step6: Move the ball from left to right

Step7: Stop

PROGRAM:
import sys, pygame

pygame.init()

size = width, height = 700, 300

speed = [1, 1]

background = 255, 255, 255

screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("Tree_Short.png")

ballrect = ball.get_rect()

while 1:

for event in pygame.event.get():

if event.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:

speed[0] = -speed[0]

if ballrect.top < 0 or ballrect.bottom > height:

speed[1] = -speed[1]

screen.fill(background)

screen.blit(ball, ballrect)

pygame.display.flip()

Execution Procedure:
1. Copy this url: https://trinket.io/features/pygame to your browser and open pygame
interpreter
2. Remove the source code in main.py and copy the below source code to main.py
3. Click the Run button to execute.

OUTPUT:

RESULT:

Thus the Python program to simulate bouncing ball using pygame is executed successfully
and the output is verified.
EXP.NO : 12B
CAR RACE
DATE:

AIM:
To write a Python program to simulate car race in pygame.

ALGORITHM:
Step1: Start
Step2: Import the necessary packages
Step3: Initialize the height, width and speed in which the ball
bounce Step4:Set the screen mode
Step5: Load the ball image
Step4: Move the ball from left to
right Step5: Stop

PROGRAM:
import pygame pygame.init()
#initializes the Pygame from pygame.locals
import* #import all modules from Pygame screen = pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('RacingBeast')
#changing the logo
logo = pygame.image.load('car game/logo.png')
pygame.display.set_icon(logo) #defining our gameloop function def
gameloop():
#setting background image
bg = pygame.image.load('car game/bg.png') # setting our
player maincar = pygame.image.load('car game\car.png')
maincarX = 100 maincarY = 495
maincarX_change = 0
maincarY_change = 0 #other
cars
car1 = pygame.image.load('car
game\car1.png') car2 =
pygame.image.load('car game\car2.png')
car3 = pygame.image.load('car game\car3.png') run =
True while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT: maincarX_change
+= 5 if event.key == pygame.K_LEFT:
maincarX_change -= 5

if event.key == pygame.K_UP: maincarY_change -= 5


if event.key == pygame.K_DOWN: maincarY_change += 5
#CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN,
BLUE
screen.fill((0,0,0))
#displaying the background image screen.blit(bg,(0,0))
#displaying our main car screen.blit(maincar,(maincarX,maincarY))
#displaing other cars screen.blit(car1,(200,100))
screen.blit(car2,(300,100)) screen.blit(car3,(400,100))
#updating the values maincarX += maincarX_change maincarY +=maincarY_change
pygame.display.update()
gameloop()

Execution Procedure:

1. Copy this url: https://trinket.io/features/pygame to your browser and open


pygame interpreter
2. Remove the source code in main.py and copy the below source code to main.py
3. Click the Run button to execute.

OUTPUT:

RESULT:

Thus the Python program to simulate car race using pygame is executed successfully and
the output is verified.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy