【问题标题】:Cannot figure out why I am getting UnboundLocalError无法弄清楚为什么我会收到 UnboundLocalError
【发布时间】:2019-02-05 18:09:10
【问题描述】:

我试图让代码“排除”一个 int 的字符串。 - “长度”。当我输入除 ValueError 之外的内容时,我返回“请输入一个数字”,但添加了更多错误。我还添加了除了 UnboundLocalError,但这似乎不起作用。请让我知道我做错了什么!这是我的代码:

import random
import string


def RPG():
    try:
        RPG = ""
        count = 0
        length = int(
            input("How many characters would you like in your password? "))
    except (ValueError, UnboundLocalError):
        print("Please enter a number.")
    while count != length:
        upper = [random.choice(string.ascii_uppercase)]
        lower = [random.choice(string.ascii_lowercase)]
        num = [random.choice(string.digits)]
        symbol = [random.choice(string.punctuation)]
        everything = upper + lower + num + symbol
        RPG += random.choice(everything)
        count += 1
        continue
    if count == length:
        print(RPG)
# could also use string.printable for digits, letters, punct., and whitespace.


RPG()

这是我使用此代码并在长度中输入字符串而不是整数后得到的结果:

How many characters would you like in your password? j
Please enter a number.
Traceback (most recent call last):
  File "c:\Users\jkelly\Desktop\python\code.py", line 28, in <module>
    pwd()
  File "c:\Users\jkelly\Desktop\python\code.py", line 14, in pwd
    while count != length:
UnboundLocalError: local variable 'length' referenced before assignment

我只希望“请输入一个数字”,而不是其余的错误,任何帮助将不胜感激。感谢您的宝贵时间!

【问题讨论】:

  • 如果您的代码的第一部分处理和异常,那么length 永远不会被分配给。
  • 那我该怎么办?

标签: python python-3.x function exception


【解决方案1】:

原始代码的问题在于count != length 总是被执行,而不管try-except 部分。如果没有引发ValueErrorUnboundLocalError,则仅继续执行while 循环可以避免这种情况。通过在try-except 之前初始化c=1 并仅在try 部分将其更改为0,如果没有发生异常,程序只会继续进行while 循环。

import random
import string


def RPG():
    c=0
    try:
        RPG = ""
        count = 0
        length = int(
            input("How many characters would you like in your password? "))
    except (ValueError, UnboundLocalError):
        print("Please enter a number.")
        c=1
    if c==0:
        while count != length:
            upper = [random.choice(string.ascii_uppercase)]
            lower = [random.choice(string.ascii_lowercase)]
            num = [random.choice(string.digits)]
            symbol = [random.choice(string.punctuation)]
            everything = upper + lower + num + symbol
            RPG += random.choice(everything)
            count += 1
            continue
        if count == length:
            print(RPG)
# could also use string.printable for digits, letters, punct., and whitespace.


RPG()

【讨论】:

    【解决方案2】:

    如果您导致错误,程序的其余部分仍将执行。您需要重复输入,直到获得正确的输入。

    import random
    import string
    
    
    def RPG():
        while True:
            try:
                RPG = ""
                count = 0
                length = int(
                    input("How many characters would you like in your password? "))
                break
            except (ValueError, UnboundLocalError):
                print("Please enter a number.")
        while count != length:
            upper = [random.choice(string.ascii_uppercase)]
            lower = [random.choice(string.ascii_lowercase)]
            num = [random.choice(string.digits)]
            symbol = [random.choice(string.punctuation)]
            everything = upper + lower + num + symbol
            RPG += random.choice(everything)
            count += 1
            continue
        if count == length:
            print(RPG)
    # could also use string.printable for digits, letters, punct., and whitespace.
    
    
    RPG()
    

    【讨论】:

    • 我已经测试过了。当您输入一串字母时,它会打印“请输入一个数字”。并重复输入请求。你确定你已经运行了我的代码吗?
    • 你说得对,我尝试粘贴时做错了;不幸的是,我不能赞成或反对您的答案,因为我几乎没有声誉,但我希望人们看到此评论以知道您的代码实际上是正确的。如果用户输入字符串,这也是一个循环,所以奖励!感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多