0% found this document useful (0 votes)
2 views59 pages

I BSC Python Programs

The document provides an introduction to Python programming, detailing its installation on Windows and basic programming concepts. It includes step-by-step instructions for installing Python, verifying installations, and running Python scripts, along with several example programs for temperature conversion, diamond pattern, student grading, area calculations, prime numbers, and factorial computation. Each example includes algorithms and source code, demonstrating practical applications of Python programming.
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)
2 views59 pages

I BSC Python Programs

The document provides an introduction to Python programming, detailing its installation on Windows and basic programming concepts. It includes step-by-step instructions for installing Python, verifying installations, and running Python scripts, along with several example programs for temperature conversion, diamond pattern, student grading, area calculations, prime numbers, and factorial computation. Each example includes algorithms and source code, demonstrating practical applications of Python programming.
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

INTRODUCTION TO PYTHON PROGRAMMING

Python is a widely used high-level programming language first launched in 1991. Since
then, Python has been gaining popularity and is considered as one of the most popular
and flexible server-side programming languages.

Unlike most Linux distributions, Windows does not come with the Python
programming language by default. However, you can install Python on your
Windows server or local machine in just a few easy steps.

Python 3 Installation on Windows

Step 1: Select Version of Python to Install

The installation procedure involves downloading the official Python .exe


installer and running it on your system. The version you need depends on
what you want to do in Python.

Step 2: Download Python Executable Installer

1. Open your web browser and navigate to the Downloads for Windows
section of the official Python website [[Link]]

2. Search for your desired version of Python.


3. Select a link to download either the Windows x86-64 executable
installer or Windows x86 executable installer.
4. The download is approximately 25MB.
Note: If your Windows installation is a 32-bit system, you need the Windows x86
executable installer. If your Windows is a 64-bit version, you need to download
the Windows x86-64 executable installer. There is nothing to worry about if you
install the “wrong” version. You can uninstall one version of Python and install
another.

Step 3: Run Executable Installer


1. Run the Python Installer once downloaded. (In this example, we
have downloaded Python 3.7.3.)
2. Make sure you select the Install launcher for all users and Add Python
3.7 to PATH checkboxes. The latter places the interpreter in the
execution path. For older versions of Python that do not support the
Add Python to Path checkbox, see Step 6.
3. Select Install Now – the recommended installation options.
4. For all recent versions of Python, the recommended installation options
include Pip and IDLE. Older versions might not include such additional
features.
5. The next dialog will prompt you to select whether to Disable path length
limit. Choosing this option will allow Python to bypass the 260-character
MAX_PATH limit. Effectively, it will enable Python to use long path
names.

The Disable path length limit option will not affect any other system settings.
Turning it on will resolve potential name length issues that may arise with Python
projects developed in Linux.

Step 4: Verify Python was installed on Windows:


1. Step 3: Run Executable Installer Navigate to the directory in which
Python was installed on the system. In our case, it is
C:\Users\Username\AppData\Local\Programs\Python \ Python37
since we have installed the latest version.
2. Double-click [Link].
3. The output should be similar to what you can see below:
Step 5: Verify Pip was installed

If you opted to install an older version of Python, it is possible that it did not
come with Pip preinstalled. Pip is a powerful package management system for
Python software packages. Thus, make sure that you have it installed.

We recommend using Pip for most Python packages, especially when


working in virtual environments.

To verify whether Pip was installed:


1. Open the Start menu and type "cmd."
2. Select the Command Prompt application.
3. Enter pip -V in the console. If Pip was installed successfully,
you should see the following output:

Step 6: Run Python

Python has been installed in your system, Now go to


1. Windows search.
2. Type IDLE.
3. Open it.

Run your First Python Code


LEARN TO EXECUTE A PYTHON SCRIPT FROM THE COMMAND LINE, AND
HOW YOU CAN PROVIDE COMMAND LINE ARGUMENTS.

Computers cannot understand code in the way humans write it and hence, you need
an interpreter between the computer and the human written code. The job of the
interpreter is to convert the code into a format that computers can then understand
and process.
The interpreter processes the code in the following ways:
• Processes the Python script in a sequence

• Compiles the code into a byte code format which is a


lower-level language understood by the computers.

• Finally, a Python Virtual Machine (PVM) comes into the


picture. The PVM is the runtime powerhouse of Python. It
is a process that iterates over the instructions of your low-
level bytecode code to run them one by one.

Like Scripts, you have a have something called Module which is a Python script
imported and used in another Python script. The Python script is saved with a .py
extension which informs the computer that it is a Python program script. Unlike
Windows, the Unix based operating systems such as Linux and Mac come with pre-
installed Python. Also, the way Python scripts are run in Windows and Unix
operating systems differ.
Command-line interpreter for Python can be accessed on the various operating
systems in the following ways:
• On Windows, the command line is known as the command
prompt which can be accessed by clicking the start menu and
search for command prompt. Another way is by going to the
Run dialog box type cmd and press enter (Start menu $->$ Run
and type cmd). After which, if Python is installed in your C-drive
then all you have to do is type C:\python36\[Link], where
python36 is the Python version (Note: This path may vary based
on the directory at which Python is configured).
EX NO: 1 TEMPERATURE CONVERSION
DATE:

Aim:
Python Program to convert the given temperature from Fahrenheit to Celsius
and vice versa depending upon user’s choice.

Algorithm:

Step 1: Start
Step 2: Read user choice as choice.
Step 3: If choice=1 then Goto step 4 else Goto Step8
Step 4: Read the value of Fahrenheit as F
Step 5: C=(F-32) * 5/9
Step 6: Write the value Celsius as C
Step 7: Go to Step 13
Step 8: If choice=2 then Go to step 9 else Go to Step 11
Step 9: Read the value of Celsius as C
Step 10: F=9/5*c+32
Step 11: Write the value Fahrenheit as F
Step 12: if choice!=3 Go to Step 2
Step 13: Stop
SOURCE CODE: [Link]

print('''**************************PROGRAM FOR TEMPERATURE CONVERSION


***********************''')

print('''TYPE 1 FOR FAHRENHEIT TO CELSIUS TYPE 2 FOR CELSIUS TO FAHRENHEIT


TYPE 3 FOR EXIT ''')

choice=0

while choice !=3:

choice=int(input("ENTER YOUR CHOICE: "))

if (choice==1):

f=float(input("ENTER THE TEMPERATURE IN FAHRENHEIT: "))

c=(f-32)*5.0/9.0

c=format(c,'.2f')

print(f," Degree FAHRENHEIT is ",c," in Degree CELSIUS")

if (choice==2):

c=float(input("ENTER THE TEMPERATURE IN CELSIUS: "))

f=9.0/5.0 * c +32

f=format(f,'.2f')

print(c," Degree CELSIUS is ", f," in Degree FAHRENHEIT")


OUTPUT – TEMPERATURE CONVERSION

Result:
The conversion of Fahrenheit to Celsius and vice versa has executed successfully.
EX NO: 2 DIAMOND PATTERN
DATE:

Aim:

To write a Python program to construct the diamond pattern using a nested loop.

Algorithm:

Step 1 : Start.
Step 2 : Read the value of val.
Step 3 : To print the upper part of diamond. Iterate each element in the list
using Nested for loop
Step 4 : Using the nested for loop, print the upper part of diamond with Star(*)
Symbol.
Step 5 : To print the Lower part of diamond. Iterate each element in the list
using Nested for loop
Step 6 : Using the nested for loop, print the lower part of diamond with Star(*)
Symbol.
Step 7: Stop.
SOURCE CODE: [Link]

val = int(input("Enter the value: "))

#Upper part of diamond


for i in range(1, val+1):
for j in range(1, val-i+1):
print(end=" ")
for k in range(1, i+1):
print("*", end=" ")
print()

#Lower part of diamond


for i in range(1, val):
for j in range(0, i):
print(end=" ")
for k in range(0, val-i):
print("*", end=" ")
print()
OUTPUT – DIAMOND PATTERN

Result:
Thus, the Python program to construct the Diamond pattern has been executed
successfully.
EX NO: 3 CALCULATING TOTAL MARKS, PERCENTAGE AND
DATE: GRADE OF A STUDENT
Aim:

To write a Python program to read five subject marks and calculate the total marks,
percentage and grade of a student..

Algorithm:

Step 1 : Start.
Step 2 : Read the values of Roll_No, Stud_Name, M1, M2, M3, M4 and M5.
Step 3 : Calculate Total=M1+M2+M3+M4+M5.
Step 4 : Calculate Percentage=Total/5.
Step 5 : If Percentage>=80, then calculate Grade=”A”.
Step 6 : Else If Percentage >=70 and Percentage<80, then calculate
Grade=”B”.
Step 7 : Else If Percentage >=60 and Percentage<70, then calculate
Grade=”C”.
Step 8 : Else if Percentage >=40 and Percentage<60, then calculate
Grade=”D”.
Step 9 : Else, calculate Grade="E”.
Step 10 : Print the values of Roll_No, Stud_Name, M1, M2, M3, M4, M5, Total,
Percentage and Grade.
Step 11 : Stop.
SOURCE CODE: MARK_LIST.PY

#Python Program to calculate the Total and Grade of a Student


Roll_No=int(input("Enter the Roll Number: "))
Stud_Name=input("Enter the Student Name : ")
M1=int(input("Enter the Mark1 : "))
M2=int(input("Enter the Mark2 : "))
M3=int(input("Enter the Mark3 : "))
M4=int(input("Enter the Mark4 : "))
M5=int(input("Enter the Mark5 : "))
Total=M1+M2+M3+M4+M5
Percentage=Total/5

print()
print("Roll Number :",Roll_No)
print("Student Name :",Stud_Name)
print("Mark1 :",M1)
print("Mark2 :",M2)
print("Mark3 :",M3)
print("Mark4 :",M4)
print("Mark5 :",M5)
print("Total :",Total)
print("Average :",Percentage)
SOURCE CODE: MARK_LIST.PY

if M1>=40 and M2>=40 and M3>=40 and M4>=40 and M5>=40:


if Percentage>=80:
Grade="A"
print("Grade :",Grade)
print("***You have passed***")
elif Percentage >=70 and Percentage<80:
Grade="B"
print("Grade :",Grade)
print("***You have passed***")
elif Percentage >=60 and Percentage<70:
Grade="C"
print("Grade :",Grade)
print("***You have passed***")
elif Percentage >=40 and Percentage<60:
Grade="D"
print("Grade :",Grade)
print("***You have passed***")
else:
Grade="E"
print("Grade :",Grade)
print("***You have failed***")
OUTPUT – CALCULATING TOTAL MARKS, PERCENTAGE AND
GRADE OF A STUDENT

Result:
Thus, the Python program to calculate the Total and Grade of a student has been executed
successfully.
EX NO: 4 AREA OF SHAPES
DATE:

Aim:
To write a Python program to find the area of a Rectangle, Square, Circle and
Triangle by accepting suitable input parameters from user.

Algorithm:

Step 1 : Start.
Step 2 : Read the value of Shape.
Step 3 : If Shape=”Rectangle”, then call the function Rectangle(), which will
calculate the area of a Rectangle.
Step 4 : If Shape=”Square”, then call the function Square(), which will calculate
the area of a Square.
Step 5 : If Shape=”Circle”, then call the function Circle(), which will calculate the
area of a Circle.
Step 6 : if Shape=”Triangle”, then call the function Triangle(), which will
calculate the area of a Triangle.
Step 7 : Else print the message “Select a Valid Shape”.
Step 8 : Stop.
SOURCE CODE: RECT_SQUARE_CIRCLE_TRIANGLE_AREA.PY

# Python Program to find to find the Area of a Rectangle, Square, Circle


and Triangle
# Function to calculate the area of a Rectangle
def Rectangle():
l=float(input("Enter the Length of a Rectangle : "))
b=float(input("Enter the Breadth of a Rectangle : "))
R_Area = l * b
print("\nThe Area of a Rectangle is : %0.2f" %R_Area)
return
# Function to calculate the area of a Square
def Square():
s=int(input("Enter the side length of a Square : "))
S_Area=s*s
print("\nThe Area of a Square is : ",S_Area)
return
# Function to calculate the area of a Circle
def Circle():
PI=3.14
r=float(input("Enter the radius of a Circle: "))
C_Area = PI*r*r
print("\nThe Area of a Circle is : %0.2f"%C_Area)
return
# Function to calculate the area of a Triangle
def Triangle():
a=int(input("Enter the first side of a Triangle : "))
b=int(input("Enter the second side of a Triangle : "))
c=int(input("Enter the third side of a Triangle : "))
s=(a+b+c)/2
T_Area=(s*(s-a)*(s-b)*(s-c)) ** 0.5
print("The Area of a Triangle is : %0.2f"%T_Area)
return
SOURCE CODE: RECT_SQUARE_CIRCLE_TRIANGLE_AREA.PY

# Main Program

print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")
Shape=input("Enter the shape you want to calculate the area: ")
if Shape=="Rectangle":
Rectangle()
elif Shape=="Square":
Square()
elif Shape=="Circle":
Circle()
elif Shape=="Triangle":
Triangle()
else:
print ("Select a Valid Shape")
OUTPUT – AREA OF SHAPES

Result:
Thus, the Python program to find the area of a Rectangle, Square, Circle and Triangle has
been executed successfully.
EX NO: 5 PRIME NUMBERS
DATE:

Aim:
To write a python script that prints prime numbers less than 20.

Algorithm:

Step 1: Start
Step 2: Loop through numbers ‘num’ from 2 to 19.
Step 3: For each ‘num’, check if it is divisible by any number ‘i’ from 2 to the
square root of ‘num’.
Step 4: If ‘num’ is not divisible by any ‘i’, then it is a prime number.
Step 5: Print the prime number ‘num’.
Step 6: Stop
SOURCE CODE: PRIME_NUMBERS.PY

# Python script that prints prime numbers less than 20.


Starting_Value = 1
Ending_Value = 20
for num in range(Starting_Value, Ending_Value + 1):
if num > 1:
for j in range(2, int(num /2) + 1):
if num % j == 0:
break
else:
print(num, end="\n")
OUTPUT – PRIME NUMBERS

Result:
Thus, the program that prints prime numbers less than 20 using Python has been executed
successfully.
EX NO: 6 FACTORIAL
DATE:

Aim:
To write a program to find factorial of the given number using recursive function

Algorithm:

Step 1: Start
Step 2: Read num from the user
Step 3: Define a recursive function factorial(x) as follows:
a. If x is 1, return 1
b. Otherwise, return (x * factorial(x-1))
Step 4: Call factorial(num) and store the result in the variable result
Step 5: Print "The factorial of", num, "is", result
Step 6: Stop
SOURCE CODE: [Link]

# Program to find the factorial of a given number using recursion


def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = int(input("Enter a number: "))


result = factorial(num)
print("The factorial of", num, "is", result)
OUTPUT – FACTORIAL

Result:
Thus, the program that finds the factorial of a given number using Python has been
executed successfully.
EX NO: 7 COUNTING THE EVEN AND ODD NUMBERS
DATE:

Aim:
To write a Python program to count the Even and Odd numbers in an array of N numbers.

Algorithm:

Step 1 : Start.
Step 2 : Initialize the array a.
Step 3 : Initialize even=0, odd=0.
Step 4 : Read the value of n.
Step 5 : Iterate each element in the list using a for loop and check if num % 2
== 0, the condition to check even numbers.
Step 6 : If the condition satisfies, then increase even else increase odd.
Step 7 : Print the number of even numbers.
Step 8 : Print the number of odd numbers.
Step 9 : Stop.
SOURCE CODE: EVEN_ODD.PY

# Program to count the number of even or odd numbers from array of 'n'
numbers
n = int(input("Enter the number of elements: "))
a = []
for i in range(n):
num = int(input(f"Enter element {i + 1}: "))
[Link](num)
even = 0
odd = 0
for num in a:
if num % 2 == 0:
even += 1
else:
odd += 1
print(f"\nThe number of even numbers in the array: {even}")
print(f"The number of odd numbers in the array: {odd}")
OUTPUT – COUNTING THE EVEN AND ODD NUMBERS

Result:
Thus, the program that counts the Even and Odd numbers in an array of N numbers using
Python has been executed successfully.
EX NO: 8 REVERSE A STRING WORD BY WORD
DATE:

Aim:
To write a python class to reverse a string word by word.

Algorithm:

Step 1: Start
Step 2: Create a class named StringReverser with a method
reverse_words(self, string):
a. Split the input string into words using the split() method
b. Reverse the list of words using slicing (rev = words[::-1])
c. Join the reversed words into a string with spaces using join()
d. Return the reversed string
Step 3: Create an instance of the StringReverser class named reverser
Step 4: Read a string from the user and store it in the variable string
Step 5: Call the reverse_words method of the reverser instance with the string
as an argument, and store the result in the variable reversed_string
Step 6: Print the reversed_string
Step 7: Stop
SOURCE CODE: STRING_REVERSE.PY

# Python class to reverse a string word by word


class StringReverser:
def reverse_words(self, string):
words = [Link]()
rev = words[::-1]
rev_string = " ".join(rev)
return rev_string

# Main Program
reverser = StringReverser()
string = input("Enter a string: ")
reversed_string = reverser.reverse_words(string)
print(reversed_string)
OUTPUT – REVERSE A STRING WORD BY WORD

Result:
Thus, the python class to reverse a string word by word using Python has been executed
successfully.
EX NO: 9 OCCURRENCES OF ALL ITEMS OF THE LIST IN THE
DATE: TUPLE
Aim:
To write a python program to count the occurrences of all items of the list in the tuple.

Algorithm:

Step 1: Start
Step 2: Read tuple1 from the user and store it in the variable tuple1
Step 3: Read list1 from the user and store it in the variable list1
Step 4: Initialize a variable items to 0
Step 5: For each item i in list1:
a. For each item j in tuple1:
i. If i is equal to j, increment items by 1
ii. Otherwise, continue to the next iteration
Step 6: Print the value of items
Step 7: Stop
SOURCE CODE: [Link]

# Program to count the occurrence of all items of a list in the tuple


tuple1 = eval(input("Enter a tuple: "))
list1 = eval(input("Enter a list: "))

items = 0

for i in list1:
for j in tuple1:
if i == j:
items += 1
else:
continue
print(items)
OUTPUT – OCCURRENCES OF ALL ITEMS OF THE LIST IN THE
TUPLE

Result:
Thus, the program to count the occurrences of all items of the list in the tuple using Python
has been executed successfully.
EX NO: 10 SAVINGS ACCOUNT
DATE:

Aim:
To create a Savings Account class that behaves just like a Bank Account, but also has an
interest rate and a method that increases the balance by the appropriate amount of interest.
Algorithm:

Step 1: Start
Step 2: Define a class BankAccount with attributes account_number and
balance, and methods deposit, withdraw, and get_balance.
Step 3: Define a subclass SavingsAccount inheriting from BankAccount, with an
additional attribute interest_rate and a method add_interest.
Step 4: Prompt the user to input account holder name, account number, and
initial balance.
Step 5: Create a SavingsAccount instance named savings_acc using the
provided input and a fixed interest rate of 0.05 (5%).
Step 6: Print account details: account holder name, account number, and initial
balance.
Step 7: Enter a loop for banking operations, with a menu of options:
1: Deposit money into the savings account, adding interest and printing
the updated balance.
2: Withdraw money from the savings account and print the updated
balance.
3: Print the interest earned and the balance with interest.
4: Print the current balance.
5: Exit the loop.
Step 8: For each option selected:
If 1: Prompt user for deposit amount, call deposit and add_interest
methods, and print the updated balance.
If 2: Prompt user for withdrawal amount, call withdraw method, and print
the updated balance.
If 3: Print the interest earned and the balance with interest.
If 4: Print the current balance.
If 5: Exit the loop.
Step 9: If an invalid option is selected, prompt the user to enter a correct input.
Step 10: Stop
SOURCE CODE: SAVINGS_ACCOUNT.PY

class BankAccount:
def __init__(self, account_number, balance):
self.account_number = account_number
[Link] = balance
def deposit(self, amount):
if amount > 0:
[Link] += amount
return True
else:
return False
def withdraw(self, amount):
if 0 < amount <= [Link]:
[Link] -= amount
return amount
else:
return None
def get_balance(self):
return [Link]

class SavingsAccount(BankAccount):
def __init__(self, account_number, balance, interest_rate):
super().__init__(account_number, balance)
self.interest_rate = interest_rate
def add_interest(self):
interest = [Link] * self.interest_rate
[Link] += interest
return interest
SOURCE CODE: SAVINGS_ACCOUNT.PY

# Account Details
name = input("Enter Account holder name: ")
acc = int(input("Enter account number: "))
acc_no = str(acc)
initial = int(input("Enter initial balance: "))

# Creating a SavingsAccount with 5% interest rate


savings_acc = SavingsAccount(acc_no, initial, 0.05)

# Printing account details


print()
print("Account holder name:", name)
print("Account number :", acc_no)
print("Initial Balance :", savings_acc.get_balance())

# Usage
bank = True
while bank:
print("\n1. Deposit\n2. Withdrawl\n3. Interest Earned\n4. Balance\n5.
Exit")
answer = int(input("Enter an option: "))
if answer == 1:
dep = int(input("\nEnter the amount to be deposited: "))
savings_acc.deposit(dep)
interest_earned = savings_acc.add_interest()
print("Balance after deposit:", savings_acc.get_balance())
elif answer == 2:
withd = int(input("\nEnter the amount to be withdrawn: "))
savings_acc.withdraw(withd)
print("Balance after withdrawal:", savings_acc.get_balance())
SOURCE CODE: SAVINGS_ACCOUNT.PY

elif answer == 3:
print("\nInterest earned:", interest_earned)
print("Balance with interest:", savings_acc.get_balance())
elif answer == 4:
print("Balance:", savings_acc.get_balance())
elif answer == 5:
print("\n****---------****")
break
else:
print("Please, Enter correct input")
continue
OUTPUT – SAVINGS ACCOUNT
OUTPUT – SAVINGS ACCOUNT

Result:
Thus, the program Create a Savings Account class that behaves just like a Bank Account
using Python has been executed successfully.
EX NO: 11 TEXT FILES
DATE:

Aim:
To write a python program to Read a file content and copy only the contents at odd lines
into a new file.

Algorithm:

Step 1: Start
Step 2: Open the input file for reading ([Link]) and the output file for writing
([Link]).
Step 3: Read all lines from the input file into a list.
Step 4: Calculate the total number of lines in the input file (l).
Step 5: Loop through each line index from 0 to l - 1:
a. Check if the current line index is odd (i.e., i % 2 == 0).
b. If the index is odd, write the current line from the input list to the output
file.
Step 6: Close both the input and output files.
Step 7: Stop
SOURCE CODE: TEXT_FILES.PY

# Read a file content and copy only the contents at odd lines into a new
file
# Use this only for creating a text file and to write a sample paragraph
in it.
# Comment after use
file = open("E://[Link]", 'w')
a = ["Python is a versatile language\n","high-level programming
language\n","Suitable for a wide range of applications\n","Python's syntax
is designed to be clear and easily readable\n","Python is dynamically
typed\n"]

for i in a:
[Link](i)
[Link]()

file = open("E://[Link]", 'r')


out = open("E://[Link]", 'w')
r = [Link]()
l = len(r)
for i in range(0, l):
if i % 2 == 0:
[Link](r[i])
[Link]()
[Link]()

# To check whether the content copied to new line


out = open("E://[Link]", 'r')
r = [Link]()
print(r)
[Link]()
OUTPUT – TEXT FILES

Result:
Thus, the program to Read a file content and copy only the contents at odd lines into a new
file using Python has been executed successfully..
EX NO: 12 TURTLE GRAPHICS WINDOW
DATE:

Aim:
To write a Python Program to create a turtle graphics window with the specified size.

Algorithm:

Step 1 : Start.
Step 2 : Import the Turtle module using the import turtle statement.
Step 3 : Set the window size using the setup() method.
Step 4 : Change the background color of the turtle graphics window using the
bgcolor() method.
Step 5 : Assign a title for the window using the title() method.
Step 6 : Stop.
SOURCE CODE: TURT_WIN.PY

# Python Program to create a Turtle Graphics Window with Specified Size

import turtle # Loads the turtle module


[Link](500, 300) # Set the window size to 500 by 300 pixels
wn = [Link]() # Creates a graphics window
[Link]("Cyan")
[Link]("Turtle Graphics Window")
OUTPUT – TURTLE GRAPHICS WINDOW

Result:
Thus, the program to create a turtle graphics window with the specified size using Python
has been executed successfully.
EX NO: 13 TOWERS OF HANOI
DATE:

Aim:
To write a Python program for Towers of Hanoi using Recursion.

Algorithm:

Step 1 : Start.
Step 2 : Define a function named Tower_Of_Hanoi().
Step 3 : Read the number of Disks.
Step 4 : Move top (n-1) disks from source to auxiliary peg.
Step 5 : Move 1 disk from source to destination peg.
Step 6 : Move top (n-1) disks from auxiliary to destination.
Step 7 : Stop.
SOURCE CODE: TOWERS_OF_HANOI.PY

# Python Program for Towers of Hanoi using Recursion

def Tower_Of_Hanoi(n , source, destination, auxilliary):


if n==1:
print("Move Disk 1 from Source",source,"to
Destination",destination)
return
Tower_Of_Hanoi(n-1, source, auxilliary, destination)
print("Move Disk",n,"from Source",source,"to
Destination",destination)
Tower_Of_Hanoi(n-1, auxilliary, destination, source)

# Main Program
n=int(input("Enter the number of Disks: "))
Tower_Of_Hanoi(n,'A','B','C') # A, C, B are the name of rods
OUTPUT – TOWERS OF HANOI

Result:
Thus, the Python Program for Towers of Hanoi using Recursion has been executed
successfully.
EX NO: 14 MENU DRIVEN
DATE:

Aim:
To Create a menu driven Python program with a dictionary for words and their meanings.

Algorithm:

Step 1: Start
Step 2: Initialize an empty dictionary called 'dictionary'.
Step 3: Display the menu options:
1. Add word and meaning
2. Look up meaning
3. Exit
Step 4: Prompt the user to enter their choice and store it in 'choice'.
Step 5: If 'choice' is 1:
i. Prompt the user to enter a word and store it in 'word'.
ii. Prompt the user to enter the meaning of the word and store it in
'meaning'.
iii. Add the word and its meaning to the 'dictionary'.
iv. Display a message that the word has been added.
Step 6: If 'choice' is 2:
i. Prompt the user to enter a word to look up and store it in 'word'.
ii. Look up the meaning of the word in the 'dictionary'.
iii. If the meaning is found, display the meaning.
iv. If the meaning is not found, display a message that the word is not in
the dictionary.
Step 7: If 'choice' is 3:
i. Display a message that the program is exiting.
ii. Break the loop to stop the program.
Step 8: If 'choice' is none of the above:
i. Display a message that the choice is invalid.
Step 9: Stop
SOURCE CODE: MENU_DRIVEN.PY

# Create a menu driven Python program with a dictionary for words and
their meanings

dictionary = {}

while True:
print("\nMenu:")
print("1. Add word and meaning")
print("2. Look up meaning")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
word = input("\nEnter the word: ")
meaning = input("Enter the meaning: ")
dictionary[word] = meaning
print(f"'{word}' has been added to the dictionary.")
elif choice == "2":
word = input("\nEnter the word to look up: ")
meaning = [Link](word)
if meaning:
print(f"The meaning of '{word}' is: {meaning}")
else:
print(f"'{word}' not found in the dictionary.")
elif choice == "3":
print("\nExiting the program.")
break
else:
print("Invalid choice. Please choose a valid option.")
OUTPUT – MENU DRIVEN

Result:
Thus, the menu driven Python program with a dictionary has been executed successfully.
EX NO: 15 HANGMAN GAME
DATE:

Aim:
To write a Python program to implement the Hangman Game.

Algorithm:

Step 1 : Start.
Step 2 : Import the random module into the program.
Step 3 : Read the value of n.
Step 4 : Using a for loop, read the words one by one and store it in an array.
Step 5 : In this game, the interpreter will choose one random word from a list of
words.
Step 6 : Read the name of the user.
Step 7 : Read the alphabet to guess.
Step 8 : If the random word contains that alphabet, it will be shown as the
output (with correct placement) else the program will prompt us to guess another
alphabet.
Step 9 : Read the number of turns.
Step 10 : The user will be given the number of turns to guess the complete
word.
Step 11 : Stop.
SOURCE CODE: HANGMAN_GAME.PY

# Python program to implement the Hangman Game

import random

# Library that we use in order to choose on random words from a list


of words

words=[]
n=int(input("Enter number of words: "))
for i in range(1,n+1):
w=input("Enter the %d word : " %i)
[Link](w)
print("\nWords in the List: ")
print(words)

# Here the user is asked to enter the name first


name = input("\nWhat is your name? ")
print("Good Luck !",name)

# Function will choose one random word from this list of words
word = [Link](words)

# Read the number of turns for the user


turns = int(input("Enter the number of turns : "))
print("\nGuess the Characters")
SOURCE CODE: HANGMAN_GAME.PY

guesses = ''

while turns > 0:


# Counts the number of times a user fails
failed = 0

# All characters from the input word taking one at a time.


for char in word:
# Comparing that character with the character in guesses
if char in guesses:
print(char)
else:
print("_")

# For every failure 1 will be incremented in failure


failed += 1

if failed == 0:
# User will win the game if failure is 0 and 'You Win' will be
given as output
print("You Win")
# This print the correct word
print("The word is: ", word)
break

# If the user has input the wrong alphabet then it will ask user to
enter another alphabet
guess = input("Guess a character : ")
SOURCE CODE: HANGMAN_GAME.PY

# Every input character will be stored in guesses


guesses += guess

# Check input with the character in word


if guess not in word:
turns -= 1
# If the character doesn’t match the word then “Wrong” will be
given as output
print("Wrong")
# This will print the number of turns left for the user
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")
OUTPUT – HANGMAN GAME
OUTPUT – HANGMAN GAME
OUTPUT – HANGMAN GAME

Result:
Thus, the Python program to implement the Hangman game has been executed
successfully.

You might also like