回到關於我的項目的另一個問題。所以我試圖在我的文本文件中按降序排列我的分數。但是,它會輸出語法錯誤。 當用戶輸入class_name時,上面創建的文件名是這樣,那麼什麼等於文件名。但是,它輸出一個錯誤。按字母順序排列分數和名稱,平均值,從最高到最低
這是我的一些代碼:
filename = class_name + ".txt"
with open(filename, 'a+') as w:
w.write(str(name) + " : " + str(score) + '\n')
print("Your results are being updated ...")
time.sleep(2)
print("Your score has been updated")
print("")
w.close()
if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
if selection == 'A':
with open(filename, 'r') as r:
for name in sorted(r):
print(name, end='')
if selection == 'B':
with open(filename, 'r') as r:
file_sorted = sorted((ast.literal_eval(x) for x in r),key=lambda z:(int(z[1]),z[0]),reverse=True)
r.close()
if selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
如何使它循環回「選擇=」的問題嗎?如果A,B或C未被選中。
if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
if selection == 'A':
print (alphabetically(data))
if selection == 'B':
print (by_score(data))
if selection == 'C':
print (by_average(data))
if selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
else:
input ("Press any key to exit")
編輯
像這樣的事情?
while True:
if selection == 'A':
print (alphabetically(data))
elif selection == 'B':
print (by_score(data))
elif selection == 'C':
print (by_average(data))
return True
else: selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
不回答的主要問題,但你可能想'如果選擇不['A','B','C']' – pkacprzak
是的,幾乎同樣的事情不是嗎?並且,如果他們不輸入A,B或C,我將如何使它回到他們輸入A,B或C的位置。 – Draguno