为什么我不能在定义中定义一个变量?

2024-04-18 13:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个倒计时,我不能定义一个变量或从外部拉一个变量。你知道吗

这是我的变量。你知道吗

go = True

这是倒计时。你知道吗

def countdown(n):
while n > 0:
    print(n)
    time.sleep(1)
    n = n - 1
    if n == 0:
        print("The storm has taken you!")
        retry = input("Would you like to play again?")
        if retry == "yes" or "Yes":

这就是问题发生的地方,因为系统说“Shadows name'go'from outer scope”和“Local variable'go'is not used”

            go = True

变量“go”用于:

while go: # Beginning script!
    print("Welcome to 'Adventures into ZORK!'")
    time.sleep(1)
    print("Entering ZORK! in three...")
    time.sleep(1)
    print("two...")
    time.sleep(1)
    print("one...")
    time.sleep(1)
    go = False 

Tags: toyoutruegoif定义timedef
2条回答

将变量传递给定义

def countdown(n,go):
  while n > 0:
    print(n)
    time.sleep(1)
    n = n - 1
    if n == 0:
      print("The storm has taken you!")
      retry = input("Would you like to play again?")
      if retry == "yes" or "Yes":

然后像这样传递变量

countdown(0,go)

编辑:

if retry == "yes" or "Yes":

可能是:

if retry.upper() == "YES" or retry.upper() == "Y":

go = True替换为

global go
go = True

该方法将在函数内部可见。或者更好,只需将global go放在函数的开头。或者更好的是,只要在函数中定义go,如果它不在其他地方使用的话。你知道吗

相关问题 更多 >