I've just started learning Python. After getting myself comfortable with Bash, I've decided to use Python and learn it. Please don't throw flame if this question seems stupid.
I got this "file.txt" which contains:
81
99
90
90
70
100
The if/else statement I'm using inside for loop does not seem to work:
with open('file.txt') as x:
for num in x:
if num > 90 :
print "NOT ok - ",num
else :
print "Okay - ",num
I can't understand why the output would be "NOT ok" for all the numbers.
NOT ok - 81
NOT ok - 99
NOT ok - 90
NOT ok - 90
NOT ok - 70
NOT ok - 100
Any help would be appreciated. Thanks.
-
3replace num with int(num) in if statement. You are comparing string with number.Dinesh Pundkar– Dinesh Pundkar2017年10月05日 03:51:25 +00:00Commented Oct 5, 2017 at 3:51
2 Answers 2
You are comparing string with number in if part.
Replace num with int(num) in if part.
>>> '81' > 90
True
>>> 81 > 90
False
>>>
Comments
As Dinesh pointed out, when reading from a file, the num is currently of string type. You can test the same by typing in the following:
for num in x:
print type(num)
if num > 90 :
So, before comparing the num, type it as below:
if int(num) > 90: