python - 每次循环重复时如何将一个数字添加到另一个数字

标签 python loops clock

所以在学校,我们的老师要求我们制作一个需要密码才能授予访问权限的程序。我已经做到了这一点,但是我想通过添加一个循环计数来改进它,每次它循环时都会增加循环计数,这是我到目前为止的循环计数,但是它不起作用。

import time
b=0
a='apple'

def start():
    print("enter password")
    c=input("->  ")
    if c==a:
        grant()
    else:
        delay()

def grant():
    end

def delay():
    b=b+1
    time.sleep(b)
    start()

start()

最佳答案

你的问题在这里:

def delay():
    b=b+1
    time.sleep(b)
    start()

当您执行 b = b + 1 时,您期望文件顶部的 b 变量增加 1,对吗?

你可能还没有学过这个,但它不起作用的原因是因为一个叫做 scope 的东西。 .

要修复它,您需要将 delay 函数更改为如下所示:

def delay():
    global b
    b=b+1
    time.sleep(b)
    start()

通过查看您的代码,我认为您还没有学会如何使用 while 循环?

您在 delay 中重复调用 start 的解决方案实际上非常聪明。但是,如果我们使用 while 循环,我们可以重写您的程序,使其更清晰,更清楚地说明您要做什么:

import time

password = 'apple'

def start():
    counter = 0
    user_guess = ''

    while user_guess != password:
        print("enter password")
        user_guess = input("->  ")
        if user_guess != password:
            counter += + 1          # Same thing as doing `counter = counter + 1`
            time.sleep(counter)

    grant()

def grant():
    print "Access granted!"

start()

关于python - 每次循环重复时如何将一个数字添加到另一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19101460/

相关文章:

iphone - 闹钟iOS

heroku - Heroku 上多个测功机的时间是否同步?

python - Flask 应用程序运行 Python 2.x 而不是 3.x

python - get和dunder getitem的区别

c - 使用 printf 打印 clock_t 的正确方法是什么?

c# - 当循环变量的值是模式 LetterNumberNumber 的字符串时进行循环?

javascript - 连接来自具有相同类的 div 的字符串

python - 传感器读取覆盆子数据

python - templategs "not a valid tag library",无法加载模型

iOS 为什么我的 UIPickerview 方法循环?