我一直在研究這個python問題一段時間。我在一個初級班,我很困難。現在我沒有收到任何錯誤,但是程序沒有打印數據(來自names.txt)或者提示我搜索。任何幫助,將不勝感激。 -謝謝!導入文件,打印數據,搜索然後再打印 - PYTHON
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()
需要調用一個函數才能運行。你可能想檢查這個問題:http://stackoverflow.com/questions/419163/what-does-if-name-main-do – monkut