Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
762 views

Python Main Program Set 2

The program allows users to interact with a dictionary through a menu. The menu offers options to create, print, modify and search the dictionary. Key features include adding and removing key-value pairs, checking if a key exists, copying dictionaries and updating dictionary content. Based on the user's choice, the relevant dictionary operations are performed. The menu loops until the user chooses the exit option.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
762 views

Python Main Program Set 2

The program allows users to interact with a dictionary through a menu. The menu offers options to create, print, modify and search the dictionary. Key features include adding and removing key-value pairs, checking if a key exists, copying dictionaries and updating dictionary content. Based on the user's choice, the relevant dictionary operations are performed. The menu loops until the user chooses the exit option.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

9.

PROGRAM TO FIND THE SUM OF ALL ITEMS IN A DICTIONARY

Aim:

To write a Python program to find the sum of all items in a Dictionary.

Algorithm:

Step 1 : Start.
Step 2 : Create a dictionary with some Key - Value pairs.
Step 3 : Read the number of Key / Value pair in a dictionary.
Step 4 : Read the Key.
Step 5 : Read the Value.
Step 6 : Add the Key / Value pair into the dictionary.
Step 7 : The sum() method is used to get the sum of all the values.
Step 8 : Print the sum of all items in the dictionary.
Step 9 : Stop.

Program:

# Python Program to find the sum of all items in a dictionary


# Dict_Sum.py
# Creating the dictionary class
class my_dictionary(dict):
def __init__(self): # The “__init__" method is used to initialize the object
self = dict() # The "self" keyword represents the same object or instance of the class
# Function to add Key:Value
def add(self, Key, Value):
self[Key]=Value
# Main Program
dict_obj = my_dictionary()
n=int(input("Enter the no of Key / Value pair in a dictionary: "))
i=1
while i<=n:
dict_obj.Key = input("Enter the Key: ")
dict_obj.Value = int(input("Enter the Value: "))
dict_obj.add(dict_obj.Key, dict_obj.Value)
i=i+1
print("The Dictionary Object is")
print(dict_obj)
print("Sum of all items in the dictionary=",sum(dict_obj.values()))

Output:

Enter the no of Key / Value pair in a dictionary: 3


Enter the Key: a
Enter the Value: 100
Enter the Key: b
Enter the Value: 200
Enter the Key: c
Enter the Value: 300
The Dictionary Object is
{'a': 100, 'b': 200, 'c': 300}
Sum of all items in the dictionary= 600
>>>
Result:
Thus, the Python program to find the sum of all items in a dictionary has been
executed successfully.
10. PYTHON PROGRAM TO PRINT THE TRIANGLE USING NESTED LOOP

Aim:

To write a Python program to print the Triangle using nested loop .

Algorithm:

Step 1 : Start.
Step 2 : Read the number of rows.
Step 3 : Using the nested for loop, print the triangle with numbers.
Step 4 : Stop.

Program:

# Python Program to print the pyramid pattern


n=int(input("Enter the number of rows: "))
for i in range(n+1):
for j in range(1,i+1):
print(i,end="")
print("")

Output:

Enter the number of rows: 9

1
22
333
4444
55555
666666
7777777
88888888
999999999
>>>
Result:

Thus, the Python program to construct the Triangle pattern has been executed
successfully.
11. PYTHON PROGRAM TO READ A FILE AND COPY ONLY THE ODD LINES INTO A NEW
FILE

Aim:

To write a Python Program to read a file and copy only the odd lines into a new file.

Algorithm:

Step 1 : Start
Step 2 : Open the first file in read mode.
Step 3 : Assign the first file to F1.
Step 4 : Open the second file in write mode.
Step 5 : Assign the second file to F2.
Step 6 : Read the content line by line of the file F1 and assign it to File1_Cont.
Step 7 : Access each element from 0 to length of File1_Cont.
Step 8 : Check if i is not divisible by 2 then write the content in F2 else pass.
Step 9 : Close the file F1.
Step 10 : Now open File2.txt in read mode and assign it to F2.
Step 11 : Read the content of the file F2 and assign it to File2_Cont.
Step 12 : Print the content of the file F2.
Step 13 : Close the files F1 and F2.
Step 14 : Stop.

Program:
# Python Program to Read a file and copy only the odd lines into a new file
# Open the first file in read mode
F1=open('File1.txt', 'r')

# Open the second file in write mode


F2=open('File2.txt', 'w')

# Read the content of the file line by line


File1_Cont = F1.readlines()
type(File1_Cont)
for i in range(0, len(File1_Cont)):
if(i%2 != 0):
F2.write(File1_Cont[i])
else:
pass

# Close the file


F1.close()

# Open file in read mode


F2 = open('File2.txt', 'r')

# Read the content of the file


File2_Cont = F2.read()

# Print the content of the file


print(File2_Cont)

# Close all files


F1.close()
F2.close()

Output:
Honesty is the Best Policy
Self Help is the Best Help

Result:
Thus, the Python program to read a file and copy only the odd lines into a new
file has been executed successfully.
12. PYTHON PROGRAM TO CREATE A TURTLE GRAPHICS WINDOW WITH SPECIFIC SIZE

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.

Program:

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


# Turt_Win.py
import turtle # Loads the turtle module
turtle.setup(500, 300) # Set the window size to 500 by 300 pixels
wn = turtle.Screen() # Creates a graphics window
wn.bgcolor("Cyan")
wn.title("Turtle Graphics Window")
Output:

Result:

Thus, the Python program to create a Turtle Graphics Window with the specified
size has been executed successfully.
13. PYTHON PROGRAM FOR TOWERS OF HANOI USING RECURSION

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.

Program:

# 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:

Enter the number of Disks: 3


Move Disk 1 from Source A to Destination B
Move Disk 2 from Source A to Destination C
Move Disk 1 from Source B to Destination C
Move Disk 3 from Source A to Destination B
Move Disk 1 from Source C to Destination A
Move Disk 2 from Source C to Destination B
Move Disk 1 from Source A to Destination B
>>>
Result:

Thus, the Python Program for Towers of Hanoi using Recursion has been
executed successfully.
14. MENU DRIVEN PYTHON PROGRAM WITH A DICTIONARY OF WORDS AND THEIR MEANINGS

Aim:

To write a menu driven Python program with a dictionary of words and their meanings.

Algorithm:

Step 1 :Start.
Step 2 :Create a dictionary object.
Step 3 :Read the value of ch.
Step 4 :If ch==1, then perform the following operations:
i) Read the number of Key / Value pair in a dictionary.
ii) Using while loop, do the following:
a. Read the Key.
b. Read the Value.
c. Add the Key / Value pair into the dictionary.
Step 5 : If ch==2, then print the dictionary.
Step 6 : If ch==3, then remove the specified Key from the dictionary.
Step 7 : If ch==4, then search the specified Key exists in the dictionary or not.
Step 8 : If ch==5, then copy the content of one dictionary to another.
Step 9 : If ch==6, then delete the entire dictionary.
Step 10 : If ch==7, empty the dictionary.
Step 11 : If ch==8, then print the length of the dictionary.
Step 12 : If ch==9, then print all the Key names in the dictionary.
Step 13 : If ch==10, then print all the Values in the dictionary.
Step 14 : If ch==11, then print the value of the specified Key.
Step 15 : If ch==12, then print both the Key names and Values of the dictionary.
Step 16 : If ch==13, then update the dictionary. Updating the dictionary means we can add
more items to the end of the dictionary.
Step 17 : if choice=14, then exit the program else print the message “Wrong Choice”.
Step 18 : Read the value of ans.
Step 19 : If ans==’Y’, then go to Step 3.
Step 20 : Stop.

Program:
# Menu driven Python program with a dictionary for words and their meanings
# Mecu_Dict.py
# Creating the dictionary class
class My_Dict(dict):
def __init__(self): # The __init__" method is used to initialize the object
self = dict() # The "self" keyword represents the same object or instance of the class
# Function to add Key:Value
def add(self, Key, Value):
self[Key] = Value
# Main Function
Dict_Obj = My_Dict()
ans='Y'
while ans=='Y':
print(" MENU ")
print("*********************************")
print("1. Create a Dictionary”
print("2. Print the Dictionary")
print("3. Remove the item from the Dictionary")
print("4. Check if Key Exists")
print("5. Copy a Dictionary")
print("6. Deleting the Entire Dictionary")
print("7. Empty the Dictionary")
print("8. Printing the Length of the Dictionary")
print("9. Print All Key Names")
print("10. Print All Values")
print("11. Get the value of the Key")
print("12. Display both Key Names and Values")
print("13. Updating the Dictionary")
print("14. Exit”)
print(“**********************************")
ch=int(input("Enter Your Choice: "))
if ch==1:
n=int(input("Enter the no of Key / Value pair in a dictionary: "))
i=1
while i<=n:
Dict_Obj.Key = input("Enter the Key: ")
Dict_Obj.Value = input("Enter the Value: ")
Dict_Obj.add(Dict_Obj.Key,Dict_Obj.Value)
i=i+1
elif ch==2:
print("The Dictionary Object is")
print(Dict_Obj)
elif ch==3:
K=input("Enter the Key to Remove : ")
Dict_Obj.pop(K)
print("The Dictionary Object after removing the specified Key is")
print(Dict_Obj)
elif ch==4:
K=input("Enter the Key to Search : ")
if K in Dict_Obj:
print(K," is one of the Keys in the Dictionary")
else:
print(K," is not found in the Dictionary")
elif ch==5:
New_Dict=Dict_Obj.copy()
print("The New Dictionary Object is")
print(New_Dict)
elif ch==6:
del Dict_Obj
print(Dict_Obj) #This will cause an error because "Dict_Obj" no longer exists.
elif ch==7:
Dict_Obj.clear()
print(Dict_Obj)
elif ch==8:
print("The Length of the Dictionary Object is : ", len(Dict_Obj))
elif ch==9:
print("The Key Names of the Dictionary Object are")
for x in Dict_Obj:
print(x)
elif ch==10:
print("The Values of the Dictionary Object are")
for x in Dict_Obj.values():
print(x)
elif ch==11:
K=input("Enter the Key : ")
x = Dict_Obj.get(K)
print("The Corresponding value is : ", x)
elif ch==12:
print("The Key and Values of the Dictionary Object are")
for x, y in Dict_Obj.items():
print(x, y)
elif ch==13:
K=input("Enter the Key : ")
V=input("Enter the Value : ")
Dict_Obj.update({K:V})
print("The Updated Dictionary Object is")
print(Dict_Obj)
elif ch==14:
exit()
else:
print("Wrong Choice")
ans=input("Do You Want to Continue(Y/N)?")

Output:
MENU
*********************************
1. Create a Dictionary
2. Print the Dictionary
3. Remove the item from the Dictionary
4. Check if Key Exists
5. Copy a Dictionary
6. Deleting the Entire Dictionary
7. Empty the Dictionary
8. Printing the Length of the Dictionary
9. Print All Key Names
10. Print All Values
11. Get the value of the Key
12. Display both Key Names and Values
13. Updating the Dictionary
14. Exit
*********************************
Enter Your Choice: 1
Enter the no of Key / Value pair in a dictionary: 2
Enter the Key: A
Enter the Value: Amaze
Enter the Key: B
Enter the Value: Benz

MENU
*********************************
1. Create a Dictionary
2. Print the Dictionary
3. Remove the item from the Dictionary
4. Check if Key Exists
5. Copy a Dictionary
6. Deleting the Entire Dictionary
7. Empty the Dictionary
8. Printing the Length of the Dictionary
9. Print All Key Names
10. Print All Values
11. Get the value of the Key
12. Display both Key Names and Values
13. Updating the Dictionary
14. Exit
*********************************
Enter Your Choice: 2
The Dictionary Object is
{'A': 'Amaze', 'B': 'Benz'}

MENU
*********************************
1. Create a Dictionary
2. Print the Dictionary
3. Remove the item from the Dictionary
4. Check if Key Exists
5. Copy a Dictionary
6. Deleting the Entire Dictionary
7. Empty the Dictionary
8. Printing the Length of the Dictionary
9. Print All Key Names
10. Print All Values
11. Get the value of the Key
12. Display both Key Names and Values
13. Updating the Dictionary
14. Exit
*********************************
Enter Your Choice : 14

15. PYTHON PROGRAM TO IMPLEMENT THE HANGMAN GAME


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 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.

Program:

# Python program to implement the Hangman Game


#Hangman_Game1.py
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)
words.append(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 = random.choice(words)

# Read the number of turns for the user


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

print("Guess the Characters")


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 : ")

# 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:

Enter number of words: 12


Enter the 1 word : rainbow
Enter the 2 word : computer
Enter the 3 word : science
Enter the 4 word : programming
Enter the 5 word : python
Enter the 6 word : mathematics
Enter the 7 word : player
Enter the 8 word : condition
Enter the 9 word : revenue
Enter the 10 word : water
Enter the 11 word : board
Enter the 12 word : geeks

Words in the List:


['rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', 'player',
'condition', 'revenue', 'water', 'board', 'geeks']

What is your name? Akash


Good Luck ! Akash
Enter the number of turns : 12

Guess the Characters


_
_
_
_
_
Guess a Character: g
g
_
_
_
_
Guess a Character: e
g
e
e
_
_
Guess a Character: k
g
e
e
k
_
Guess a Character: s
g
e
e
k
s
You Win
The word is: geeks

Result:

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

********************

You might also like