[英]Python | simple if/else statement inside for loop - not working
我剛剛開始學習Python。 在使自己對Bash感到滿意之后,我決定使用Python並學習它。 如果這個問題看起來很愚蠢,請不要大怒。
我得到了這個“ file.txt”,其中包含:
81
99
90
90
70
100
我在for循環內部使用的if / else語句似乎不起作用:
with open('file.txt') as x:
for num in x:
if num > 90 :
print "NOT ok - ",num
else :
print "Okay - ",num
我不明白為什么所有數字的輸出都“不好”。
NOT ok - 81
NOT ok - 99
NOT ok - 90
NOT ok - 90
NOT ok - 70
NOT ok - 100
任何幫助,將不勝感激。 謝謝。
您正在比較字符串和數字, if
部分。
if
部分將num
替換為int(num)
。
>>> '81' > 90
True
>>> 81 > 90
False
>>>
正如Dinesh指出的那樣,從文件中讀取時,num當前為字符串類型。 您可以通過輸入以下內容進行測試:
for num in x:
print type(num)
if num > 90 :
因此,在比較num之前,請如下鍵入:
if int(num) > 90:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.