为什么得分总是返回零

时间:2016-01-08 16:53:13

标签: python

我曾尝试在Stack Overflow上查看此问题,但它并没有真正回答我的问题,我正在寻找一个我无法找到这个问题的具体原因。

我试图制作一个随机问题生成器,询问10个随机数学问题然后它应该给出10分。然而它总是将得分返回为零,我无法找出原因。请帮忙!

import random

count=0
score=0
name=input('Enter your name: ')
print(name+' Welcome to this short test. Please enter a number for       every question')

while count<10:
    numb1=random.randint(1,12)
    numb2=random.randint(1,12)
    numb1Str=str(numb1)
    numb2Str=str(numb2)
    ops=[' add ',' times ',' takeaway ']
    ops2=random.choice(ops)
    question=numb1Str+''.join(ops2)+numb2Str
    print(question)
    ans=int(input('Answer: '))
    if question==numb1+numb2 and ans== numb1+numb2:
        score=score+1
    if question==numb1-numb2 and ans== numb1-numb2:
        score=score+1
    if question==numb1*numb2 and ans== numb1*numb2:
        score=score+1
   count=count+1



print('Your score was: '+str(score))

2 个答案:

答案 0 :(得分:1)

你应该比较ans而不是问题

所以你的代码应该是这样的

import random

count=0
score=0
name=input('Enter your name: ')
print(name+' Welcome to this short test. Please enter a number for       every question')

while count< 3:
    numb1=random.randint(1,12)
    numb2=random.randint(1,12)
    numb1Str=str(numb1)
    numb2Str=str(numb2)
    ops=[' add ',' times ',' takeaway ']
    ops2=random.choice(ops)
    question=numb1Str+''.join(ops2)+numb2Str
    print(question)
    ans=int(input('Answer: '))
    if ans==numb1+numb2:
        score=score+1
    if ans==numb1-numb2:
        score=score+1
    if ans==numb1*numb2:
        score=score+1

    count=count+1



print('Your score was: '+str(score))

我不得不将循环减少到3

答案 1 :(得分:0)

您的if条件没有意义。 question是一个字符串,而不是数字。

重要的是包含在ops2变量中。它指的是您期望用户执行的操作。因此,您可以将条件代码更改为:

if ops2==" add " and ans== numb1+numb2:
    score=score+1
elif ops2==" takeaway " and ans== numb1-numb2:
    score=score+1
elif ops2==" times " and ans== numb1*numb2:
    score=score+1