[英]How do I increase the score every time the user gets a question correct?
我正在制作一个非常简单的数学问答游戏,每次用户答对问题时,我都想提高分数。 但是当我运行代码时,分数保持在 1 并且没有增加。
import random
for x in range (0,10):
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
ansstring = "What is {0} + {1}:".format(num_1,num_2)
answer = int(input(ansstring))
score = 0
if answer == (num_1 + num_2):
print("CORRECT!")
score = score + 1
print ("Score:",score)
else:
print("INCORRECT! Correct answer is", (num_1 + num_2))
print ("Your score was", score,"/10")
您需要将所有游戏内容放在for loop
中,并将变量score
放在for
循环之外。
原因是每次for loop
迭代时,您都在重置变量。
出于同样的原因,您需要检查每个总和,因此您需要将if
语句放在for loop
中。
代码:
import random
score = 0
for x in range (0,10):
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
ansstring = "What is {0} + {1}:".format(num_1,num_2) + " "
answer = int(input(ansstring))
if answer == (num_1 + num_2):
print("CORRECT!")
score = score + 1
print ("Score:",score)
else:
print("INCORRECT! Correct answer is", (num_1 + num_2))
print ("Your score was", score,"/10")
希望这可以帮助!
将变量score
放在循环之外,因此不会在每次迭代时将其初始化回0
。
获取for-loop
内的if-else
条件以检查每次迭代的当前分数:
import random
score = 0 # score var should be outside the loop
for x in range (0,10):
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
ansstring = "What is {0} + {1}:".format(num_1,num_2)
answer = int(input(ansstring))
if answer == (num_1 + num_2):
print("CORRECT!")
score = score + 1
print ("Score:", score)
else:
print("INCORRECT! Correct answer is", (num_1 + num_2))
print ("Your score was", score,"/10")
很简单,从 for 循环中取出score
:
import random
score = 0
for x in range (0,10):
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
ansstring = "What is {0} + {1}:".format(num_1,num_2)
answer = int(input(ansstring))
if answer == (num_1 + num_2):
print("CORRECT!")
score += 1
print ("Score:",score)
else:
print("INCORRECT! Correct answer is", (num_1 + num_2))
print ("Your score was", score,"/10")
您的不起作用的原因是,在每次迭代期间,您一遍又一遍地设置score = 0
。
你必须改变的事情:
for loop
之外,因为您每次都给它赋值 0。for loop
内以下是代码的外观:
import random
score = 0
for x in range (0,10):
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
ansstring = "What is {0} + {1}:".format(num_1,num_2)
answer = int(input(ansstring))
if answer == (num_1 + num_2):
print("CORRECT!")
score = score + 1
print ("Score:",score)
else:
print("INCORRECT! Correct answer is", (num_1 + num_2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.