0

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.

1
  • 3
    replace num with int(num) in if statement. You are comparing string with number. Commented Oct 5, 2017 at 3:51

2 Answers 2

2

You are comparing string with number in if part.

Replace num with int(num) in if part.

>>> '81' > 90
True
>>> 81 > 90
False
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.