简体   繁体   English

无法弄清楚为什么我收到UnboundLocalError

[英]Cannot figure out why I am getting UnboundLocalError

I am trying to get the code to "except" a string for an int. 我正在尝试使代码“排除”一个int字符串。 - "length". - “长度”。 When I put except ValueError, I get back "Please enter a number", but more error is added. 当我输入ValueError以外的值时,我会返回“请输入数字”,但是会添加更多错误。 I also added to except UnboundLocalError, but that does not seem to work. 我还添加了UnboundLocalError除外,但这似乎行不通。 Please let me know what I'm doing wrong! 请让我知道我做错了! Here is my code: 这是我的代码:

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()

Here is what I got back from using this code and typing a string instead of an integer into length: 这是我从使用此代码并在长度中键入字符串而不是整数的结果:

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

I only expect the "Please enter a number", not the rest of the error, any help would be greatly appreciated. 我只希望“请输入一个数字”,而不是其余的错误,我们将不胜感激。 Thank you for your time! 感谢您的时间!

If you cause an error, the rest of the program will still be executed. 如果导致错误,则程序的其余部分仍将执行。 You need to repeat the input, until you get the correct input. 您需要重复输入,直到获得正确的输入。

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()

The problem with the original code is that while count != length always gets executed, no matter the try-except part. 原始代码的问题在于,无论try-except部分如何,总是执行count != length This can be avoided by only proceeding to the while loop if an ValueError or UnboundLocalError was not raised. 如果未引发ValueErrorUnboundLocalError则仅进入while循环可以避免这种情况。 By initializing c=1 before the try-except and changing it to 0 only in the try part, the program only proceeds to the while loop if exception didn't happen. 通过在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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM