是一个While True或If语句,最好在移动到下一个函数之前执行一个函数

时间:2016-12-02 04:46:31

标签: python python-2.7

我被困在一个简单的问题上。我试图要求用户从列表中选择所需的功能。该输入的用户字符串将调用所选择的函数,直到它完成运行。 (这是照明序列)。在此序列结束后,我想询问用户他或她是否希望选择其他功能。如果是这样,继续。如果没有,请退出代码。

我无法判断一段时间是真的还是if语句是最好的。

这是我的代码:

# random functions
def rainbow():
    print 'rainbow'
def clover():
    print 'clover'
def foo():
    print 'eggs'

if __name__ == '__main__':
    # here are some random initializations
    print 'ctr-c to quit'
    user_input = input("choose from the following: ")

    if user_input == 'rainbow':
        print 'generating'
        rainbow()
        rainbow()
        rainbow()
        user_input = input('choose another')
    if user_input == 'foo':
        clover()
        clover()

2 个答案:

答案 0 :(得分:2)

I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:

while True:
    user_input = input('...')
    if "good result"
        break
    else:
        continue

答案 1 :(得分:1)

while True:
    user_input = input("choose from the following: ")
    if user_input == "condition a":
        do something
    elif user_input == "condition b":
        do something..
    elif any(user_input == keyword for keyword in ["q", "quit"]):
        # when meet any quit keyword, use break to terminate the loop
        break
    else:
        # when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
        continue

while True can meet your requirement. you can use if-elif-else clauses to do different works.