You are on page 1of 23

IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 1a
ARMSTRONG NUMBER
Date :
AIM:

To write a python program to check if the number provided by the user is an Armstrong
number or not.

ALGORITHM:

1. Read a number
2. Initialize sum=0 and Times=0
3. Calculate number of individual digits
4. Divide the given number into individual digits using mod operator
5. Calculate the power of n for each individual and add those numbers
6. Compare the sum with the original number
7. If they exactly matched then it is armstrong number else it is not Armstrong
8. Finally, compare the sum with the original number and conclude that it is Armstrong
number if they are equal

PROGRAM:

#! /usr/bin/python
Number = int(input("\nPlease Enter the Number to Check for Armstrong: "))
# Initializing Sum and Number of Digits
Sum = 0
Times = 0
# Calculating Number of individual digits
Temp = Number
while Temp > 0:
Times = Times + 1
Temp //= 10
# Finding Armstrong Number
Temp = Number
while Temp > 0:
Reminder = Temp % 10
Sum = Sum + (Reminder ** Times)
Temp //= 10
if Number == Sum:
print("\n %d is Armstrong Number.\n" %Number)
else:
print("\n %d is Not a Armstrong Number.\n" %Number)

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 1


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

OUTPUT:
apl@apl-desktop ~/Desktop/pythonpractice $ ./Arm.py Please Enter the Number to Check for
Armstrong: 9474
9474 is Armstrong Number.

apl@apl-desktop ~/Desktop/pythonpractice $ ./Arm.py Please Enter the Number to Check for


Armstrong: 153
153 is Armstrong Number.

apl@apl-desktop ~/Desktop/pythonpractice $ ./Arm.py Please Enter the Number to Check for


Armstrong: 407
407 is Armstrong Number.

apl@apl-desktop ~/Desktop/pythonpractice $ ./Arm.py Please Enter the Number to Check for


Armstrong: 558
558 is Not a Armstrong Number.

RESULT:
Thus the python program for checking of Armstrong number has been successfully
executed and output is verified.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 2


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 1b
DESIGN OF SIMPLE CALCULATOR
Date :
AIM:
To write a program for making a simple calculator that can add, subtract, multiply and
divide using python.

ALGORITHM:

1. Start the program


2. Read a choice from user
3. If the choice is 1
a) Read two numbers (num1 and Num2) from user and find the sum of two
numbers using the following statement
b) res-num1+num2
c) Then print the result
4. If the choice is 2
a) Read two numbers (num1 and Num2) from user and find the difference
between two numbers using the following statement
b) res-num1- num2
c) Then print the result
5. If the choice is 3
a) read two numbers (num1 and Num2) from user and find the multiplication
between two numbers using the following statement
b) res-num1* num2
c) Then print the result
6. if the choice is 4
a) read two numbers (num1 and Num2) from user and find the division of
numbers using the following statement
b) res-num1 / num2
c) Then print the result
7. Stop the program

PROGRAM:

#!/usr/bin/python

# Python Program - Make Simple Calculator


print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Exit");
choice = int(input("Enter your choice: "));

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 3


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

if (choice>=1 and choice<=4):


print("Enter two numbers: ");
num1 = int(input());
num2 = int(input());
if choice == 1:
res = num1 + num2;
print("Result = ", res);
elif choice == 2:
res = num1 - num2;
print("Result = ", res);
elif choice == 3:
res = num1 * num2;
print("Result = ", res);
else:
res = num1 / num2;
print("Result = ", res);
elif choice == 5:
exit();
else:
print("Wrong input..!!");
OUTPUT:
apl@apl-desktop ~/Desktop/pythonpractice $ chmod a+x calc.py apl@apl-desktop
~/Desktop/pythonpractice $ ./calc.py
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter two numbers:
4
5
('Result = ', 9)
apl@apl-desktop ~/Desktop/pythonpractice $ ./calc.py
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 2
Enter two numbers:

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 4


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

4
5
('Result = ', -1)
apl@apl-desktop ~/Desktop/pythonpractice $ ./calc.py
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 3
Enter two numbers:
4
5
('Result = ', 20)
apl@apl-desktop ~/Desktop/pythonpractice $ ./calc.py
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 4
Enter two numbers:
4
5
('Result = ', 0)
apl@apl-desktop ~/Desktop/pythonpractice $
apl@apl-desktop ~/Desktop/pythonpractice $ ./calc.py
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 4
Enter two numbers:
10
2
('Result = ', 5)

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 5


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

RESULT:

Thus the program for making a simple calculator that can add, subtract, multiply and
divide using python has been executed successfully and the output is verified.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 6


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 1c CALCULATION OF FACTORIAL


Date :
AIM:

To write a python program to find the factorial of a given number.

ALGORITHM:

1. Start the program


2. Read a number from user and Initialize factorial=1 and i=1
3. Repeat the steps until i=n
a) factorial←factorial*i
b) i←i+1
4. Display the result
5. Stop the program

PROGRAM:

#! /usr/bin/python
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

OUTPUT:
apl@apl-desktop ~/Desktop/pythonpractice $ chmod a+x fact.py
apl@apl-desktop ~/Desktop/pythonpractice $ ./fact.py
Enter a number: 5

('The factorial of', 5, 'is', 120)


apl@apl-desktop ~/Desktop/pythonpractice $

RESULT:
Thus the program to find the factorial of a given number using python has been executed
successfully and the output is verified.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 7


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 2a GENERATION OF RANDOM NUMBERS AND APPEND THEM TO


Date : THE LIST
AIM:

To write a python program to generate random numbers from 1 to 20 and append them to
the list.

ALGORITHM:

1. Import the random module into the program.


2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them
appending to a list.
4. Then print the randomized list.
5. Exit.

PROGRAM:

import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)

OUTPUT:

apl@apl-desktop ~/Desktop/pythonpractice $ ./ran.py


Enter number of elements:4
('Randomised list is: ', [17, 13, 2, 18])
apl@apl-desktop ~/Desktop/pythonpractice $ ./ran.py
Enter number of elements:7
('Randomised list is: ', [17, 13, 19, 14, 16, 7, 5])
apl@apl-desktop ~/Desktop/pythonpractice $ ./ran.py
Enter number of elements:21
('Randomised list is: ', [3, 20, 12, 3, 16, 10, 19, 1, 11, 18, 4, 8, 15, 16, 16, 5, 9, 4, 11, 20,
3])

RESULT:
Thus the program to generate random numbers from 1 to 20 and append them to the list
using python has been executed successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 8


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 2b CALCULATION OF THE LENGTH OF THE STRING WITHOUT


Date : USING A LIBRARY FUNCTION
AIM:

To write a python program to calculate the length of the string without using a library
function.

ALGORITHM:

1. Start the program


2. Take a string from the user and store it in a variable.
3. Initialize a count variable to 0.
4. Use for loop to traverse through the characters in the string and increment the count
variable each time.
5. Print the total count of the variable.
6. Exit.

PROGRAM:

#! /usr/bin/python
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)of each node and

OUTPUT:

apl@apl-desktop ~/Desktop/pythonpractice $ chmod a+x str.py


apl@apl-desktop ~/Desktop/pythonpractice $ ./str.py
Enter string:hello
Length of the string is:5
apl@apl-desktop ~/Desktop/pythonpractice $ ./str.py
Enter string:welcome
Length of the string is:7

RESULT:
Thus the program to calculate the length of the string without using a library function using
python has been executed successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 9


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 2c
MAPPING OF TWO LISTS INTO DICTIONARY
Date :
AIM:

To write a python program to map two lists into a dictionary.

ALGORITHM:

1. Start the program


2. Declare two empty lists and initialize them to an empty list.
3. Consider for loop to accept values for the two lists.
4. Take the number of elements in the list and store it in a variable
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 3 and 4 for the values list.
7. Zip the two lists and use dict() to convert it into a dictionary.
8. Print the dictionary.

PROGRAM:
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)

OUTPUT:
Enter number of elements for dictionary:3
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
For values:
Enter element1:1
Enter element2:4

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 10


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Enter element3:9
The dictionary is:{1: 1, 2: 4, 3: 9}

RESULT:

Thus the program to map two lists into a dictionary using python has been executed
successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 11


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 3a READING OF A FILE AND CAPITALIZE THE FIRST LETTER OF


Date : EVERY WORD IN THE FILE
AIM:

To write a python program to read a file and capitalize the first letter of every word in the
file.

ALGORITHM:

1. Start the program


2. Read a file name.
3. Opening a file using the open() function in read mode
4. A for loop is used to read through each line in the file.
5. Each word in the line is capitalized using the title() function.
6. The altered lines are printed.

PROGRAM:

fname = input("Enter file name: ")


with open(fname, 'r') as f:
for line in f:
l=line.title()
print(l)

OUTPUT:
Contents of file:
hello world
hello
Enter file name: read.txt
Hello World
Hello

RESULT:

Thus the program to read a file and capitalize the first letter of every word in the file
using python has been executed successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 12


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 3b SHUT DOWN AND RESTART THE COMPUTER


Date :
AIM:

To write a python program to shut down and restart our computer.

ALGORITHM:

1. import os library
2. Read the option from user (Yes or no)
3. If the option is no exit from the program
4. Else use os.system() function with the code "shutdown /s /t 1" and "shutdown /r /t 1"
to shut down and restart our computer in a second.

PROGRAM:

# Python Program - Shutdown Computer import os;


check = input("Want to shut down your computer ? (y/n): ");
if check == 'n':
exit();
else:
os.system("shutdown /s /t 1");
# Python Program - Restart Computer
import os;
check = input("Want to restart your computer ? (y/n): ");
if check == 'n':
exit();
else:
os.system("shutdown /r /t 1");

OUTPUT:

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 13


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

RESULT:

Thus the program to shut down and restart our computer using python has been executed
successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 14


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 3c
RESOLUTION OF THE IMAGE
Date :
AIM:

To write a python program to find resolution of a jpeg image without using external
libraries.

ALGORITHM:

1. Open the image in binary mode


2. Set height of the image is at 164th position followed by width of the image and both
are 2 bytes long
3. Convert the 2 bytes into a number using bitwise shifting operator <<
4. Finally, the resolution is displayed

PROGRAM:
def jpeg_res(filename): #This function prints the resolution of the jpeg image file passed
into it # open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")

OUTPUT:
The resolution of the image is 280 x 280

RESULT:
Thus the program to find resolution of a jpeg image without using external libraries using
python has been executed successfully.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 15


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 4a SIMULATE ELLIPTICAL ORBITS IN PYGAME


Date :
AIM:

To write a python program to stimulate elliptical orbits in Pygame.

ALGORITHM:

1. Import the necessary header files for the implementation of this pygame.
2. Set the display mode for the screen using screen=pygame.display.set_mode
((700,700))
3. Develop the balls with necessary colors.
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
4. Set the radius for sun, moon and their orbit.
5. Set the time for the pygame orbit clock=pygame.time.Clock()
6. Update the earth position.
7. Again update moon position based on earth position.
8. Update the moon and earth angles.
9. Reset the screen and draw the stars, sun, moon and the earth.
10. Set the clock tick as (60) and exit

PROGRAM:

import pygame
import random
import math
pygame.init()
screen=pygame.display.set_mode((700,700))
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
sun_radius=50
center=(350,350)
earth_x=50
earth_y=350 earth_orbit=0
moon_orbit=0

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 16


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

clock=pygame.time.Clock()
running=True
stars=[(random.randint(0,699),random.randint(0,699)) for x in range(140)]
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
earth_x=math.cos(earth_orbit)*300+350
earth_y=-math.sin(earth_orbit)*300+350
moon_x=math.cos(moon_orbit)*50+earth_x
moon_y=-math.sin(moon_orbit)*50+earth_y
earth_orbit+=0.002
moon_orbit+=0.01
screen.fill(black)
for star in stars:
x,y=star[0],star[1]
pygame.draw.line(screen,white,(x,y),(x,y))
pygame.draw.circle(screen,yellow,center,sun_radius)
pygame.draw.circle(screen,blue,(int(earth_x),int(earth_y)),15)
pygame.draw.circle(screen,gray,(int(moon_x),int(moon_y)),5)
pygame.display.flip()
clock.tick(60)
pygame.quit()
OUTPUT:

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 17


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

RESULT:

Thus the simulation of Elliptical orbits using pygame has been successfully executed.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 18


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 4b
SIMULATE BOUNCING BALL USING PYGAME
Date :
AIM:
To write a python program to simulate bouncing ball using Pygame

ALGORITHM:

1. Import the necessary files for the implementation of this Pygame.


2. Set the display mode for the screen using windowSurface=pygame.display.set_mode
((500,400),0,32)
3. Now set the display mode for the pygame to bounce pygame.display.set_caption
(“Bounce”)
4. Develop the balls with necessary colors.
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
5. Set the display information info=pygame.display.Info()
6. Set the initial direction as down.
7. Change the direction from down to up.
8. Then again change the direction from up to down.
9. Set the condition for quit.
10. Exit from the pygame

PROGRAM:

import pygame,sys,time
import random frompygame.locals
import * from time
import * pygame.init()
windowSurface=pygame.display.set_mode((500,400),0,32)
pygame.display.set_caption("Bounce")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
info=pygame.display.Info()
sw=info.current_w
sh=info.current_h
y=0 direction=1

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 19


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface,GREEN,(250,y),13,0)

OUTPUT:

RESULT:

Thus the bouncing ball using pygame has been successfully executed.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 20


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

Ex No: 4c
SIMULATE SIMPLE SNAKE PROGRAM
Date :
AIM:

To write a python program to simulate simple snake program using Pygame.

ALGORITHM:

1. Import the necessary files for the implementation of this Pygame.


2. Develop the balls with necessary colors.
BLACK= (0, 0, 0)
WHITE= (255,255,255)
3. Set the width and height of each snake segment
4. Set Margin between each segment
5. Set initial speed
6. Create an 800x600 sized screen using screen = pygame.display.set_mode([800, 600])
7. Set the title of the window using pygame.display.set_caption('Snake Example')
8. Set the speed based on the key pressed
9. Set the condition for quit.
10. Exit from the pygame

PROGRAM:

import pygame
# --- Globals ---
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set the width and height of each snake
segment segment_width = 15
segment_height = 15
# Margin between each segment
segment_margin = 3
# Set initial speed
x_change = segment_width + segment_margin
y_change = 0
class Segment(pygame.sprite.Sprite):
# Class to represent one segment of the snake
def __init (self, x, y):
# Call the parent's constructor
super(). init ()
# Set height, width
self.image = pygame.Surface([segment_width, segment_height])

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 21


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x self.rect.y =
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])
# Set the title of the window pygame.display.set_caption('Snake Example')
allspriteslist = pygame.sprite.Group()
# Create an initial snake
snake_segments = []
for i in range(15):
x = 250 - (segment_width + segment_margin) * i
y = 30
segment = Segment(x, y)
snake_segments.append(segment)
allspriteslist.add(segment)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the speed based on the key pressed
# We want the speed to be enough that we move a full
# segment, plus the margin.
if event.type == pygame.KEYDOWN:

if event.key == pygame.K_LEFT:
x_change = (segment_width + segment_margin) * -1
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = (segment_width + segment_margin)
y_change = 0
if event.key == pygame.K_UP:
x_change = 0
y_change = (segment_height + segment_margin) * -1
if event.key == pygame.K_DOWN:
x_change = 0
y_change = (segment_height + segment_margin)
# Get rid of last segment of the snake

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 22


IFETCE R-2019 ACADEMIC YEAR: 2021-2022

# .pop() command removes last item in list


old_segment = snake_segments.pop()
allspriteslist.remove(old_segment)
# Figure out where new segment will be
x = snake_segments[0].rect.x + x_change
y = snake_segments[0].rect.y + y_change
segment = Segment(x, y)
# Insert new segment into the list
snake_segments.insert(0, segment)
allspriteslist.add(segment)
# -- Draw everything
# Clear screen screen.fill(BLACK)
allspriteslist.draw(screen)
# Flip screen pygame.display.flip()
# Pause clock.tick(5)
pygame.quit()

OUTPUT:

RESULT:

Thus the simulation of simple snake program using pygame has been successfully
executed.

IFET COLLEGE OF ENGINEERING | Department of Computer Science and Engineering 23

You might also like