How to create a Menu driven Program in Python..
Step 1. Open your python command prompt.
Step 2. Write the following code into it.
Step 3. Execute it / Test the output for various inputs.
Step 4. Now move towards the study parts of python like how to declare and define function in python.
Step 5. To study function more in detail please click on the following link
The code to write in Step 2 are as follows:
Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Ana
conda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def mainMenu():
... print("1. Adition")
... print("2. Substraction")
... print("3. Exit")
... choice=int(input("Enter u r choice"))
... if choice==1:
... add()
... elif choice==2:
File "<stdin>", line 8
elif choice==2:
^
SyntaxError: invalid syntax Note: indentation of code is too much important in python otherwise you will get error like this.
# Following is the code of main function in python.
>>> def mainMenu():
... print("1. Adition")
... print("2. Substraction")
... print("3. Exit")
... choice=int(input("Enter u r choice"))
... if choice==1:
... add() #when choice is equals to 1 we call add() function from mainMenu()
... elif choice==2:
... sub() #when choice is equals to 2 we call sub() function from mainMenu()
... elif choice==3:
... exit #when choice is equals to 3 we call exit function from mainMenu()
... else:
... print("Invalid choice, Enter valid choice1-3")
... mainMenu()
...# to come out from function press two times Enter key.
# To call mainMenu function for execution.
>>> mainMenu()
1. Adition
2. Substraction
3. Exit
Enter u r choice5 # here we are testing our code for invalid input.
Invalid choice, Enter valid choice1-3
1. Adition
2. Substraction
3. Exit
Enter u r choice3 # for valid inputs its works fine
# Definition of add() function that is actual logic of addition function how it behaves after calling.
>>> def add():
... print("Enter no1:")
... x=int(input())
... y=int(input("Enter no2:"))
... z=x+y
... print("The add is:",z)
... mainMenu()
...
>>> mainMenu() # space is not allowed while calling function
File "<stdin>", line 1
mainMenu()
^
IndentationError: unexpected indent
>>> mainMenu()
1. Adition
2. Substraction
3. Exit
Enter u r choice1 #Execution or calling of sub() function
Enter no1:
2
Enter no2:2
The add is: 4
1. Adition
2. Substraction
3. Exit
Enter u r choice4
Invalid choice, Enter valid choice1-3
1. Adition
2. Substraction
3. Exit
Enter u r choice3
# Definition of sub() function that is actual logic of substraction function how it behaves after calling.
>>> def sub():
... a=int(input("enter no1"))
... b=int(input("enter no2"))
... print("The sub is:",a-b)
... mainMenu()
...
>>> mainMenu()
1. Adition
2. Substraction
3. Exit
Enter u r choice2 #Execution or calling of sub() function
enter no120
enter no210
The sub is: 10
1. Adition
2. Substraction
3. Exit
Enter u r choice3
>>>
No comments:
Post a Comment