簡體   English   中英

我遇到了 python 中的循環問題

[英]I'm having a problem with a loop in python

因此,我試圖制作一個代碼,該代碼從用戶那里獲取一個數字輸入,並通過該輸入顯示其他輸入的 x 數量以填充要寫在 a.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()

您的問題從這一行開始:

f = file.write(input("Probes:"))

首先, input()總是返回一個字符串,所以如果你想稍后將它與整數進行比較,你需要使用int()來轉換它。

但是,更大的問題是您沒有將input()語句的返回值分配給f ,而是分配了file.write()的返回值。 這樣的事情會更好地為您服務:

f = int(input("Probes:"))
file.write(f)
...

此外,正如上面評論中所解釋的,您不需要x ,因為您已經在使用a 但是請記住,除非另有說明,否則range()從 0 開始生成值。

所呈現的代碼存在許多問題。

首先,雖然file.write可能返回一個數字,但在這種情況下它不是一個有用的數字:它返回寫入文件的字節數。 所以這是你需要做的第一個改變。

f = input("Probes:")

但是, input返回一個字符串,因此我們需要將其轉換為數字。 如果我們忽略錯誤檢查,這很簡單:

f = int(input("Probes:"))

現在我們丟失了file.write調用,所以我們需要重新添加:

f = int(input("Probes:"))
file.write(f)

下一點現在可以了:

f = int(input("Probes:"))
file.write(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(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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM