所以我試圖制作一個代碼,從用戶那里輸入一個數字,并用該輸入顯示其他輸入的 ax 數量,以填充要寫在 .txt 檔案上的資料。但我真的無法讓它停止顯示,即使是if x > f: break. 我仍在學習 Python,并通過我的小專案走到了這一步。
f = file.write(input("Probes:"))
if f == 1:
file.write(" One Single Soil Probe")
else:
file.write(" Multiple Soil Probes")
file.write(" \n")
# System
x = 1
for a in range(f):
file.write("SP" str(x) ": ")
file.write(input("SP " str(x) ": " " \n"))
file.write("m")
x = x 1
if f > x:
break
else:
continue
file.write(" \n")
file.close()
uj5u.com熱心網友回復:
你的問題從這一行開始:
f = file.write(input("Probes:"))
首先,input()總是回傳一個字串,所以如果你想稍后將它與整數進行比較,你需要使用int().
但是,更大的問題是您沒有將input()陳述句f的回傳值分配給,而是將 的回傳值分配給file.write()。像這樣的東西會更好地為你服務:
f = int(input("Probes:"))
file.write(f)
...
此外,如上面的評論中所述,您不需要x,因為您已經在使用a. 但是請記住,range()除非另有說明,否則從 0 開始生成值。
uj5u.com熱心網友回復:
所提供的代碼存在許多問題。
首先,雖然file.write可能回傳一個數字,但在這種情況下它不是一個有用的數字:它回傳寫入檔案的位元組數。所以這是您需要進行的第一個更改。
f = input("Probes:")
但是,input回傳一個字串,因此我們需要將其轉換為數字。如果我們忽略錯誤檢查,那就很簡單了:
f = int(input("Probes:"))
現在我們已經失去了file.write呼叫,所以我們需要重新添加它。但是,file.write需要一個字串:
f = int(input("Probes:"))
file.write(str(f))
下一點現在可以了:
f = int(input("Probes:"))
file.write(str(f))
if f == 1:
file.write(" One Single Soil Probe")
else:
file.write(" Multiple Soil Probes")
file.write(" \n")
接下來我們有你的處理回圈。你真的不應該像那樣結合讀取和寫入,這會讓你很難理解發生了什么。我會像這樣重寫它:
for a in range(f):
sp_val = input("SP " str(a 1) ": " " \n")
file.write("SP" str(a 1) ": " sp_val "m\n")
file.write(" \n")
file.close()
然后,您可以使用一些技巧來使其更干凈。首先是with陳述句,其次是fstrings:
with open(filename) as file:
f = int(input("Probes:"))
file.write(str(f))
for a in range(f):
sp_val = input(f"SP {a 1}: \n")
file.write(f"SP{a 1}: {sp_val}m\n")
file.write(" \n")
我要提出的最后一點是重命名一些變數以使其更清晰,并避免隱藏內置函式:
with open(filename) as ouput_file:
probe_num = int(input("Probes:"))
ouput_file.write(str(probe_num))
for a in range(probe_num):
sp_val = input(f"SP {a 1}: \n")
ouput_file.write(f"SP{a 1}: {sp_val}m\n")
ouput_file.write(" \n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391581.html
