重启Python程序和If语句 - 不复杂

时间:2016-08-26 20:26:28

标签: python

Question1 = input("We will start off simple, what is your name?")
if len(Question1) > 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers.
    Question2 =  input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1)
    if Question2.lower() in m: #checks if the user input is in the variable m
        print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
    elif Question2.lower() in w: # checks if the user input is in the variable w
        print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
    else: #if neither of the statements are true (incorrect answer)
        print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")
else:
    print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name)
Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?")

为了得到正确的答案,我会首先告诉你运行时会发生什么: 有几种情况,但我会引导你完成2.当我运行程序时,我首先被问到我的名字是什么,我可以在这里输入任何字母,然后它问我是否喜欢男人或女人,很奇怪我知道但是这是我正在研究的一个项目,如果我说'男'或'女'这个程序运行得很好,但是如果我要输入说''狗'它会遵循else语句print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")但是然后它继续代码并转到上面显示的最后一行“现在我知道你的名字和性别吸引你......等等等等”。 我要做的是让你重新启动脚本,如果你输入的不是“男人”或“女人”。 我被告知可以使用while语句,但是我需要解释为什么以及如何...在某种意义上我是Python的新手。

2 个答案:

答案 0 :(得分:0)

那是什么循环。

while True:
    # your input and all that here
    if answer == "man" or answer == "woman":
        # do what you want if the answer is correct
        break # this is important, as it breaks the infinite `while True` loop
    else:
        # do whatever you want to do here :)
        continue

答案 1 :(得分:0)

如果您希望脚本无限重复,您可以简单地将所有内容包装在while循环中,如下所示:

while True:
    # Do yo your logic here.
    # Break out when a condition is met.

如果你想更精明地使用它,你可以使用一种方法,并让方法一遍又一遍地调用,直到它完成。

def ask_questions():
    # Do your logic here
    if INPUT_NOT_VALID:
        ask_questions()
    else:
        # Continue on.

另外,在这个网站上搜索你的文字,因为我已经看到所有涉及这个编程场景的五六个问题,这意味着它必须是编程类的一个常见问题(我假设你在一个) 。如果是这种情况与同学讨论,并试图互相激励,找到解决方案,而不是只是在网上发帖回答。