2012-01-07 62 views
0
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位創建一個循環,任何人都知道如何? 感謝您的幫助!簡單的python循環錯誤

+1

它是一個新東西的奧奇。但我可以建議你看看這些系列的視頻:http://www.youtube.com/watch?v=tKTZoB2Vjuk&ob=av3e或類似的東西?這將花費你幾個小時,但它將是完全值得的。你會對事物的工作有一些基本的瞭解:) – 2012-01-07 09:44:36

回答

1

使用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.") 
... 
+0

對不起,我真的很新,雖然我聽說過這兩個我還沒有學到它們。你願意解釋還是舉一個例子 – user1135707 2012-01-07 09:27:07

+0

哦,我明白了,謝謝! – user1135707 2012-01-07 09:29:34

1

現在一個完全不同的事情:

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中的小白,我想在這裏幾個新引進事情來補充你可能會發現有用的其他答案。