无法生成我的print语句n次并让我的if语句在python中工作

时间:2013-03-01 19:58:46

标签: python for-loop

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

3 个答案:

答案 0 :(得分:3)

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

if equation == int(answer):

答案 1 :(得分: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循环

答案 2 :(得分: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: ')) ...