A menu structure - Answers
Q1. Type the following code into Python and get it working:
#A simple menu structure
import math
myNumber = int(input('Please enter any whole number >>> '))
choice = input(
'''
*****************************************************
Good choice! What would you like to do with it?
Type s to find the square of the number >>>
Type root to find the square root >>>
Type fact to find the factorial of the number >>>
and then press <ENTER> .....
''')
if choice == 's':
print('The square of',myNumber,'is',myNumber*myNumber)
elif choice == 'root':
print('The square root of',myNumber,'is',math.sqrt(myNumber))
elif choice == 'fact':
print('The factorial of',myNumber,'is',math.factorial(myNumber))
else:
print('Not a valid choice. Bye')
Q2. Certain maths functions are not available in the standard Python installation. We can, however, easily extend the functionality of Python simply by importing 'modules' of functions.
Q3. In the line myNumber = int(input('Please enter any whole number >>> ')) we used int because input only reads in strings. We need to convert the string into a number if we want to do some maths on it.
Q4. We needed to use the else keyword because there are many options possible not in our menu, or we may make a mistake when selecting an option.
Q5. There are approximately 40 different functions available in the standard maths module for Python.
Q6. The error message you would get if you typed
print('The square root of',myNumber,'is',sqrt(myNumber))
instead of
print('The square root of',myNumber,'is',math.sqrt(myNumber))
is NameError: name 'sqrt' is not defined
Q7. Add an extra choice by selecting something from the math module.
Q8 - Q10:
#A simple menu structure
import math
myNumber = int(input('Please enter any whole number >>> '))
choice = input(
'''
*****************************************************
Good choice! What would you like to do with it?
Type s to find the square of the number >>>
Type root to find the square root >>>
Type fact to find the factorial of the number >>>
and then press <ENTER> .....
''')
if choice == 's':
print('The square of',myNumber,'is',myNumber*myNumber)
elif choice == 'root':
print('The square root of',myNumber,'is',round(math.sqrt(myNumber),2))
elif choice == 'fact':
print('The factorial of',myNumber,'is',math.factorial(myNumber))
else:
print('Not a valid choice. Bye')
print('Pi is',round(math.pi,2))
print('The data type of', choice,'is',type(choice))