2016-11-05 167 views
0

我基本上是在Python switch語句的嘗試。無法讓這個循環工作。每次只打印一樣的東西。python madlib while循環問題

choice = input("Do you want to play a game? (y) or (n)") 
while choice == "y": 
while True: 
    print("1. Fun story") 
    print("2. Super Fun story") 
    print("3. Kinda Fun story") 
    print("4. Awesome Fun story") 
    print("5. Some Fun story") 

    choice2 = int(input("Which template of madlib would you like to play(Enter the number of your choice")) 

if choice2 == 1: 
    noun1 = input("Enter a noun: ") 
    plural_noun = input("Enter a plural noun: ") 
    noun2 = input("Enter another noun: ") 
    print("Be kind to your {}-footed {}, or a duck may be somebody’s {}".format(noun1, plural_noun, noun2)) 


else: 
    print("Goodbye") 
+0

請修復您的縮進。 –

回答

0

使用「while True」時很容易產生問題。您可能希望以適當的退出條件結束程序,但對縮進的一些調整和中斷聲明可解決問題。之前,if條件從來沒有達到過,因爲它在第二個while循環之外,導致故事選擇在您做出選擇2後再次打印出來。這應該工作:

choice = input("Do you want to play a game? (y) or (n)") 
while choice == "y": 
    while True: 
     print("1. Fun story") 
     print("2. Super Fun story") 
     print("3. Kinda Fun story") 
     print("4. Awesome Fun story") 
     print("5. Some Fun story") 

     choice2 = int(input("Which template of madlib would you like to play (Enter the number of your choice) ")) 
     break # break out of this while loop to reach if/else 

    if choice2 == 1: 
     noun1 = input("Enter a noun: ") 
     plural_noun = input("Enter a plural noun: ") 
     noun2 = input("Enter another noun: ") 
     print("Be kind to your {}-footed {}, for a duck may be somebody’s {}".format(noun1, plural_noun, noun2)) 

    else: 
     choice = "n" # Assume user does not want to play, reassign choice to break out of first while loop (exit condition to prevent infinite loop of program) 
     print("Goodbye")