0

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()
2
  • Why do you think that it doesn't work? Commented Sep 22, 2022 at 22:14
  • I don't think - counts as a digit. Commented Sep 22, 2022 at 22:17

1 Answer 1

1

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

Based on Mark's comment, if we employ the EAFP principle it will look something like this:

top_of_range = input("Type a number: ")

try:
    top_of_range = int(top_of_range)

    if top_of_range <= 0:
        print ("please enter a nubmer greater than 0 next time.")
        quit()
except ValueError:
    print(" please type a number next time.")
    quit()
Sign up to request clarification or add additional context in comments.

1 Comment

In Python it's considered better to just do the conversion and detect an error with try/except rather than qualify the input first. It's called the EAFP principle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.