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

python programs

The document contains a series of programming exercises and flowcharts covering various topics such as calculating three-phase current, electricity billing, and weight calculations. It includes Python programs for variable exchange, list manipulation, distance calculation, factorial computation, and area calculation for different shapes. Additionally, it demonstrates the use of data structures like tuples, lists, sets, and dictionaries, along with file handling and basic plotting using matplotlib.

Uploaded by

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

python programs

The document contains a series of programming exercises and flowcharts covering various topics such as calculating three-phase current, electricity billing, and weight calculations. It includes Python programs for variable exchange, list manipulation, distance calculation, factorial computation, and area calculation for different shapes. Additionally, it demonstrates the use of data structures like tuples, lists, sets, and dictionaries, along with file handling and basic plotting using matplotlib.

Uploaded by

iniyavanir.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

1

FLOWCHART: CALCULATE THREE PHASE CURRENT


FLOWCHART: ELECTRICITY BILLING
FLOWCHART: SINE SERIES
FLOWCHART: CALCULATE WEIGHT OF A BIKE
FLOWCHART: RETAIL SHOP BILLING
FLOWCHART: CALCULATE WEIGHT OF A STEEL BAR
:2(a)
PROGRAM:
#exchange the values of two variables
print("enter the value for A:")
A=int(input())
print("enter the value for B:")
B=int(input())
print("before exchanging the values")
print("A=",A,"B=",B)
temp=A
A=B
B=temp
print("after exchanging the values of variables")
print("A",A,"B=",B)
OUTPUT:
Enter the value for A: 10
Enter the value for B:
5
Before exchanging the values A=10 B=5
After exchanging the values of variables A=5 B=10
2(b)
PROGRAM:
no_of_terms = int(input("Enter number of values: "))
list1 = []
for val in range(0, no_of_terms, 1):
element = int(input("Enter integer: "))
list1.append(element)
print("Original list:", list1)
for val in range(0, no_of_terms, 1):
element = list1.pop(0)
list1.append(element)
print("Circulated list:", list1)
OUTPUT:
enter number of values :4 enter integer:10
enter integer:20 enter interger:30 enter interger:40
circulating the elements of list[10,20,30,40,] [20,30,40,10]
[30,40,10,20]
[40,10,20,30]
[10,20,30,40]
2(c)
PROGRAM:
import math
X1 = int(input("Enter the value of x1: "))
Y1 = int(input("Enter the value of y1: "))
X2 = int(input("Enter the value of x2: "))
Y2 = int(input("Enter the value of y2: "))
Distance = math.sqrt((X2 - X1)**2 + (Y2 - Y1)**2)
print("The distance between two points is", Distance)
OUTPUT: Enter the value for x1:2
Enter the value fory1:3
Enter the value for x2:5
Enter the value for y2:6
The distance between the two points is 4.242640687119285
3(a)
PROGRAM:
n = int(input("Enter a number: "))
a = []
for i in range(1, n + 1):
print(i, sep="",end="")
if i <=n:
print("+", sep="", end="")
a.append(i)
print("=", sum(a))
print()
OUTPUT:
Enter a number:6
1+2+3+4+5+6+=21
3(b)
PROGRAM:
nrows = 5
for i in range(nrows, 0, -1):
for j in range(0, i + 1):
print(j, end='')
print("\n")
print(i - 1)
OUTPUT:

012345
01234
0123
012
01
0
3(c)
PROGRAM:
row=int(input("enter number of rows:"))
k=0
for i in range(1,(row+1)):
print("*"*(2*i-1))
print()
OUTPUT:
*
***
*****
*******
*********
4(a):-
Program:-
tuple_library1 = ("deptbooks", "deptjournals", "univquestpqpers")
tuple_library2 = ("competitiveexamsguide", "ebooks", "ejournals")
print("Indexing position of library1:", tuple_library1[1])
print("Number of components in library tuple1:", len(tuple_library1))
print("Number of components in library tuple2:", len(tuple_library2))
print("Concatenation of two library tuples:", tuple_library1 +
tuple_library2)
print("Repetition of tuple_library1:", tuple_library1 * 2)
print("Membership operator of tuple_library1:", "ebooks" in
tuple_library1)
print("Membership operator of tuple_library2:", "ebooks" in
tuple_library2)
print("Slicing of tuple_library2:", tuple_library2[0:2])
Output:-
Indexing position of library1: deptjournals
Number of components in library tuple1: 3
Number of components in library tuple2: 3
Concatenation of two library tuples: ('deptbooks', 'deptjournals',
'univquestpqpers', 'competitiveexamsguide', 'ebooks', 'ejournals')
Repetition of tuple_library1: ('deptbooks', 'deptjournals',
'univquestpqpers', 'deptbooks', 'deptjournals', 'univquestpqpers')
Membership operator of tuple_library1: False
Membership operator of tuple_library2: True
Slicing of tuple_library2: ('competitiveexamsguide', 'ebooks')
4(b):-
Program
tuple_building1 = ("bricks", "sand", "cement")
tuple_building2 = ("tiles", "paint", "wood")
print("Indexing position of building1:", tuple_building1[1])
print("Number of components in building tuple1:",
len(tuple_building1))
print("Number of components in building tuple2:",
len(tuple_building2))
print("Concatenation of two building tuples:", tuple_building1 +
tuple_building2)
print("Repetition of tuple_building1:", tuple_building1 * 2)
print("Membership operator of tuple_building1:", "paint" in
tuple_building1)
print("Membership operator of tuple_building2:", "paint" in
tuple_building2)
print("Slicing of tuple_building1:", tuple_building1[0:2])
Output:-
Number of components in building tuple1: 3
Number of components in building tuple2: 3
Concatenation of two building tuples: ('bricks', 'sand', 'cement', 'tiles',
'paint', 'wood')
Repetition of tuple_building1: ('bricks', 'sand', 'cement', 'bricks', 'sand',
'cement')
Membership operator of tuple_building1: False
Membership operator of tuple_building2: True
Slicing of tuple_building1: ('bricks', 'sand')
4(c):-
Program:-
list_car1 = ["steering", "wheels", "brake", "engine", "seats"]
list_car2 = ["accelerator", "clutch", "gear", "horn", "indicator",
"battery"]
print("Indexing position of 2 in car list1:", list_car1[2])
print("Number of components in car list1:", len(list_car1))
print("Number of components in car list2:", len(list_car2))
print("Concatenation of two car lists:", list_car1 + list_car2)
print("Repetition of car list1:", list_car1 * 2)
print("Membership operator of car list1:", "battery" in list_car1)
print("Membership operator of car list2:", "battery" in list_car2)
print("Slicing of car list1:", list_car1[0:3])
Output:-
Indexing position of 2 in car list1: brake
Number of components in car list1: 5
Number of components in car list2: 6
Concatenation of two car lists: ['steering', 'wheels', 'brake', 'engine',
'seats', 'accelerator', 'clutch', 'gear', 'horn', 'indicator', 'battery']
Repetition of car list1: ['steering', 'wheels', 'brake', 'engine', 'seats',
'steering', 'wheels', 'brake', 'engine', 'seats']
Membership operator of car list1: False
Membership operator of car list2: True
Slicing of car list1: ['steering', 'wheels', 'brake']
5(a):-
Program:-
set1_lang = {"c", "c++", "python", "java"}
set2_lang = {"c", "python", ".net", "c#"}
print("The set1 languages are", set1_lang)
print("The set2 languages are", set2_lang)
print("Union of two sets:", set1_lang.union(set2_lang))
print("Intersection of two sets:", set1_lang.intersection(set2_lang))
print("Difference of two sets:", set1_lang.difference(set2_lang))

Output:-
The set1 languages are {'c++', 'python', 'c', 'java'}
The set2 languages are {'python', 'c', 'c#', '.net'}
Union of two sets: {'c', '.net', 'python', 'c#', 'java', 'c++'}
Intersection of two sets: {'python', 'c'}
Difference of two sets: {'c++', 'java'}
5(b):-
Program:-
automobile1={"transmission":"clutch", "body":"steeringsystem",
"axiliary":"seats"}
print("item in the dictionaries:",automobile1)
automobile1["body2"]="wheels"
print("Add element in the dictionaries:",automobile1)
print("Accessing single element in the
dictionaries:",automobile1["body"])
print("Item in the dictionaries or not:","body" in automobile1)
print("item in the dictionaries or not:","head" in automobile1)

Output:-
item in the dictionaries: {'transmission': 'clutch', 'body':
'steeringsystem', 'axiliary': 'seats'}
Add element in the dictionaries: {'transmission': 'clutch', 'body':
'steeringsystem', 'axiliary': 'seats', 'body2': 'wheels'}
Accessing single element in the dictionaries: steeringsystem
Item in the dictionaries or not: True
item in the dictionaries or not: False
6(a):
Program:-
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while n > 1:
fact *= n
n -= 1
return fact
num = int(input("Enter the number: "))
print("Factorial of", num, "is", factorial(num))

Output:-
Enter the number: 5
Factorial of 5 is 120
6(b)
Program:-
def large(arr):
#root element variable
max=arr[0]
for elem in arr:
if(elem>max):
max=elem
return max
list1=[1,4,5,2,6]
result=large(list1)
print(result)

Output:-
6
6(c)
Program:-
def calculate_area(name):
#converting all characters into lower cases
name=name.lower()
#check for the conditions
if(name=="rectangle"):
l=int(input("enter rectangle's length:"))
b=int(input("enter rectangle's breadth:"))
#calculate area of rectangle
r_area=l*b
print(f"the area of rectangle is {r_area}.")
elif(name=="square"):
s=int(input("enter square’s side length:"))

#calculate area of square


sqt_area=s*s
print(f"the area of square is {sqt_area}.")
elif(name=="triangle"):
h=int(input("enter triangle’s height length:"))
b=int(input("enter triangle breadth length:"))
tri_area=0.5*b*h
print(f"the area of triangle is {tri_area}.")
elif(name=="circle"):
r=int(input("enter circle’s radius length:"))
pi=3.14
circle_area=pi*r*r
print(f"the area of triangle is{circle_area}.")
elif(name=='parallelogram'):
b=int(input("enter parallelogram’s base length:"))
h=int(input("enter parallelogram’s height length:"))
#calculate area of parallelogram
para_area=b*h
print(f"the area of parallelogram is {para_area}.")
else:
print("sorry! this shape is not available")
#drive code
if __name__ == "__main__" :
print("calculate shape area")
shape_name=input("enter the name of shape whose area you want
to find:-")
calculate_area(shape_name)
Output:-
Calculate shape Area
Enter the name of shape whose area you want to find:square
Enter square’s side length:5
The area of square is 25
Calculate shape Area
Enter the name of shape whose area you want to find:rectangle
Enter rectangle’s side length:5
The area of rectangle’s breadth:3
The area of rectangle is 15.
Calculate shape Area
Enter the name of shape whose area you want to find:triangle
Enter triangle’s height length:5
Enter triangle’s breadth length:3
The area of triangle is7.5
Calculate shape Area
Enter the name of shape whose area you want to find:circle
Enter circle’s radius length:3
The area of triangle is 28.2599999999999998.
Calculate shape Area
Enter the name of shape whose area you want to find:parallogram
Sorry! This shape is not available
7
PROGRAM:
def ispalindrome(s):
return s == s[::-1]
Str = input("Enter the string: ")
print("The reverse of the string is", Str[::-1])
check_palin = ispalindrome(Str)
if check_palin:
print(f"The given string ({Str}) is a palindrome")
else:
print(f"The given string ({Str}) is not a palindrome")
print("The length of the given string is", len(Str))
print("Replacing 'm' with 'h' in the string:", Str.replace('m', 'h', 1))
OUTPUT:1
Enter the string:madam
The reverse of the string is madam
The given string (madam)is a palindrome The length of the given string
is 5
Replace a character in the string hadam
8
PROGRAM:
import numpy as np
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[7, -7, 4, 2.0]])
print("Initial array:")
print(arr)
sliced_arr = arr[:2, ::2] # Select first 2 rows and alternate columns (0
and 2)
print("\nArray with first 2 rows and alternate columns (0 and 2):\n",
sliced_arr)
index_arr = arr[[1, 1, 0, 3], [3, 2, 1, 0]] # Selecting elements at specified
indices
print("\nElements at indices (1,3), (1,2), (0,1), (3,0):\n", index_arr)
OUTPUT:
Initial array [[-1. 2. 0. 4.]
[4. 0.5. 6. 0.]
[2.6. 0. 7. 8.]
[3. -7. 4. 2.]]
Array with first 2 rows and alternate columns(0and2) [[-1. 0.]
[4. 6.]]
Elements at indices (1,3),(1,2),(0,1),(3,0):
[0.60, 2,3]
MATPLOTLIB
# Importing matplotlib module
from matplotlib import pyplot as plt
X = [5, 2, 9, 4, 7]
Y = [10, 5, 8, 4, 2]
plt.plot(X, Y)
plt.show()
OUTPUT:
PROGRAM:
# Importing the matplotlib module
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.bar(x, y)
plt.show()
OUTPUT:
9
PROGRAM:
f1 = open("text1.txt", "r")
f2 = open(r"e:\text2.txt", "w")
str = f1.read()
f2.write(str)
print("Content of file1 (f1) is read and it will be written to file2 (f2)")
f1.close()
f2.close()
f3 = open("text1.txt", "r")
words = f3.read().split()
print("The word count in the file (f3) is", len(words))
max_len = len(max(words, key=len))
for word in words:
if len(word) == max_len:
print("The longest word in the file (f3) is", word)
f3.close()
OUTPUT:
Content of file1(f1) is read and it will be write to file2(f2)
The word count in the file(f3) is 6
The longest word in the file (f3) is programming
10(A)
PROGRAM:
n = int(input("Enter the value of dividend (n): "))
d = int(input("Enter the value of divisor (d): "))
c = int(input("Enter the value of another divisor (c): "))
try:
q = n / (d - c) # This is n divided by (d - c)
print("Quotient:", q)
except ZeroDivisionError:
# Handling division by zero error
print("Error: Division by zero!")
OUTPUT:
Enter the value of divident(n):6
Enter the value of divisor(d):3
Enter the value of divisor(c):3
Division by zero
10(B)
PROGRAM:
name = input("Enter the voter name: ")
try:
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except ValueError as err:
# Handling invalid input (non-integer value for age)
print("Error:", err)
else:
print("Thank you, you have successfully checked the voting
eligibility.")
OUTPUT:
Enter the voter name:Karthick
Enter your age:28
Eligibile to vote
Thank you , you have successfully checked the voting eligibility”)
11
PROGRAM:
import pygame
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.rect(screen, (0, 125, 255), pygame.Rect(30, 30, 60, 60))
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()
OUTPUT:
12(A)
PROGRAM:
import os
import sys
import pygame
from pygame.locals import *

# Initialize Pygame
pygame.init()
os.environ['pygame_hide_support_prompt'] = 'hide'.
speed = [1, 1]
color = (255, 250, 250)
width = 500
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame Bouncing Ball")
ball = pygame.image.load("ball.png")
rect_boundry = ball.get_rect()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left < 0 or rect_boundry.right > width:
speed[0] = -speed[0] # Reverse horizontal direction
if rect_boundry.top < 0 or rect_boundry.bottom > height:
speed[1] = -speed[1] # Reverse vertical direction

# Fill the screen with the background color


screen.fill(color)
# Draw the ball on the screen
screen.blit(ball, rect_boundry)
# Update the display
pygame.display.flip()
OUTPUT:
12(B):
PROGRAM:
import random
from time import sleep
import pygame
import sys
class CarRacing:
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()
def initialize(self):
self.crashed = False
self.car_img = 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 settings
self.enemy_car = pygame.image.load('.\\img\\enemy_car1.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 settings
self.bg_img = 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
def car(self, car_x_coordinate, car_y_coordinate):
self.gamedisplay.blit(self.car_img, (car_x_coordinate,
car_y_coordinate))
def racing_window(self):
self.gamedisplay = pygame.display.set_mode((self.display_width,
self.display_height))
pygame.display.set_caption('Car Game')
self.run_game()
def run_game(self):
while not self.crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.crashed = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.car_x_coordinate -= 50
print("Car X coordinate:", self.car_x_coordinate)
if event.key == pygame.K_RIGHT:
self.car_x_coordinate += 50
print("X:{}, Y:{}".format(self.car_x_coordinate,
self.car_y_coordinate))
# Fill the screen with the background color
self.gamedisplay.fill(self.black)
self.back_ground_road()
# Move enemy car and reset if it moves off the screen
self.run_enemy_car(self.enemy_car_startx,
self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed
if self.enemy_car_starty > self.display_height:
self.enemy_car_starty = 0 - self.enemy_car_height
self.enemy_car_startx = random.randrange(310, 450)
# Draw the player's car
self.car(self.car_x_coordinate, self.car_y_coordinate)
self.count += 1
if self.count % 100 == 0:
self.enemy_car_speed += 1
self.bg_speed += 1
# Check for collisions with enemy car
if self.car_y_coordinate < self.enemy_car_starty +
self.enemy_car_height:
if (self.car_x_coordinate > self.enemy_car_startx and
self.car_x_coordinate < self.enemy_car_startx +
self.enemy_car_width or
self.car_x_coordinate + self.car_width >
self.enemy_car_startx and
self.car_x_coordinate + self.car_width <
self.enemy_car_startx + self.enemy_car_width):
self.crashed = True
self.display_message("Game Over!")
# Check if car goes out of bounds
if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:
self.display_message("Game Over!")
pygame.display.update()
self.clock.tick(60)
def display_message(self, msg):
font = pygame.font.SysFont("comicsansms", 72)
text = font.render(msg, True, self.white)
self.gamedisplay.blit(text, (400 - text.get_width() // 2, 240 -
text.get_height() // 2))
pygame.display.update()
sleep(1)
def back_ground_road(self):
self.gamedisplay.blit(self.bg_img, (self.bg_x1, self.bg_y1))
self.gamedisplay.blit(self.bg_img, (self.bg_x2, self.bg_y2))
self.bg_y1 += self.bg_speed
self.bg_y2 += self.bg_speed
if self.bg_y1 >= self.display_height:
self.bg_y1 = -600
if self.bg_y2 >= self.display_height:
self.bg_y2 = -600
def run_enemy_car(self, thingx, thingy):
self.gamedisplay.blit(self.enemy_car, (thingx, thingy))
if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT:

You might also like