I am having trouble allowing users to type anything other than integers because doing so will make the programme crash and not print a piece of text I intended.
This is the programme in terminal.
I am having trouble allowing users to type anything other than integers because doing so will make the programme crash and not print a piece of text I intended.
This is the programme in terminal.
You need to use raw_input() for python 2.x
guess = raw_input()
Also the code
elif: #Need help here!
Is not syntactically valid - it needs a condition clause. But looking at your code, you can probably remove the "elif:" down to the "break", since it just replicates what's below it.
from random import randint
import sys
# Python version compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
TRIES = 10
def main():
print("Welcome to the Math Challenge!")
correct = 0
for m in rng(1, TRIES + 1):
n = randint(1, 16)
answer = m * n
guess = inp("What is {} x {}? ".format(m, n))
try:
guess = int(guess)
if guess == answer:
print("That's right")
correct += 1
else:
print("Sorry, it's actually {}".format(answer))
except ValueError:
# guess is not an int value
guess = guess.strip().lower()
if guess == "skip":
print("Skipping...")
continue
elif guess == "stop":
print("Stopping...")
break
print("You got {} correct out of {}!".format(correct, TRIES))
if __name__ == "__main__":
main()