Difference between revisions of "CSC111 Lab 9 2015"
(→preparation) |
(→preparation) |
||
Line 11: | Line 11: | ||
<br /> | <br /> | ||
::<source lang="python"> | ::<source lang="python"> | ||
+ | # lab9_1.py | ||
+ | # Your name here | ||
+ | |||
# getInput: returns an integer larger | # getInput: returns an integer larger | ||
# than 0. Expected to be robust | # than 0. Expected to be robust | ||
def getInput(): | def getInput(): | ||
− | x = int( input( "Enter an integer | + | |
− | + | while True: | |
− | + | x = int( input( "Enter an integer greater than 0: " ) ) | |
− | + | if x <= 0: | |
+ | print( "Invalid entry. Try again!" ) | ||
+ | else: | ||
+ | return x | ||
def main(): | def main(): | ||
Line 24: | Line 30: | ||
main() | main() | ||
+ | |||
+ | |||
</source> | </source> | ||
* Test it with numbers such as -3, -10, 0, 5. Verify that the input function works well when you enter numbers. | * Test it with numbers such as -3, -10, 0, 5. Verify that the input function works well when you enter numbers. |
Revision as of 06:26, 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. Expected to be robust def getInput(): x = int( input( "Enter a positive (or null) int: " ) ) while x < 0: try: x = int( input( "Invalid number: Please try again: " ) ) except ValueError: print( "Invalid entry. Try again!" ) return x