jeudi 3 juin 2021

Trying to control the user's input to strictly a positive number only

I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number. I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:

def input_validation(prompt):
    boolChoice = True
    while boolChoice == True:
        try:
            l = input(prompt)
            x = int(l)
            boolChoice = False
        except ValueError:
            print("Not a valid input")
            if l.isalpha() == True:
                print("Your input is not a number")
            elif l.isalnum() == True:
                print ("Your input is not completely a positive number")
            elif l < 0:
                print("Your number is not positive")
            print("Try again")
    return x

def main():
    x = input_validation("Enter a positive number: ")
    print (x)
main()

My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.

Aucun commentaire:

Enregistrer un commentaire