Python程序中的“NameError”

2024-09-23 22:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学校做一个程序,遇到了一个困扰我的问题,可能是因为我对Python和编程本身很在行。你知道吗

不管怎样,下面是导致问题的代码部分:

# A function used to determine a 'try' and 'except' loop for an input of a integer data type. It also adds boundaries for the integer variables in this program        
def tryAndExceptInputInt(text):
while True:
    try:
        variable = int(input(text))
        if variable == speedLimit:
            if variable > 120 or variable < 5:
                raise ValueError("Please input a suitable speed limit")
            else:
                break
        elif variable == distance:
            if variable < 1:
                raise ValueError("Please input a suitable distance")
            else:
                break
        elif variable == vehicles:
            if variable <= 0:
                raise ValueError("Please input a valid number of vehicle(s)")
            else:
                break  
        elif variable == time1 or variable == time2:
            if len(variable) != 4:
                raise ValueError("Please input a suitable entrance/leaving time")
            else:
                variable = int(variable)
                if variable >= 2400 or variable < 0000:
                    raise ValueError("Please input a suitable entrance/leaving time")
                else:
                    break
        else:
            break
    # This statement keeps looping until the user inputs the suitable data type
    except ValueError:
        print("Please input a value which is an integer\n")
    else:
        return variable

# MAIN PROGRAM


# A function made to loop 'try' and 'except' so that the user's input would be the desired data type as well as variable
speedLimit = tryAndExceptInputInt("Enter the speed limit in the monitored area (mph): ")

以下是运行这部分代码时收到的错误消息:

"In 'tryAndExceptInputInt', 'if variable == speedLimit:', NameError: name 'speedLimit' is not defined

有人能用我创建的“tryAndExceptInputInt”函数的正确版本回答我吗,谢谢;-)


Tags: theinputifintegervariableelseraiseplease
1条回答
网友
1楼 · 发布于 2024-09-23 22:19:50

摆脱speedLimit = tryAndExceptInputInt("Enter the speed limit in the monitored area (mph): ") 并替换为

speed = input("speedLimit = tryAndExceptInputInt("Speed (MPH): ")
tryAndExceptInputInt(int(speed))

并将def tryAndExceptInputInt(text):替换为

def tryAndExceptInputInt(speedLimit):

相关问题 更多 >