Difference between revisions of "CSC111 Lab 9 2015"
(→preparation) |
(→preparation) |
||
Line 42: | Line 42: | ||
<br /> | <br /> | ||
::<source lang="python" highlight="9-14"> | ::<source lang="python" highlight="9-14"> | ||
− | # | + | # getInput: returns an integer larger |
# than 0. Catches Value errors | # than 0. Catches Value errors | ||
− | def | + | def getInput(): |
# repeat forever... | # repeat forever... | ||
Line 61: | Line 61: | ||
print( "You entered a negative number. Try again!" ) | print( "You entered a negative number. Try again!" ) | ||
else: | else: | ||
+ | # finally, we can return x as it is an int that is >0 | ||
return x | return x | ||
Revision as of 07:32, 29 March 2015
--D. Thiebaut (talk) 07:14, 29 March 2015 (EDT)
Exceptions
preparation
- Create a new program called lab9_1.py, and copy this code to the new Idle window.
# lab9_1.py # Your name here # getInput: returns an integer larger # than 0. Expected to be robust def getInput(): while True: x = int( input( "Enter an integer greater than 0: " ) ) if x <= 0: print( "Invalid entry. Try again!" ) else: return x def main(): num = getInput() print( "You have entered", num ) main()
- Test it with numbers such as -3, -10, 0, 5. Verify that the input function works well when you enter numbers.
- Test your program again, and this time enter expressions such as "6.3", or "hello" (without the quotes).
- Make a note of the Error reported by Python:
- Modify your function and add code that will catch the exception:
# getInput: returns an integer larger # than 0. Catches Value errors def getInput(): # repeat forever... while True: # try to get an int try: x = int( input( "Enter an integer greater than 0: " ) ) except ValueError: # the user must have entered something other than an int print( "Invalid entry. Not an integer. Try again!" ) continue # No errors caught. See if the number is negative if x <= 0: print( "You entered a negative number. Try again!" ) else: # finally, we can return x as it is an int that is >0 return x