[英]Python arithmetic quiz task 1
I have no idea why this code is not working, as you can see I'm trying to ask the user 10 questions display their score at the end.我不知道为什么这段代码不起作用,你可以看到我试图问用户 10 个问题,最后显示他们的分数。 Everything works except that the score will always appear as a
0
or 1
at the end, even if more than 1
question was answered right.一切正常,除了分数在最后总是显示为
0
或1
,即使超过1
问题被正确回答。 Here is my code:这是我的代码:
import random
studentname=input("what is your name?:")
def question():
global operation
global number1
global number2
global studentanswer
global score
operation=random.choice(["*","-","+"])
score=0
trueanswer=0
number1=random.randrange(1,10)
number2=random.randrange(1,10)
print("what is", number1,operation,number2,"?:")
studentanswer=int(input("insert answer:"))
def checking():
global score
if operation == "*":
trueanswer = number1*number2
if studentanswer == trueanswer:
print("correct")
score=score+1
else:
print("incorrect")
score=score
elif operation == "-":
trueanswer = number1-number2
if studentanswer == trueanswer:
print("correct")
score=score+1
else:
print("incorrect")
score=score
elif operation == "+":
trueanswer = number1+number2
if studentanswer == trueanswer:
print("correct")
score = score+1
else:
print("incorrect")
score=score
def main():
for i in range (10):
question()
checking()
print("your score is", score)
main()
Each call to question()
resets score
to be 0
.每次调用
question()
都会将score
重置为0
。 Remove the score=0
line from that function, and instead initialize it in main
:从该函数中删除
score=0
行,并在main
对其进行初始化:
def main():
global score;
score = 0;
for i in range (10):
question()
checking()
print("your score is", score)
You can error check to see if your variable to count has been initialized.您可以错误检查以查看要计数的变量是否已初始化。 It's not the cleanest solution but does the job.
这不是最干净的解决方案,但可以完成工作。
def checking():
try:
global score
score = score
except:
global score
score = 0
if operation == "*":
trueanswer = number1*number2
if studentanswer == trueanswer:
print("correct")
score=score+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.