-3

I'm quite new to coding. I've managed to produce this code which is a little test for children. It works fine I just need to prevent kids from entering letters or other characters when math questions are asked. Something like "please only enter numbers" should come up. I've tried a variety of functions like ValueError but with no luck. Any help will be appreciated!

import time
import random
import math
import operator as op

def test():
    number1 = random.randint(1, 10)
    number2 = random.randint(1, num1)

    ops = {
        '+': op.add,  
        '-': op.sub,
        '*': op.mul,
        }

    keys = list(ops.keys()) 
    rand_key = random.choice(keys)  
    operation = ops[rand_key]  

    correctResult = operation(number1, number2)

    print ("What is {} {} {}?".format(number1, rand_key, number2))
    userAnswer= int(input("Your answer: "))

    if userAnswer != correctResult:
        print ("Incorrect. The right answer is {}".format(correctResult))
        return False
    else:
        print("Correct!")
        return True

username=input("What is your name?")

print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))

while True:
    try:
        # try to convert the user's input to an integer
        usersClass = int(input("Which class are you in? (1,2 or 3)"))
    except ValueError:
        # oh no!, the user didn't give us something that could be converted
        # to an int!
        print("Please enter a number!")
    else:
        # Ok, we have an integer... is it 1, 2, or 3?
        if usersClass not in {1,2,3}:
            print("Please enter a number in {1,2,3}!")
        else:
            # the input was 1,2, or 3! break out of the infinite while...
            break

input("Press Enter to Start...")
start = time.time()

correctAnswers = 0
numQuestions = 10

for i in range(numQuestions):
    if test():
        correctAnswers +=1

print("{}: You got {}/{} {} correct.".format(username, correctAnswers,  numQuestions,
'question' if (correctAnswers==1) else 'questions'))

end = time.time()
etime = end - start
timeTaken = round(etime)

print ("You completed the quiz in {} seconds.".format(timeTaken))

if usersClass == 1:
    with open("class1.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersClass == 2:
    with open("class2.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersClass == 3:
    with open("class3.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
    print("Sorry, we can not save your data as the class you entered is not valid.")
Hasiba
  • 3
  • 5
  • Do you mean like [this](http://stackoverflow.com/q/23294658/3001761)? – jonrsharpe Feb 01 '15 at 18:10
  • 3
    I am curious to know what course you are taking; I've seen about 30 very similar questions in the past couple of weeks. – Hugh Bothwell Feb 01 '15 at 18:10
  • 1
    @HughBothwell GCSEs, see e.g. http://www.reddit.com/r/Python/comments/2gawvg/gcse_computing_programming_tasks_14_16_year_olds/ – jonrsharpe Feb 01 '15 at 18:13
  • GCSE assessment. Were allowed to use the internet. – Hasiba Feb 01 '15 at 18:13
  • 1
    @Hasiba you're allowed to *do research on the internet*, not ask people to write your code. – jonrsharpe Feb 01 '15 at 18:14
  • I havnt asked anyone to write my code. I just want to be told a function for something. – Hasiba Feb 01 '15 at 18:15
  • How do you consider those two things to be different? If you wanted *help*, then rather than just say *"I've tried a variety of functions like ValueError but with no luck."* you might consider **showing the code** that you have tried (produce a [minimal example](http://stackoverflow.com/help/mcve) to remove the irrelevant parts of your code) and **being specific about the problem** you're having with it (*"with no luck"* tells us nothing, how about an error traceback or example outputs?) – jonrsharpe Feb 01 '15 at 18:16

1 Answers1

1
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter an integer value!")

Look, in your code:

import operator as op

# DEFINE THE `get_int` FUNCTION HERE
#   (in global scope so other functions can call it)

def test():

then use it below:

    userAnswer = get_int("Your answer: ")   # call the function
                                            #  No ValueErrors!
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • would this come under the def test (): ? – Hasiba Feb 01 '15 at 18:22
  • @Hasiba: I would insert it right after your `import`s so it is available for the rest of your code to use. – Hugh Bothwell Feb 01 '15 at 18:29
  • The "please enter an interger value!" doesnt come up. Instead the program ends and this error message comes - Traceback (most recent call last): File "L:/computingCoursework/majorChanges4.py", line 65, in if test(): File "L:/computingCoursework/majorChanges4.py", line 29, in test user_answer= int(input("Your answer: ")) ValueError: invalid literal for int() with base 10: 'f' – Hasiba Feb 01 '15 at 18:35
  • 1
    @Hasiba: It sounds like you've cut and pasted bits of it instead of using the function as given. Is the `int(input("Your answer: "))` still inside a `try .. except ValueError` block? Because that should have caught the error, printed the message, and looped again. – Hugh Bothwell Feb 01 '15 at 18:42
  • Sorry, Im quite confused as to what you suggest I do. Ive added the code you given just bellow the int(input("Your answer: ")) and the same error message comes up. – Hasiba Feb 01 '15 at 18:58
  • 1
    you use this instead of `int(input("your answer:"))` you may need to hit the books pretty hard to pass whatever class or test this is for ... – Joran Beasley Feb 01 '15 at 19:03
  • Well this is the exam ;) – Hasiba Feb 01 '15 at 19:29