我一直在研究这个python问题。我在一个介绍级别课程,我太困了。现在我没有错误,但程序没有打印数据(来自names.txt)或提示我搜索。任何帮助,将不胜感激。 -Thanks!
def main():
print("Last, \tFirst")
print
name_list = get_names()
print_list(name_list)
new_file(name_list)
search_list(name_list)
def get_names():
# open the data file
infile = open('names.txt', 'r')
# read all the lines from the file
name_list = infile.read().split('\n')
#close the input file
infile.close()
return(name_list)
#def print list
def print_list(name_list):
#print the data
for name in name_list:
print (name)
return(name)
#def new_file
def new_file(name_list):
outfile = open('sorted_names.txt' ,'w')
for item in name_list:
outfile.write(item + '\n')
outfile.close()
#def search_list
def search_list(name_list):
again = 'Y'
while again == 'Y':
name = input("What name would you like to look for? :")
try:
name_index = name_list.index(name)
print (name), (" was found in the list at index point: "), name_index
except ValueError as err:
print (name), (" was not found in the list.")
print ("Would you like to search for another name?")
again = input("Would you like to run the program again? [y/n]") == 'y'
# execute the main function
main()
答案 0 :(得分:0)
main()
做得不多,只打印几行。你会想让它调用你的其他功能。
答案 1 :(得分:0)
更正版本的最小更改:
def main():
print("Last, \tFirst")
print
name_list = get_names()
print_list(name_list)
new_file(name_list)
search_list(name_list)
def get_names():
# open the data file
infile = open('names.txt', 'r')
# read all the lines from the file
name_list = infile.read().split('\n')
#close the input file
infile.close()
#print data read into memory
print(name_list)
return(name_list)
#def print list
def print_list(name_list):
#print the data
for name in name_list:
print (name)
return(name)
#def new_file
def new_file(name_list):
outfile = open('sorted_names.txt' ,'w')
for item in name_list:
outfile.write(item + '\n')
outfile.close()
#def search_list
def search_list(name_list):
again = 'Y'
while again.upper()== 'Y':
name = raw_input("What name would you like to look for? :")
try:
name_index = name_list.index(name)
print (name), (" was found in the list at index point: "), name_index
except ValueError as err:
print (name), (" was not found in the list.")
print ("Would you like to search for another name?")
again = raw_input("Would you like to run the program again? [y/n]") == 'y'
# execute the main function
main()
发生了什么变化:
,name_list读取实际上是一个字符串,而不是列表。要获取需要在换行符上分割的行列表(.split('\n')
)。之后,您无需从名称
在get_names()返回后,您需要存储列表并传递给其他函数
new_file使用了name_list,但没有收到它作为参数
try / except块应嵌套在while块