传入字符串时出现 UnboundLocalError

我是 python 新手,我想练习一下,try/except但我卡住了:


def monitor():

    try:

        brightness = int(input("brightness:"))

    except ValueError:

        print("please pass in a number")


    if brightness < -1 or brightness > 101:

        print("invaild",brightness)

    else:

        print("invalid",brightness)


while True:

    monitor()

我希望输入字符串时不会出现错误,但它给了我:


UnboundLocalError


互换的青春
浏览 157回答 3
3回答

眼眸繁星

检查此代码片段try:&nbsp; &nbsp; brightness = int(input("brightness:"))except ValueError:&nbsp; &nbsp; print("please pass in a number")print(brightness)print(brightness)如果在被要求输入时输入“有点暗” ,应该输出什么?因为输入不是整数,int()这种情况下会抛出异常,所以局部变量brightness不会被初始化。您可以在except子句中将其初始化为某个默认值,但在这种情况下,如果输入不正确,您可能不应该对 brightess 值做任何事情。你可以在 try...except 中移动逻辑处理brightness,那么它只有在输入可以被解析的情况下才会执行。def monitor():&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; brightness = int(input("brightness:"))&nbsp; &nbsp; &nbsp; &nbsp; if brightness < -1 or brightness > 101:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invaild",brightness)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invalid",brightness)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("please pass in a number")

largeQ

改用它(这可以解决您提出的问题):def monitor():&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; brightness = int(input("brightness:"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if brightness < -1 or brightness > 101:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invaild",brightness)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if brightness < -1 or brightness > 101:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invaild",brightness)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invalid",brightness)&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("please pass in a number")&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("invalid",brightness)monitor()您的代码也有逻辑错误,因为无论输入(亮度),输出总是print("invalid",brightness)如果您不知道,请告诉您,以防万一。您的代码输出:我的输出:

RISEBY

请检查这个,这里我们强制用户只输入整数值。&nbsp; &nbsp; brightness=-2while (brightness < -1 or brightness > 101):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; brightness = int(input("brightness:"))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("please pass in a number")if brightness < -1 or brightness > 101:&nbsp; &nbsp;print("invaild",brightness)else:&nbsp; &nbsp;print("Valid",brightness)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python