0
def game(n):
    #teaches children how to add single digit numbers
    import random
    firstNum=random.randrange(0,10) #1st random number
    secondNum=random.randrange(0,10)#2nd random number
    equation=(firstNum + secondNum)
    print(firstNum, '+', secondNum, '=')
    answer=input('Enter answer: ')
    for i in range(n):
            if equation == answer:
                    print('Correct')
            else:
                    print('Incorrect')

输出:

>>> game(3)
7 + 2 =
Enter answer: 9
Incorrect
Incorrect
Incorrect
4

3 回答 3

3

您正在将整数与字符串进行比较。转换输入值:

if equation == int(answer):
于 2013-03-01T20:00:12.173 回答
1

你需要把这些东西

firstNum=random.randrange(0,10) #1st random number
secondNum=random.randrange(0,10)#2nd random number
equation=(firstNum + secondNum)
print(firstNum, '+', secondNum, '=')
answer=input('Enter answer: ')

进入for循环

于 2013-03-01T20:01:07.497 回答
1

向上移动for

def game(n):
    #teaches children how to add single digit numbers
    import random
    for i in range(n):
        firstNum=random.randrange(0,10) #1st random number
        secondNum=random.randrange(0,10)#2nd random number
        equation=(firstNum + secondNum)
        print(firstNum, '+', secondNum, '=')
        answer=input('Enter answer: ')

        if equation == answer:
            print('Correct')
        else:
            print('Incorrect')

此外(如果您不在 Python 3 上)您可能希望考虑替换:

input('Enter answer: ')

int(raw_input('Enter answer: '))

因为:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

因为eval可能会执行 Python 代码的随机位。你只是不知道那些孩子这些天会输入什么...... :-)

如果您使用的是 Python 3,int(input('Enter answer: '))则除了更改循环之外,您还需要...

于 2013-03-01T20:02:12.960 回答