0% found this document useful (0 votes)
3 views33 pages

Python Lab Programs

The document contains a series of Python programs demonstrating various functionalities such as temperature conversion, pattern construction, student percentage calculation, area calculation of shapes, prime number identification, factorial calculation, even/odd number counting, string reversal, file handling, turtle graphics, Towers of Hanoi, dictionary management, and a Hangman game. Each section includes code snippets along with sample outputs to illustrate the results of the programs. The programs cover basic programming concepts and are designed for educational purposes.

Uploaded by

vvarsh1212
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

Python Lab Programs

The document contains a series of Python programs demonstrating various functionalities such as temperature conversion, pattern construction, student percentage calculation, area calculation of shapes, prime number identification, factorial calculation, even/odd number counting, string reversal, file handling, turtle graphics, Towers of Hanoi, dictionary management, and a Hangman game. Each section includes code snippets along with sample outputs to illustrate the results of the programs. The programs cover basic programming concepts and are designed for educational purposes.

Uploaded by

vvarsh1212
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

TEMPERATURE CONVERSION

print('Conversion of Temperature'.center(60,'*'))

print ("\n [Link] from Celsius to Fahrenheit \[Link] from Fahrenheit to

Celsius\n")

user=int(input("Enter your choice: "))

if(user==1):

c=float(input("Enter the temperature in Celsius: "))

f = (c * 1.8) + 32

print("Temperature in Fahrenheit=",f)

else:

f=float(input("Enter the temperature in Fahrenheit: "))

c = (f-32)/1.8;

print("Temperature in Celsius =",c)


OUTPUT
1. Convert from Celsius to Fahrenheit

2. Convert from Fahrenheit to Celsius

Enter your choice: 1

Enter the temperature in Celsius: 30

Temperature in Fahrenheit= 86.0

Enter your choice: 2

Enter the temperature in Fahrenheit: 85

Temperature in Celsius = 29.44


2. PATTERN CONSTRUCTION

rows = int(input("Enter the rows"))

k = 2 * rows - 2

for i in range(0, rows):

for j in range(0, k):

print(end="")

k=k-1

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

print("* ", end="")

print("")

k = rows - 2

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

for j in range(k, 0, -1):

print(end="")

k=k+1

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

print("* ", end="")

print("")
OUTPUT

Enter the rows 4

*
**
***
****
*****
****
***
**
*
3. CACULATING STUDENTS PERCENTAGE AND GRADE

Py='Students Marks Database'

print([Link](60,'*'))

sub1=int(input("Enter marks of the first subject: "))

sub2=int(input("Enter marks of the second subject: "))

sub3=int(input("Enter marks of the third subject: "))

sub4=int(input("Enter marks of the fourth subject: "))

sub5=int(input("Enter marks of the fifth subject: "))

total= (sub1+sub2+sub3+sub4+sub5)

avg=total/5

print('\n Total marks : ', total)

print(' Average :', avg)

if(avg>=80):

print("Grade: A")

elif(avg>=70 and avg<80):

print("Grade: B")

elif(avg>=60 and avg<70):

print("Grade: C")

elif(avg>=40 and avg<60):

print("Grade: D")

else:

print("Grade: E")
OUTPUT

******************Students Marks Database*******************

Enter marks of the first subject: 85

Enter marks of the second subject: 77

Enter marks of the third subject: 69

Enter marks of the fourth subject: 88

Enter marks of the fifth subject: 95

Total marks : 414

Average : 82.8

Grade: A
4. FINDING AREA OF GIVEN SHAPES

print ("\n [Link] of Rectangle \n [Link] of Square \n [Link] of Circle \n [Link] of Triangle \n ")

shape=int(input("Enter your choice : "))

if(shape==1):

len=float(input("Enter the length : "))

bre= float(input("Enter the breadth : "))

area =len * bre

print("Area of rectangle",area)

elif(shape==2):

side=float(input("Enter length of side: "))

area=side*side

print("Area of square",area)

elif(shape==3):

import math

r=float(input("Enter radius of circle: "))

area=[Link]*r*r

print("Area of circle ",area)

elif(shape==4):

base=float(input("Enter the base : "))

height= float(input("Enter the height : "))

area =0.5 * base * height

print("Area of triangle",area)

else:

print("Invalid choice")
OUTPUT

1. Area of Rectangle

2. Area of Square

3. Area of Circle

4. Area of Triangle

Enter your choice : 1

Enter the length : 5

Enter the breadth : 6

Area of rectangle 30.0

Enter your choice : 2

Enter length of side: 6

Area of square 36.0

Enter your choice : 3

Enter radius of circle: 7

Area of circle 153.93804002589985

Enter your choice : 4

Enter the base : 2

Enter the height : 3

Area of triangle 3.0


5. PRINTING PRIME NUMBERS LESS THAN 20

Starting_value = 1

n = int(input("Enter your number"))

print("Prime numbers between",Starting_value,"and",n,"are:")

for num in range(Starting_value,n+1):

if num> 1:

for i in range(2,int(num/2)+1):

if(num%i)==0:

break

else:

print(num)
OUTPUT

Enter your number: 20

Prime Numbers Between 1 To 20 are

2
3
5
7
11
13
17
19
6. FINDING FACTORIAL USING RECURSIVE FUNCTION

print("Factorial of a number".center(60,'#'))

n=int(input("Enter a number "))

if n < 0:

print("The factorial of {0} is 0".format(n))

elif n == 0 or n == 1:

print("The factorial of {0} is 1".format(n))

else:

fact = 1

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

fact=fact*i

print("The factorial of {0} is {1}".format(n,fact))


OUTPUT

###################Factorial of a number####################

Enter a number 9

The factorial of 9 is 362880


7. COUNTING EVEN AND ODD NUMBERS IN A LIST

print("Count the number of Odd and Even numbers")

num_list=[]

n=int(input("Enter the number of elements in the list "))

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

val=int(input("Enter the value %d "%i))

num_list.append(val)

count_odd = 0

count_even = 0

for x in num_list:

if not x % 2:

count_even+=1

else:

count_odd+=1

print("Number of even numbers :",count_even)

print("Number of odd numbers :",count_odd)


OUTPUT

Count the number of Odd and Even numbers

Enter the number of elements in the list 7

Enter the value 1 6

Enter the value 2 5

Enter the value 3 9

Enter the value 4 4

Enter the value 5 1

Enter the value 6 8

Enter the value 7 2

Number of even numbers : 4

Number of odd numbers : 3


8. REVERSING A STRING

def rev_words(string):

words = [Link](' ')

rev = ''.join(reversed(words))

return rev

s= input("Enter a string")

print ("The reversed string is: ",rev_words(s))


OUTPUT

Enter a string Basics of python programming

The reversed string is: programming python of Basics


11. WORKING WITH FILES

print("Read a file content and copy only the contents at odd lines into a new

file.")

fn = open('[Link]', 'r')

fn1 = open('odd_file.txt', 'w')

cont = [Link]()

print("[Link] contains")

print(cont)

for i in range(0,len(cont)):

if(i % 2 != 0):

[Link](cont[i])

[Link]()

fn1 = open('odd_file.txt', 'r')

cont1 = [Link]()

print("odd_file.txt contains")

print(cont1)

[Link]()

[Link]()
OUTPUT

Read a file content and copy only the contents at odd lines into a new file.

[Link] contains

['Python is easy to learn\n', 'Python is a interpreted Language\n', 'Python is

created by Guido Van Rossum\n', 'Python has very simple syntax\n', 'Variables

are containers for storing values\n', 'File concept in python is very interesting\n']

odd_file.txt contains

Python is a interpreted Language

Python has very simple syntax

File concept in python is very interesting


12. TURTLE GRAPHICS

import turtle

[Link](800,600)

window=[Link]()

[Link]('My First Turtle Graphics Program')

skk=[Link]()

for i in range(4):

[Link](50)

[Link](90)

[Link]()
OUTPUT
13. TOWERS OF HANOI USING RECURSION

def TowerOfHanoi(n , source, destination, auxiliary):

if n==1:

print ("Move disk 1 from source",source,"to destination",destination )

return

TowerOfHanoi(n-1, source, auxiliary, destination)

print ("Move disk",n,"from source",source,"to destination",destination)

TowerOfHanoi(n-1, auxiliary, destination, source)

# Driver code

n=3

print("Towers of Hanoi".center(60,':'))

TowerOfHanoi(n,'A','C','B')
OUTPUT

::::::::::::::::::::::Towers of Hanoi:::::::::::::::::::::::

Move disk 1 from source A to destination C

Move disk 2 from source A to destination B

Move disk 1 from source C to destination B

Move disk 3 from source A to destination C

Move disk 1 from source B to destination A

Move disk 2 from source B to destination C

Move disk 1 from source A to destination C


14. MENU DRIVEN PYTHON PROGRAM WITH A DICTIONARY

word_dict = {}

def create_dict():

global word_dict

word_dict = {}

ch = "y"

while (ch == "y") or (ch == "Y"):

print("\nEnter word:", end="")

word = input()

print("\nEnter meaning:", end="")

meaning = input()

word_dict[word] = meaning

print("\nDo you want to continue adding words(y or n):", end="")

ch = input()

def add_word():

global word_dict

print("\nEnter word:", end="")

word = input()
print("\nEnter meaning:", end="")

meaning = input()

word_dict[word] = meaning

def find_meaning(w):

return word_dict[w]

def display_sorted():

for w, m in word_dict.items():

print("{0} ==> {1}".format(w,m))

print("Sorted list of words : ")

print(sorted(word_dict.keys()))

def menu_dict():

ch = "y"

while ch == "Y" or ch == "y":

print("1: Create new dictionary")

print("2: Add new word")

print("3: Find meaning")

print("4: Display sorted list of words")

print("5: Quit")
print("Enter Choice: ", end="")

option = int(input())

if option == 1:

create_dict()

elif option == 2:

add_word()

elif option == 3:

print("Enter word:", end="")

word = input()

print("Meaning:%s" % (find_meaning(word)))

elif option == 4:

display_sorted()

elif option == 5:

exit()

print("\nDo you want to continue(y or n)?", end="")

ch = input()

#Driver Code

menu_dict()
OUTPUT

1: Create new dictionary

2: Add new word

3: Find meaning

4: Display sorted list of words

5: Quit

Enter Choice: 1

Enter word:Algorithm

Enter meaning:set of instructions

Do you want to continue adding words(y or n):y

Enter word:binary

Enter meaning:dual

Do you want to continue adding words(y or n):y

Enter word:circuit

Enter meaning:rough circular line

Do you want to continue adding words(y or n):y

Enter word:durable

Enter meaning:able to withstand

Do you want to continue adding words(y or n):n


Do you want to continue(y or n)?y

1: Create new dictionary

2: Add new word

3: Find meaning

4: Display sorted list of words

5: Quit

Enter Choice: 2

Enter word:email

Enter meaning:system of sending messages

Do you want to continue(y or n)?y

1: Create new dictionary

2: Add new word

3: Find meaning

4: Display sorted list of words

5: Quit

Enter Choice: 3

Enter word: durable

Meaning: able to withstand


Do you want to continue(y or n)?y

1: Create new dictionary

2: Add new word

3: Find meaning

4: Display sorted list of words

5: Quit

Enter Choice: 4

Algorithm ==> set of instructions

binary ==> dual

email ==> system of sending messages

circuit ==> rough circular line

durable ==> able to withstand

Sorted list of words :

['Algorithm', 'binary', 'circuit', 'durable', 'email']

Do you want to continue(y or n)?n


15. HANGMAN GAME

import random

print("Hangman Game".center(60,'-'))

name = input("What is your name? ")

print("Good Luck ! ", name)

words = ['rainbow', 'computer', 'science', 'programming', 'python', 'mathematics',

'player', 'condition', 'reverse', 'water', 'board']

word = [Link](words)

print("Guess the characters")

guesses = ''

turns = 12

while turns > 0:

failed = 0

for char in word:

if char in guesses:

print(char)

else:

print("_")

failed += 1

if failed == 0:
print("You Win")

print("The word is: ", word)

break

guess = input("guess a character:")

guesses += guess

if guess not in word:

turns -= 1

print("Wrong")

print("You have", + turns, 'more guesses')

if turns == 0:

print("You Lose")
OUTPUT

------------------------Hangman Game------------------------
What is your name? VCW
Good Luck ! VCW
Guess the characters
_
_
_
_
_
_
guess a character:a
Wrong
You have 11 more guesses
_
_
_
_
_
_
guess a character:e
Wrong
You have 10 more guesses
_
_
_
_
_
_
guess a character:o
_
_
_
_
o
_
guess a character:t
_
_
t
_
o
_
guess a character:r
Wrong
You have 9 more guesses
_
_
t
_
o
_
guess a character:p
p
_
t
_
o
_
guess a character:n
p
_
t
_
o
n
guess a character:y
p
y
t
_
o
n

guess a character:h
p
y
t
h
o
n
You Win
The word is: python

You might also like