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

时间:2019-02-05 18:09:11

标签: python python-3.x function exception

我正在尝试使代码“除” 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

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

原始代码的问题在于,count != length始终会执行try-except,而无论while部分如何。仅当未引发ValueErrorUnboundLocalError时,才进入c=1循环,可以避免这种情况。通过在try-except之前初始化0并仅在try部分将其更改为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() 循环发生。

// on clicking the update all button run all of the set forms in turn
$(".updateall").click(
    function() {
    $.post('actions/set-address.php', $('#setaddress').serialize())
    $.post('actions/set-addressnotes.php', $('#setaddressnotes').serialize())
    $.post('actions/set-parking.php', $('#setparking').serialize())
    $.post('actions/set-mailinglist.php', $('#setmailinglist').serialize())
    $.post('actions/set-boiler.php', $('#setboiler').serialize())
    $.post('actions/set-addcosts.php', $('#setaddcosts').serialize())
    $.post('actions/set-comments.php', $('#setcomments').serialize())
    $.post('actions/set-installdate.php', $('#setinstalldate').serialize())
    $.post('actions/set-engineer.php', $('#setengineer').serialize())
    // then return to customer page
    $(location).attr('href','show-all.php')
    }
 );