Login

Back

A simple calculator

Q1. Type in and test this code:

1. """A simple calculator program
2. This program accepts 2 numbers and then carries out a calculation
3. on them"""
4. 
5. number1 = float(input("Please enter the first number >>> "))
6. number2 = float(input("Please enter the second number >>> "))
7. print(
8.     """
9.                                    Menu
10.
11. What would you like to do with the numbers?
12.
13. Press 1 to add them.
14. Press 2 to subtract the second number from the first.
15. Press 3 to divide the first number by the second.
16. Press 4 to multiply them.
17.     """
18.      )
19.
20. selection = int(input("Make your selection now >>> "))
21. 
22. if selection == 1:
23.
     result = number1 + number2
24. elif selection == 2:
25.     result = number1 - number2
26. elif selection == 3:
27.     result = number1 / number2
28. elif selection == 4:
29.     result = number1 * number2
30. else:
31.     result = "Sorry, that's not a valid selection"

32. print(result)
33. input("\n\nPress <ENTER> to quit ...")

Q2. Describe in some detail what this program does.
Q3. A comment block was used at the start of the program. Comments help people who might have to make changes in the future understand what the program does. Can you suggest other ways that code can be made easier to read and understand?
Q4. Explain what a float is, as used in lines 5 and 6.
Q5. When you divide two numbers, is the result a float or an int? Give some examples to explain your answer.
Q6. Why are lines 30 and 31 necessary? What would happen if you didn't have line lines 30 and 31 and you entered an incorrect selection? Delete lines 30 and 31 and see if your prediction was correct.
Q7. Integer division is when you divide the first number by a second and see how many times the second number will divide into the first without a remainder. In Python, the symbol is // so for example, 10 // 4 = 2 because 4 goes into 10 completely twice. 20 // 6 = 3 because 6 goes into 20 three times completely. Modify your code to include integer division.
Q8. MOD is when you divide the first number by a second and get the remainder. In Python, the symbol is % so for example, 10 % 4 = 2 because 2 is the remainder. 20 // 6 = 2 because 6 goes into 20 three times and the remainder is 2. Modify your code to include MOD.
Q9. After the program has outputted the result, also print out a comment block that explains what integer division and mod are, with examples.
Q10. Write a program that asks the user for three numbers. The user should be given the option of displaying the total, displaying the average or displaying the biggest number.

Extension
Investigate how you can round a number. For example 1 / 3 is 0.33333333 - how can you display this to 2 decimal places? 

Back