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

Question:

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()
Asked By: AHumaidi9

||

Answers:

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()
Answered By: Omer Khalil
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.