如何在 python 中形成条纹(计算是否正确然后将 1 添加到变量)

How to make a streaks in python (count if something is right then add 1 to a variable)

我正在用pythong测试东西(我真的很平庸,还在学习);我做了一个游戏,我想数一数wins/guesses。我已经尝试了一些定义函数的方法,但是必须在函数之前调用变量,以便它重置;再说一次,我真的很糟糕,所以如果有人能给我写一封 example/explanation,我将不胜感激。 PS:我是堆栈溢出的新手,如果您没有使用特定格式或其他东西,我很抱歉:D

如果您想计算获胜次数,一个很好的方法是使用 for 循环。这些是重复一定次数的代码段。您可以将您的主要游戏结构放在一个函数中,该函数在循环的每次迭代中完成。因此,假设您的实际游戏是一个名为 main_game():

的函数
def main_game():
    # all your game code can go here
    if won: # you can change this to reflect your own code
        return True # the return statement passes a value back to the place that called it
    else:
        return False

旁注:如果您不理解 returndef 等基本 python 结构,请查看 python docs.

然后我们可以循环这个函数。 range() 这里有一个参数,表示应该执行的次数,因此在本例中为 10 次。

wins = 0
for i in range(10): # this a for loop. "i" represents the iteration of the loop.
    result = main_game() # this calls the function
    if result == True: # in other words, if they've scored
         wins = wins+1 # add one to the wins total

表达式 result = main_game() 基本上将任何 main_game() returns 分配给名为 result 的变量。这就是我们在 main_game 函数中使用 return True 而不是 print(True) 的原因,因为它将那个值发送回 result.

然后它会检查用户是否赢了,如果是,则在迭代之前增加他们的赢奖总数。请注意,没有 elifelse 语句,因为如果 result 不是 True,我们就不必对获胜总数做任何事情。

这是关于如何使用根据游戏条件上升的计数器的基本框架,需要一些扩展,但应该给你一些提示。