0

I'm trying to learn about Pythons error handling and I've currently come across the Try and Except statements. I have found myself stuck with a problem. I need a User to enter an number between 0-24. If a number is not entered (i.e a string), I need to use except to print "not a number". If a number is entered and it is not between 0-24 I need to raise another error and print " not in range 0-24" Otherwise print "Valid number. I've been playing around with the code and I have ended up here.

error = False
try:
    number = int(input("\nEnter an hour: "))
except ValueError:
    print("\nNot an number.")
    error = True
while error == false:
    try:
        if number <0 or number >24:
            raise ValueError("number not between 0-24")
        else:
            print ("\nIts a number and its between 0-24")

Please Help or point me in the right direction:)

  • You do not tell us what your difficulty is. Are you getting wrong errors, wrong output, or something else? What data input gives those things? For help and a general routine that does somethin close to what you want, check the `sanitised_input` function in [this answer](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response/23294659#23294659). – Rory Daulton Jun 04 '18 at 20:16
  • The first thing you need to do is put the `input` and both checks inside the `while` loop, instead of just the second check. As it is, you never change the value of `error` inside the loop, so you can never get out of it (except by raising an exception—and if you don't do that the first time, you'll never do it). – abarnert Jun 04 '18 at 20:18
  • Meanwhile, you have a number of other errors. `false` is not the same thing as `False`, your second `try` has no `except`, etc. But you can't really fix those until you get the basic structure right first. – abarnert Jun 04 '18 at 20:18

1 Answers1

0

I would do that like this basically:

try:
    num = int(input('hour? '))
    if 0 < num < 25:
        print('All good')
        print('Hour:', num)
    else:
        print('Invalid hour')
except ValueError:
    print('Not a number')
ThePoetCoder
  • 182
  • 8