在Python中控制循环

时间:2017-04-24 23:59:10

标签: python

我目前正在处理此代码:

import time
import webbrowser

while True:
    user_inputq3 = raw_input("Which model of phone is it? ")  
    import csv  
    words=user_inputq3.split(" ")  
    reader=csv.reader(open("task3worksheet.csv"))  
    problemlist=[row for row in reader]  
    for x in range(0,len(words)):  
        for y in range(0,len(problemlist)-1,2):  
            if(words[x].lower() in problemlist[y]):  
                print(problemlist[y+1][0])  
                break  
            elif user_inputq3 == "exit":  
                print("The programme will now shut down.")  
                time.sleep(5)  
                exit(0)  
                break  
            else:  
                print("This troubleshooting programme will only support iPhone 3-7.")  
                print("Make sure you type in iphone then the model of iPhone. (e.g iphone4)")  
                print("If you do not have these versions of the iPhone, please type in exit when prompted with the question again.")  
                break  

" task3worksheet"是一个excel工作表,其中包含关键字和响应。例如,当" iPhone4"键入,"下一个问题"应该出现。但是,当我输入" iPhone4"时,它会说下一个问题并再次回到问题。如何使它不会再次回到问题,我想要它,以便当输入有效输入时当前循环结束,所以我可以转到其他代码。

1 个答案:

答案 0 :(得分:0)

我添加了一个变量,告诉我是否已经回答了问题,如果我这样做,我就打破了外循环。 评论中建议的修改版本:

import time
import webbrowser

answered = False
while not answered:
    user_inputq3 = raw_input("Which model of phone is it? ")  
    import csv  
    words=user_inputq3.split(" ")  
    reader=csv.reader(open("task3worksheet.csv"))  
    problemlist=[row for row in reader]
    for x in range(0,len(words)):
        if answered:
            break
        for y in range(0,len(problemlist)-1,2):  
            if(words[x].lower() in problemlist[y]):  
                print(problemlist[y+1][0])  
                answered = True
                break
            elif user_inputq3 == "exit":  
                print("The programme will now shut down.")  
                time.sleep(5)  
                exit(0)  
                break  
            else:  
                print("This troubleshooting programme will only support iPhone 3-7.")  
                print("Make sure you type in iphone then the model of iPhone. (e.g iphone4)")  
                print("If you do not have these versions of the iPhone, please type in exit when prompted with the question again.")  
                break