我想实现一个循环,但我不知道如何去做

时间:2016-04-05 00:57:19

标签: python loops python-3.x

好的......

print("What do you wanna do?")

input1 = input()

if input1 == "Stab this guy" or input1 == "stab this guy":
     print("You stabbed that guy and killed him.")

elif input1 == "Punch this guy" or input1 == "punch this guy":
     print("You punched him...")

我想尝试用这些复杂的输入创建一个循环,所以当你输入一个仍然很复杂但没有提到的输入时,我希望它能打印出类似于&#34的内容;抱歉没有。赶上那个"所以他们必须重复输入列表中包含的不同输入,直到他们说出正确的输入。

1 个答案:

答案 0 :(得分:2)

以你已经拥有的为基础:

print("What do you wanna do?")

input1 = input()

complex_inputs = ["stab this guy", "punch this guy"]

while input1.lower() not in complex_inputs:
    print("Sorry didn't catch that")
    print("What do you wanna do?")
    input1 = input()

if input1 == "Stab this guy" or input1 == "stab this guy":
    print("You stabbed that guy and killed him.")

elif input1 == "Punch this guy" or input1 == "punch this guy":
    print("You punched him...")

修改

要处理关键字,这也是一个想法:

print("What do you wanna do?")

input1 = input()

complex_inputs = ["stab this guy", "punch this guy"]

actions_list = [action for actions in complex_inputs for action in actions.split()]

while input1.lower() not in (actions_list or complex_inputs):
    print("Sorry didn't catch that")
    print("What do you wanna do?")
    input1 = input()

if input1.lower() in "stab this guy":
    print("You stabbed that guy and killed him.")

elif (input1.lower() in "punch this guy"):
    print("You punched him...")