Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading