【发布时间】: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