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

标签 python python-3.x

(我是 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/

相关文章:

python - 如何将 numpy 矩阵转换为 OpenCV 图像 [python]

来自索引数组的python numpy数组

Python 3 绑定(bind)方法订阅

Python终端输出宽度

Python 没有名为 X 的模块 - 绝对导入

Python 如何在导入包时模拟 ImportError

python - 我无法在 python shell 中导入和使用 numpy

python - Raspberry PI 2 GPIO.setup() 退出且没有任何错误

python - Python阴影转换优化

python - Numpy:加载多个 CSV 文件作为字典