When input goes wrong
Answers are for parents and teachers.
1
Fill the table: what does int() do with "12", "twelve", "3.0" and "-5"?
"12" gives 12; "twelve" gives a ValueError; "3.0" gives a ValueError; "-5" gives -5.
2
A friend writes except: and the message Error. Improve both.
Write except ValueError: and a message that tells what to do, such as Please type digits only.
3
What does the program show for the typed value 0, and for 5?
Python
1try: 2 num = int(input("Divide 10 by: ")) 3 print(10 / num) 4except ValueError: 5 print("Please type digits only.") 6except ZeroDivisionError: 7 print("You cannot divide by zero.")
For 0: You cannot divide by zero. For 5: 2.0, because 10 / 5 = 2.0.
4
In the retry loop the user types x and then 9. What does the screen show after the questions?
Python
1while True: 2 try: 3 num = int(input("Enter a number: ")) 4 print("You entered:", num) 5 break 6 except ValueError: 7 print("Numbers only, try again.")
Numbers only, try again. and then You entered: 9.
5
Why do tasks in this course use an invented number of books or pencils and never your real age or details?
Practice programs and games should never receive personal details. Invented values teach the same idea and keep your information private.