【问题标题】:NameError: name 'Key' is not defined [duplicate]NameError:名称“键”未定义[重复]
【发布时间】:2021-02-03 14:52:31
【问题描述】:

我在尝试调用 def Password() 时遇到 NameError,说“密钥”未定义。当我清楚地在 RandomKey(): 函数中定义它并返回值时......我该如何修复它?

def RandomKey():

            Main_Key = random.randint(1,25) 
            Key = Main_Key
            return Key 

def Password():
            while T:
                    pass_code = (int(input('Enter The Key: '))) 

                    if pass_code == Key and User_Menu_Input == 2:
                          time.sleep(.3) 
                          print('Key recognized... Transfering to the Encryption Menu') 
                          Timer(Time)
                          ReadFile() 
                          break
                    elif pass_code == Key and User_Menu_Input == 3:
                          time.sleep(.3) 
                          print('Key Correct... Transfering to Decryption Menu') 
                          Timer(Time) 
                          Decrypt() 
                          break

                    else:
                            print('Key Not Recognized... Try Again!')

【问题讨论】:

  • 当我明确定义在RandomKey():函数中时可以,但是如果不是全局变量,Password函数就看不到了。搜索“python 变量范围”。一种选择是将其作为参数传递给RandomKey 函数。
  • 你有一个函数RandomKey,它返回一个值,但你没有显示你在哪里调用了这个函数以及你是否存储了返回的值。

标签: python function return-value nameerror defined


【解决方案1】:

当然 Key 没有定义,因为它是其他函数中的私有变量。您可以使用 1000 种变体对其进行修复。在第一个尝试这个

Key = RandomKey()
if pass_code == Key

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 2020-06-17
    • 2016-07-06
    • 2015-10-22
    • 2016-05-12
    • 2011-11-19
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多