for i in range(0,5):
f = open("StudentRecords.txt", "a")
try:
f.write(input("Name: ") "\n")
f.write(str(int(input("ID: "))) "\n")
f.write(str(float(input("GPA: "))) "\n")
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.close()
例如,如果我嘗試為 GPA 撰寫一個字串,我將捕獲錯誤并且程式將繼續運行,但仍會寫入同一迭代的名稱和 ID 我希望它僅在所有 3 個資料都為時才寫入有效的。
uj5u.com熱心網友回復:
正如評論所說,最好的方法是在寫入任何內容之前驗證所有資料。但是如果你真的需要撤消,你可以通過保存每條記錄之前的檔案位置,回傳到它,并截斷以洗掉之后寫入的所有內容來實作。
而不是為每個記錄重新打開檔案,您應該在回圈之前打開它一次。用于with在塊完成時自動關閉它。
with open("StudentRecords.txt", "w") as f:
for i in range(0,5):
try:
filepos = f.tell()
f.write(input("Name: ") "\n")
f.write(str(int(input("ID: "))) "\n")
f.write(str(float(input("GPA: "))) "\n")
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.seek(filepos)
f.truncate()
uj5u.com熱心網友回復:
簡單的解決方案是先將輸入保存在變數中,然后再保存到檔案中。
for i in range(0,5):
f = open("StudentRecords.txt", "a")
try:
name = input("Name: ") "\n"
ID = str(int(input("ID: "))) "\n"
GPA = str(float(input("GPA: "))) "\n"
f.write(name ID GPA)
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.close()
話雖如此,我建議多更新代碼:
for i in range(0,5):
name = input("Name: ") "\n"
try:
ID = str(int(input("ID: "))) "\n"
GPA = str(float(input("GPA: "))) "\n"
with open("StudentRecords.txt", "a") as f:
f.write(name ID GPA)
except ValueError:
print("Error: You entered a String for ID or GPA.")
使用with意味著您不必處理f.close(),除其他外,因此您不會忘記它。由于該name = ...行似乎不需要 try-except 塊,我們可以將其移到外面。
uj5u.com熱心網友回復:
其他人已經向您展示了一種驗證資料的方法,但現在如果用戶犯了錯誤,程式就會停止。你真的想要一些方法讓他們糾正他們的錯誤并繼續。
把它放在你的主程式中需要一個單獨的回圈和try/except結構為每個數字,現在有兩個值還不錯,但隨著你添加更多值變得笨拙。
因此,與其重復我們自己,不如撰寫一個重復的函式,直到用戶輸入有效數字為止。我們可以傳入我們想要的數字型別(int或float)。
def inputnum(prompt, T=float):
while True:
try:
return T(input(prompt))
except ValueError:
print(">>> You entered an nvalid number. Please try again.")
然后呼叫該函式來獲取您的數字(結合其他一些小改進):
with open("StudentRecords.txt", "a") as f:
for i in range(5):
name = input("Name: ")
ID = inputnum("ID: ", int)
GPA = inputnum("GPA: ", float)
f.write(f"{name}\n{ID}\n{GPA}\n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324118.html
