1

In my program I have asked the user some basic maths questions. But I don't want them to be able to type a letter. Is there a function or method out there that would allow me to create an error message and ask them to re-enter the answer.

Answer = int(input ("What is the answer to the question?"))

if Answer == Maths:
        print ("Correct.")
        Score += 1

#function/method to prevent them from entering letters:
        print ("Please enter a valid answer.")

if Answer != Maths:
        print ("Incorrect.")

Edit - I basically don't want them to enter a letter but in a way it doesn't crash.

Joe
  • 13
  • 1
  • 4
  • You need some kind of console or curses module for this, there isn't a simple solution. Since you're just starting to program you should just be validating the input instead. – simonzack Nov 30 '15 at 20:45
  • You should take a look at regular expressions as well. They would allow you to do some simple text input validation. – bob0the0mighty Nov 30 '15 at 20:46

2 Answers2

2

Here's one way to wait for a valid integer:

def get_int(prompt):
    while True:
        try:
            answer = int(input(prompt))
            break
        except ValueError:
            print('Please enter an integer value.')
    return answer

# Ask for 10 integers
for i in range(3):
    print(get_int('Enter an integer: '))

Output:

Enter an integer: 1
1
Enter an integer: 2
2
Enter an integer: a
Please enter an integer value.
Enter an integer: b
Please enter an integer value.
Enter an integer: 3
3

If answer can't be converted to an integer, it will throw a ValueError exception and continue in the while loop. If answer is valid it will break from the loop.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

Probably not the most efficient way of doing this:

import string
user_input = ' '

while not all(char in string.digits for char in user_input):
    user_input = raw_input("Enter only numbers")
user_input = int(user_input)

string.digits is the string 0123456789.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154