1

Currently i have this:

try:
    number = int(input('Please enter a number greater than 20'))
    if number > 20:
        print(number)
except ValueError:
    print('We encountered an error. Please try again.')

Is there a way to integrate the if statement into try? Basically so that if the input is not greater than 20 it goes to the except ValueError line. I kind of understand how the try statement works but i can only use it for really simple things, i tried reading up on it and i just got confused. Any help would be greatly appreciated.

Anya
  • 395
  • 2
  • 13

2 Answers2

2

You can change your logic around and test if number is invalid and raise ValueError()

try:
    number = int(input('Please enter a number greater than 20'))
    if number <= 20:
        raise ValueError()
    print(number)
except ValueError:
    print('We encountered an error. Please try again.')

You can put a message in the constructor Value('Value <= 20') but you aren't printing out the message in the except clause so no need.
You can wrap this in a forever loop:

while True:
    try:
        number = int(input('Please enter a number greater than 20'))
        if number <= 20:
            raise ValueError()
        print(number)
    except ValueError:
        print('We encountered an error. Please try again.')
    else:
        break
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

You may raise/throw a ValueError exception within the try block as follows:

Manually raising (throwing) an exception in Python

Community
  • 1
  • 1
Mark
  • 4,249
  • 1
  • 18
  • 27
  • Ok. Borrowing from the excellent post I cited: `raise ValueError('A very specific bad thing happened')` – Mark Mar 26 '17 at 18:53