Advertisement
Guest User

Untitled

a guest
May 27th, 2025
7
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. # original approach, assume no functions or exceptions
  2. # has duplicated "input(...)" call, that's not good
  3.  
  4. age = input("Enter your age: ")
  5. while age == "" or not age.isnumeric(): # note isnumeric()
  6. print("Try again")
  7. age = input("Enter your age: ")
  8. age = int(age) # this can't fail because isnumeric() above
  9. print(age)
  10.  
  11. ###########
  12.  
  13. # while True, assume no functions or exceptions
  14. # "input()" not duplicated
  15.  
  16. while True:
  17. age = input("Enter your age: ")
  18. if age and age.isnumeric(): # "age" is False if empty string
  19. age = int(age)
  20. break
  21. print("Try again")
  22.  
  23. print(age)
  24.  
  25. ###########
  26.  
  27. # use function, still no exceptions
  28. # just return the integer value
  29.  
  30. def input_int(prompt):
  31. """Return an integer from the user."""
  32.  
  33. while True:
  34. answer = input(prompt)
  35. if answer and answer.isnumeric():
  36. return int(answer)
  37. print("Try again")
  38.  
  39. age = input_int("Enter your age: ")
  40. print(age)
  41.  
  42. ###########
  43.  
  44. # function plus exceptions
  45. # just try to convert and return int, catch exception, try again
  46.  
  47. def input_int(prompt):
  48. """Return an integer from the user."""
  49.  
  50. while True:
  51. try:
  52. return int(input(prompt))
  53. except ValueError:
  54. print("Try again")
  55.  
  56. age = input_int("Enter your age: ")
  57. print(age)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement