功能不断要求输入

时间:2015-05-11 09:34:44

标签: python-3.x infinite-loop

我写的函数绘制了squaretrianglerectangle。它要求用户输入他们想要绘制的形状。如果输入不是以下之一,则重新要求用户输入有效输入:

有效输入

square,
triangle,
rectangle,
q #function Quits.

我遇到的问题,当用户第一次输入有效输入时,该功能完美地完成并绘制该形状。然而,如果用户首先输入“无效输入”,例如(圆圈),则它要求用户重新输入“有效输入(形状)”。当他这样做时,无穷大功能一直在说:

错误消息

Unknown shape. Please try again
Enter shape to draw (q to quit):

def get_valid_shape():
''' Asking the user to enter a valid shape that the function can draw '''
    shape = input("Enter shape to draw (q to quit): ").lower()
    unvalid_names1 = shape != "triangle" and shape != "square"
    unvalid_names2 = shape != "rectangle" and shape != "q"

    while unvalid_names1 == True and unvalid_names2 == True:
        print("Unknown shape. Please try again")
        shape = input("Enter shape to draw (q to quit): ").lower()
    if shape == "q":
        print("Goodbye")
    return

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

这是因为你要求循环中的下一个值没有条件突破循环。一个简单的解决方案是:

def get_valid_shape():
    ''' Asking the user to enter a valid shape that the function can draw '''
    shape = input("Enter shape to draw (q to quit): ").lower()
    unvalid_names1 = shape != "triangle" and shape != "square"
    unvalid_names2 = shape != "rectangle" and shape != "q"
    quit = False

    while not quit and unvalid_names1 == True and unvalid_names2 == True:
        print("Unknown shape. Please try again")
        shape = input("Enter shape to draw (q to quit): ").lower()
        quit = shape == 'q'

    if shape == "q":
        print("Goodbye")
    return

get_valid_shape()

除此之外,您的代码很难理解。我冒昧地制作了另一个版本。可读性确实是意见,但它也解决了你的问题,同时使(恕我直言)更清楚你正在尝试做什么:

def get_valid_shape():
    ''' Asking the user to enter a valid shape that the function can draw '''
    valid_shapes = set(['triangle', 'square', 'rectangle'])
    user_quit = False
    requested_shape = ''

    while True:
        requested_shape = input("Enter shape to draw (q to quit): ").lower()
        if requested_shape in valid_shapes:
            break
        elif requested_shape == 'q':
            user_quit = True
            break
        else:
            print('Invalid shape')

    if not user_quit:
        print('Would now print shape')
    else:
        print('Goodbye')

get_valid_shape()