Home > Blockchain >  Is there a possibility to add "less than" exception to this piece of code in Python?
Is there a possibility to add "less than" exception to this piece of code in Python?

Time:10-22

I'm quite new to coding and I'm doing this task that requires the user to input an integer to the code. The function should keep on asking the user to input an integer and stop asking when the user inputs an integer bigger than 1. Now the code works, but it accepts all the integers.


while True:
        try:
            number = int(input(number_rnd))
        except ValueError:
            print(not_a_number)
        else:
            return number

CodePudding user response:

You can do something like this:

def getPositiveInteger():
    while True:
        try:
            number = int(input("enter an integer bigger than 1: "))
            assert number > 1
            return number
        except ValueError:
            print("not an integer")
        except AssertionError:
            print("not an integer bigger than 1")

number = getPositiveInteger()
print("you have entered", number)

CodePudding user response:

while True:
    # the input return value is a string
    number = input("Enter a number")
    # check that the string is a valid number
    if not number.isnumeric():
        print(ERROR_STATEMENT)
    else:
        if int(number) > 1:
            print(SUCCESS_STATEMENT)
            break
        else:
            print(NOT_BIGGER_THAN_ONE_STATEMENT)
 

Pretty simple way to do it, of course you must define ERROR_STATEMENT, SUCCESS_STATEMENT and NOT_BIGGER_THAN_ONE_STATEMENT to run this code as it is, I am using them as place-holder.

  • Related