添加“ else”会使我的for循环无法正常工作

时间:2019-07-22 22:08:44

标签: python python-3.x for-loop if-statement

我是编码的新手,并且有我需要搜索的列表列表。 我想看看包含在较大列表中的哪些列表具有变量full_choice作为序列中的第三项。 我需要将所有包含third_choice的列表打印到txt文件。

下面的代码可以正常工作,并将我需要的确切添加到文件中,但是如果变量full_choice不匹配,我需要重新启动该函数。

def display_instructor_txt():
    file_name = input('type in the name of the file you want to create do not include .txt')
    file_name_full = file_name + '.txt'
    new_file = open(file_name_full,'w')
    first_choice = input('type in the first name of the instructor you want to filter by ')
    last_choice = input('type in the last name of the instructor you want to filter by ')
    full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
    for course in all_courses_list:
        if course[2].replace(" ","").replace(",","") == full_choice:
            course_st = ''.join(course)
            new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
    else:
        print('please try again')
        display_instructor_txt()


我尝试插入else:在代码末尾,尽管最终创建了文件,但它并未写入任何内容。

2 个答案:

答案 0 :(得分:1)

试图解决您的缩进问题。我猜你想要这样的东西:

def display_instructor_txt():
    file_name = input('type in the name of the file you want to create do not include .txt')
    file_name_full = file_name + '.txt'
    new_file = open(file_name_full,'w')
    first_choice = input('type in the first name of the instructor you want to filter by ')
    last_choice = input('type in the last name of the instructor you want to filter by ')
    full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
    for course in all_courses_list:
        if course[2].replace(" ","").replace(",","") == full_choice:
            course_st = ''.join(course)
            new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
        else:
            print('please try again')
            display_instructor_txt()

我刚刚将else块向前移动,以与之前有几行的if块对齐。

答案 1 :(得分:0)

@Haken Lid怀疑,请修复缩进:

for course in all_courses_list:
    if course[2].replace(" ","").replace(",","") == full_choice:
        course_st = ''.join(course)
        new_file.write(course_st.replace('[','').replace(']','').
                       replace("'",'').replace('\\n','').replace(" ", ", "))
    else:
        print('please try again')
        display_instructor_txt()