gpt4 book ai didi

Python:每次函数运行时如何增加数字并存储在变量中

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:36 24 4
gpt4 key购买 nike

(我是 Python 的初学者,你知道的)

我正在尝试做的事情:我想记录用户选择错误选项的次数,如果超过次数,他就会失败。

我的方法是将计数存储在函数内的变量中,并使用 if/else 语句检查是否超过了次数。

部分代码:

    choice = int(input("> "))

if choice == 1:
print("This is the wrong hall.")
increment()
elif choice == 2:
print("This is the wrong hall.")
increment()
elif choice == 3:
hall_passage()
else:
end("You failed")

COUNT = 0
def increment():
global COUNT
COUNT += 1

increment()

print(COUNT)

增量部分来自this thread并且使用全局范围读取不是一个好的做法。

我不太明白的部分是如何将计数存储在变量中,并且它会在每次函数运行时记住最后一个值。

执行此操作的最佳方法是什么?

最佳答案

也许是这样的……

class Counter():
def __init__(self):
self.counter = 0

def increment(self):
self.counter += 1

def reset(self):
self.counter = 0

def get_value(self):
return self.counter


mc = Counter()

while mc.get_value() < 3:
v = int(input('a number: '))
if v == 1:
print('You won!')
mc.counter = 3
else:
print('Wrong guess, guess again...')
if mc.counter == 2:
print('Last guess...')
mc.increment()

关于Python:每次函数运行时如何增加数字并存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com