gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:02 24 4
gpt4 key购买 nike

我正在尝试将代码“排除”为 int 的字符串。 - “长度”。当我输入 except ValueError 时,我返回“请输入数字”,但添加了更多错误。我还添加了 except 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()

这是我使用此代码并在 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

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

最佳答案

原始代码的问题是,尽管 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()

关于python - 无法弄清楚为什么我收到 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54540545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com