Write a Python program to perform the following tasks according to the user's choice using a menu.

a) Display the menu with four options: 1. Reverse a String, 2. Count Vowels, 3. Remove Duplicates, 4. Exit.

b) Ask the user to enter their choice and validate it. If the choice is invalid, display an error message and ask again. 

c) If the choice is 1, ask the user to enter a string and then reverse and print it using slicing. 

d) If the choice is 2, ask the user to enter a string and then count and print the number of vowels in it using a loop.

e) If the choice is 3, ask the user to enter a string and then remove and print the duplicate characters in it using a set. 

f) If the choice is 4, exit the program with a goodbye message.

g) Use a loop to repeat the menu until the user chooses to exit.

 

Answer:

Answer by student

 

print( "Menu" )

print( "1. Reverse a String" )

print( "2. Count Vowels" )

print( "3. Remove Duplicates" )

print( "4. Exit" )

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

while choice not in [ 1 , 2 , 3 , 4 ]:

    print( "Invalid choice. Please try again." )

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

 

while choice != 4 :

    if choice == 1 :

        s = input( "Enter a string: " )

        reversed_s = s[:: -1 ]

        print( "The reversed string is:" , reversed_s)

 

    elif choice == 2 :

        s = input( "Enter a string: " )

        vowels = "aeiouAEIOU"

        count = 0

        for c in s:

            if c in vowels:

                count += 1

        print( "The number of vowels is:" , count)

 

    elif choice == 3 :

        s = input( "Enter a string: " )

        no_duplicates = "" .join(set(s))

        print( "The string without duplicates is:" , no_duplicates)

 

    print( "\nMenu" )

    print( "1. Reverse a String" )

    print( "2. Count Vowels" )

    print( "3. Remove Duplicates" )

    print( "4. Exit" )

 

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

 

    while choice not in [ 1 , 2 , 3 , 4 ]:

        print( "Invalid choice. Please try again." )

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

 

print( "Thank you for using the program. Goodbye!" )

Detailed answer by teachoo

The rest of the post is locked. Join Teachoo Black to see the full post.

 

 

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.