简单python循环

2024-04-25 08:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

print("Hi im a PC and my name is Micro, What's your name?")
name = raw_input("")
print("Hi " + name + " how are you, are you good?")
answer = (raw_input(""))
if answer == "yes":
           print("That's good to hear!")
elif answer == "no":
           print("Oh well")
while answer != ("yes","no")
           print("Sorry, you didnt answer the question properly, Please answer with a yes or no.")
print"I'm going to sleep for 5 seconds and then i'll be back."
import time
time.sleep(5)
print"I'm back!"

需要为yes或no位创建一个循环,有人知道怎么做吗? 谢谢你的帮助!你知道吗


Tags: andtonoanswernameyouinputraw
2条回答

现在是完全不同的事情:

options = {'intro':"Hi, I'm a PC and my name is Micro, What's your name? > ",
           'ask':  "Hi %s how are you, are you good? > ",
           'yes':  "That's good to hear!",
           'no':   "Oh well",
           'error':"Sorry, you didnt answer the question properly\n",
           'hint': "Please answer with yes/no"}

name = raw_input(options['intro'])

while True:
    try:
        answer = raw_input(options['ask'] % name)
        print options[answer.lower()]
        break
    except KeyError:
        print options['error'], options['hint']    

正如您所说的您是Python的noob,我想在这里介绍一些新的东西来补充您可能会发现有用的另一个答案。你知道吗

使用while True:,当您想停止循环时,使用break。你知道吗

这将是您的代码,而不是:

...
while True:
    answer = (raw_input(""))
    if answer == "yes":
        print("That's good to hear!")
        break
    elif answer == "no":    
        print("Oh well")
        break
    else:
        print("Sorry, you didnt answer the question properly, Please answer with a yes or no.")
...

相关问题 更多 >