我的主要问题是打印,它不工作,因为它给我的错误:
NameError; the name 'ask2' is not defined
我是Python的绝对初学者,因此我完全不知道如何使它成为全局的,或者在这些行中做些什么。你知道吗
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
if int(ask) == 1:
print("========================================================================")
ask2 = ""
while ask2 != 'exit':
ask2 = input("Please enter it in such form (XX00XXX): ")).lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
# This 'elif' is optional, it just provides a bit better feedback to the user so he knows he manually stopped
elif ask2 == 'exit':
#There are other parts of the code, but it's not necessary
else:
plate = ""
# This randomly adds two capital letters (your own code)
for i in range(2):
plate += chr(random.randint(65, 90))
print()
print(plate)
print("The program, will determine whether or not the car "+str(plate),ask2+" is travelling more than the speed limit")
您的代码当前的结构如下:
问题是当
some_condition
是False
并且else
块执行时,在if
/else
之后,当您尝试打印ask2
时,您得到的是NameError
,因为if
块从未运行,而且ask2
未定义。你知道吗你需要做:
另外,这是不相关的,但是使用
break
绝对没有错。你知道吗这个错误确实很好地说明了这一点。ask2似乎没有定义。你知道吗
你以前在什么地方定义过int吗?如果您以前没有在某个地方声明过它,您将无法使用它。你知道吗
你好像在呼吁“ask2存在!='退出'',但您没有给它赋值。它只是说ask2=“。尝试在之前给它赋值,要么定义它,要么自动赋值。你知道吗
相关问题 更多 >
编程相关推荐