Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # original approach, assume no functions or exceptions
- # has duplicated "input(...)" call, that's not good
- age = input("Enter your age: ")
- while age == "" or not age.isnumeric(): # note isnumeric()
- print("Try again")
- age = input("Enter your age: ")
- age = int(age) # this can't fail because isnumeric() above
- print(age)
- ###########
- # while True, assume no functions or exceptions
- # "input()" not duplicated
- while True:
- age = input("Enter your age: ")
- if age and age.isnumeric(): # "age" is False if empty string
- age = int(age)
- break
- print("Try again")
- print(age)
- ###########
- # use function, still no exceptions
- # just return the integer value
- def input_int(prompt):
- """Return an integer from the user."""
- while True:
- answer = input(prompt)
- if answer and answer.isnumeric():
- return int(answer)
- print("Try again")
- age = input_int("Enter your age: ")
- print(age)
- ###########
- # function plus exceptions
- # just try to convert and return int, catch exception, try again
- def input_int(prompt):
- """Return an integer from the user."""
- while True:
- try:
- return int(input(prompt))
- except ValueError:
- print("Try again")
- age = input_int("Enter your age: ")
- print(age)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement