繁体   English   中英

每次用户答对问题时,如何提高分数?

[英]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

你必须改变的事情:

  1. 分数必须在for loop之外,因为您每次都给它赋值 0。
  2. 当答案正确时,您必须增加分数。
  3. 您的 if-else 语句必须在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM