簡體   English   中英

python 2.7.3 while循環

[英]python 2.7.3 while loop

我是python的新手。 我需要反復循環,要求用戶選擇一個選項,然后運行命令並重復直到用戶選擇退出。 如果用戶選擇任何其他選項,程序必須一直要求他們選擇一個值,直到他們選擇一個正確的值。 到目前為止,我的計划進展不順利。 如果可能的話,我想保持原狀,如果,elif條件。 有人能夠提供幫助嗎? 非常感謝!

print """
How do you feel today?
1 = happy
2 = average
3 = sad
0 = exit program
"""

option = input("Please select one of the above options: ")
while option > 0 or option <=3:
    if option > 3:
        print "Please try again"
    elif option == 1:
        print "happy"
    elif option == 2:
        print "average"
    elif option == 3:
        print "sad"
    else:
        print "done"

break命令將為您退出循環 - 但是,就開始控制流而言,它也不是真正推薦的。 但請注意,用戶永遠不能輸入新值,因此您將陷入無限循環。

也許嘗試這個:

running = True

while running:
    option = input("Please select one of the above options: ")
    if option > 3:
        print "Please try again"
    elif option == 1:
        print "happy"
    elif option == 2:
        print "average"
    elif option == 3:
        print "sad"
    else:
        print "done"
        running = False

這是我將如何修改它以實現預期的結果。你在哪里關閉但if和else不應該在循環內:)。

print """
How do you feel today?
1 = happy
2 = average
3 = sad
0 = exit program
"""

option = input("Please select one of the above options: ")
while option >3:
    print "Please try again"
    option = input("Please select one of the above options: ")

if option == 1:
    print "happy"
elif option == 2:
    print "average"
elif option == 3:
    print "sad"
else:
    print "done"

請注意,您可以隨時使用break來停止循環

謝謝Ben

import sys
option = int(input("Please select one of the above options: "))
while not option in (0, 1, 2, 3):
    option = int(input("Please select one of the above options: ")
    if option == 0: sys.exit()
    else: print "Please try again"
if option == 1:
        print "happy"
elif option == 2:
        print "average"
elif option == 3:
        print "sad"

邏輯是如果選項不是0,1,2或3,程序會不斷要求輸入。 如果它在該范圍內,則循環結束並打印結果。 如果輸入為0,則程序使用sys.exit()結束。

或者,您可以使用字典創建更簡單,更短的程序:

import sys
userOptions = {1: 'happy', 2: 'average', 3: 'sad'}
option = int(input("Please select one of the above options: "))
while not option in (0, 1, 2, 3):
    option = int(input("Please select one of the above options: ")
    if option == 0: sys.exit()
    else: print "Please try again"
print userOptions[option]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM