1

Hello this is part of my code I'm working on. I wanted to know if there was a way to detect if the input typed is an alphabet and give a response. I need to subtracted the time so I converted it to a int but if anything other than a int is type if gives me an error.

def Continue():
    time = int(input("What time is it?: "))
    if time > 12:
        print ("I'm sorry, just the hour, I don't need anymore than that.")
        Continue()
    else:
        print ("It's %d" % time + "?!")
        time = time - 1
        print ("I'm late!\nI'm sorry I have to go!\nI'm sure your leg is fine just walk it off!")
        print ("I was suppose to be there at %d" % time, "I'm an hour late!")
Sabrina
  • 35
  • 1
  • 6
  • An alphabet? You mean like the Greek alphabet? I guess you meant a letter of the alphabet, right? – nbro Jan 17 '16 at 00:08
  • Usually what I do is try to catch the exception raised by `int(...)` when you try to convert its argument to an int. You will no for sure that the input cannot be an int. Look at this question: http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number or better https://www.google.com/#q=python+check+if+input+is+integer – nbro Jan 17 '16 at 00:12

2 Answers2

0

This does what you want:

def Continue():
    try:
        time = int(input("What time is it?: "))
    except ValueError:
        print('Invalid input.')
        print('Please enter a number between 1 and 12.')
        Continue()
    if time > 12:
        print("I'm sorry, just the hour, I don't need anymore than that.")
        Continue()
    else:
        print("It's %d" % time + "?!")
        time = time - 1
        print ("I'm late!\nI'm sorry I have to go!\nI'm sure your leg is fine just walk it off!")
        print ("I was suppose to be there at %d" % time, "I'm an hour late!")

You can use a try-except statement. Python will raise an ValueError if the conversion into an integer fails. In this case, you catch the exception with except, tell the user that the input was wrong, and call your function again.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
0

One way to solve this problem is to not cast the input as an int immediately, but create an if else statement which checks if the input is a number or not. If it is a number, then you can cast the variable as an int.

Chris Mills
  • 63
  • 2
  • 7