0

I want the user to give 2 numbers between 1 and 100 whereas both inputs need to be integers only. Then the program will count from the lower number to the higher number. What's the solution for handling user inputs that are not digit values (e.g. 'two' instead of 2) by converting the string into an integer equivalent?

while True:
    try:
        num_1 = int(input('Please enter a number between 1-100:> '))
        num_2 = int(input('Please enter a number between 1-100:> '))
  
    except ValueError:
        print('Sorry, only integers between 1-100. Please try again')
        continue
    
    else:
        break
   
while num_1 < 0 or num_2 < 0 or num_1 > 100 or num_2 > 100 or num_1 == num_2:
    print('Numbers must be different values between 1 and 100, try again')
    num_1 = int(input('Please enter a number between 1-100:> '))
    num_2 = int(input('Please enter a number between 1-100:> '))
    
if num_1 < num_2:
    for i in range(num_1,num_2+1):
        print(i,end=' ')
else:
    for i in range(num_2,num_1+1):
        print(i,end=' ')
        
Bo Louie
  • 31
  • 1
  • 10
  • You need to handle the exception. Take a look at the Python documentation for the try/except keywords. You may also find https://stackoverflow.com/questions/730764/how-to-properly-ignore-exceptions helpful. – Dave Costa Sep 30 '20 at 19:25
  • Yes of course it's possible. You could catch the ValueError and then re-prompt the user. You could also check if the input is a spelled-out number like `"two"` and return `2` instead, before converting it to an int. There are plenty of ways people handle bad input, it's your choice what you want to do. How do you _want_ it to behave? – Random Davis Sep 30 '20 at 19:25

0 Answers0