2014-03-12 28 views
0

對不起,我只是Python的初學者所以這可能是一個很簡單的問題,但我有一個代碼,我想循環它使代碼詢問用戶是否要再次播放,而且用戶輸入「是」重新啓動代碼和「不」結束代碼之後。如果其他輸入什麼比是或否它應該問告訴他們進入yes或no,然後再次提出這樣的問題。我將如何完全做到這一點? (我不知道while和for循環,但我不知道我怎麼會以這種方式使用它們)我想有一個是在我的代碼/沒有循環,但我無法這樣做(蟒蛇3.3)

回答

1

這是一個簡單的:要執行

while True: 
    a = input("Enter yes/no to continue") 
    if a=="yes": 
     gameplay() 
     continue 
    elif a=="no": 
     break 
    else: 
     print("Enter either yes/no") 

凡遊戲功能包含代碼如果您使用Python3變化raw_inputinput

while True: 
    # your code 
    cont = raw_input("Another one? yes/no > ") 
    while cont.lower() not in ("yes","no"): 
     cont = raw_input("Another one? yes/no > ") 
    if cont == "no": 
     break 

+0

你可能想補充一點,玩遊戲時如果條件內,當==「是」。 – slider

+0

@slider:改變 –

1

我的這種方法:

# Sets to simplify if/else in determining correct answers. 
yesChoice = ['yes', 'y'] 
noChoice = ['no', 'n'] 

# Prompt the user with a message and get their input. 
# Convert their input to lowercase. 
input = raw_input("Would you like to play again? (y/N) ").lower() 

# Check if our answer is in one of two sets. 
if input in yesChoice: 
    # call method 
elif input in noChoice: 
    # exit game 
    exit 0 
else: 
    print "Invalid input.\nExiting." 
    exit 1 
1

我認爲這是你在找什麼

def playGame(): 
    # your code to play 

if __name__ == '__main__': 
    play_again = 'start_string' 
    while not play_again in ['yes', 'no']: 
     play_again = raw_input('Play Again? (type yes or no) ') 
    if play_again == 'yes': 
     playGame() 
相關問題