【发布时间】:2019-11-30 22:06:43
【问题描述】:
我是编码新手,我有一个需要搜索的列表列表。 我想查看较大列表中包含的哪些列表将变量 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: ,但是虽然这最终会创建文件,但它不会向其中写入任何内容。
【问题讨论】:
-
else之后到底写了什么代码? -
请显示无效的代码。
-
else: print('name not found please try again') dispaly_instructor_txt()
-
@AndreaRichmond:编辑问题并将其添加到那里。在 python 中,缩进很重要,问题中的代码示例与导致错误的原因完全相同,这一点非常重要。
-
代码中的
''''''''''''应该是做什么用的?那缩进是否正确?
标签: python python-3.x for-loop if-statement