Advertisement
gruntfutuk

getnumber

Jun 13th, 2019
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. from random import randint
  2.  
  3. def get_num(prompt:str, low:int=0, high:int=100) -> int:
  4.     'function to display prompt for user to input an integer'
  5.     'validate input to be an integer within the range'
  6.     '<low> to <high> and reprompting if not valid'
  7.     'returns an integer'
  8.     while True:  # keep prompting until valid input given
  9.         try:
  10.             num = int(input(prompt))  # try to convert input to integer
  11.             if not (low <= num <= high):  # is integer in range required#
  12.                 raise ValueError  # if not, raise an exception
  13.             return num  # got here, so we can return valid integer
  14.         except ValueError:  # not integer or not in valid range
  15.             print(f'Whole number required between {low} and {high}.')
  16.             print('Please try again.')
  17.            
  18. def testing():
  19.     tests = [(randint(1, 50), randint(51, 100)) for _ in range(10)]
  20.     nums = []
  21.     for low, high in tests:
  22.         nums.append(get_num(f'Enter whole number between {low} and {high}: ', low, high))
  23.     print(f'Numbers:', *nums, sep='\n')
  24.    
  25.  
  26. testing()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement