整数,输入,打印

时间:2015-11-18 02:41:19

标签: python python-3.x

我遇到的主要问题是印刷,它不起作用,因为它给我错误:

  

NameError;名字' ask2'未定义

我在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")

2 个答案:

答案 0 :(得分:0)

您的代码目前的结构如下:

if some_condition:
    ask2 = ''
else:
    ...
print(ask2)

问题是当some_conditionFalseelse块执行时,在if / else后尝试打印时{{1} }},您正在获取ask2,因为NameError块从未运行且if未定义。

你需要这样做:

ask2

此外,无关,但使用ask2 = '' if some_condition: ... else: ... print(ask2) 绝对没有错。

答案 1 :(得分:-1)

错误确实说得相当好。 ask2似乎没有被定义。

你之前在某处定义过int吗?如果你以前没有在某个地方宣布它,你将无法使用它。

if int(ask) == 1:
    print("========================================================================")
    ask2 = ""
    while ask2 != 'exit':

好像你正在调用'theask2 being!='exit'',但你没有给它分配任何值。它只是说ask2 =“”。尝试在之前为其分配一些值,方法是定义它或者自动分配一个值。

相关问题