Python madlib while循环问题

时间:2016-11-05 20:01:53

标签: python

我基本上尝试了Python switch语句。无法让这个循环起作用。每次只打印相同的东西。

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")

1 个答案:

答案 0 :(得分:0)

使用“while True”时很容易产生问题。您可能希望以适当的退出条件结束程序,但对缩进和break语句进行一些调整可以解决问题。以前,if条件从未到达,因为它在第二个while循环之外,导致故事选择在你做出choice2之后再次打印出来。这应该有效:

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")