Home > Enterprise >  My python condition checking the input from user is a negative number doesn't work
My python condition checking the input from user is a negative number doesn't work

Time:09-23

I write a code in python to ask a user to input a number and check if is it less than or equal to zero and print a sentence then quit or otherwise continue if the number is positive , also it checks if the input is a number or not

here is my code

top_of_range = input("Type a number: ")

if top_of_range.isdigit():
    top_of_range = int(top_of_range)

    if top_of_range <= 0:
        print ("please enter a nubmer greater than 0 next time.")
        quit()

else:
    print(" please type a number next time.")
    quit()

CodePudding user response:

As the help on the isdigit method descriptor says:

Return True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string.

When you pass a negative number, e.g. -12. All characters in it are not a digit. That is why you're not getting the desired behavior.

You can try something like the following:

top_of_range = input("Type a number: ")

if top_of_range.isdigit() or (top_of_range.startswith("-") and top_of_range[1:].isdigit()):
    top_of_range = int(top_of_range)

    if top_of_range <= 0:
        print ("please enter a nubmer greater than 0 next time.")
        quit()

else:
    print(" please type a number next time.")
    quit()
  • Related