Python Forum

Full Version: If statement not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Using Linux Mint 18.2 and Python 2.7 with Python 3.5.
Help needed do not understand why the ' if (number == line_num) ' does
not work. The routine continues and gives results for ' expenses-18 '.
How to resolve this?
tia
oldcity
 #!/usr/bin/python3
 #
 ###############################################
 line_num = 1
 with open('Expenses-YY', 'r') as exp_yrs:
     for line in exp_yrs:
         yrs_file = line.strip(",")
         print '(', line_num, ')', yrs_file
         line_num+=1
 #
 #
 number = input(' Enter line #  : ')
 #
 line_num = 0
 with open('Expenses-YY', 'r') as exp_yrs:
     for line in exp_yrs:
         datafile1 = line.strip()
         line_num+=1
         print number, line_num, datafile1
         line_num = int(line_num)
     if (number == line_num):
        datafile = datafile1
 #
 #
 #
 datafile = datafile1.strip()
 #
 print datafile
 with open(datafile, 'r') as exp_data:
     for line in exp_data:
         (pdate,catg,amt,howp) = line.split(',')
         pdate = str(pdate)
         pdate = pdate.strip()
         pdate = str(pdate)
         length = len(pdate)
         howp = howp.strip()
         print pdate, catg, amt, howp

 #   Do stuff here not above line

 print 'job done'
###################################################

 # This is a sample of the resluts.

 ( 1 ) expenses-16

 ( 2 ) expenses-17

 ( 3 ) expenses-18

  Enter line #  : 2
 2 1 expenses-16
 2 2 expenses-17
 2 3 expenses-18

 expenses-18

 010318 2 19.67 2
 010518 5 82.40 2
 010518 6 195.87 2
 050818 2 18.96 2
 051718 3 15.37 2
 052918 1 0.00 2
 job done
The problem is that "number" is a string. The input function returns a raw string of the user input. Python cannot compare strings and numbers (e.g. "5" != 5). To correct this, you can change line 12:

number = int(input(' Enter line #  : '))
By the OP's print statement, they must be using Python 3, where input() returns a string.
I think you want to break out of the loop when the condition is True. But in fact you continue to loop till the end of the file. So at that moment the value of datafile1 is expenses-18 and on line 26 you override the value of datafile that was assigned when the condition was True with the current one (i.e. the last entry in the file).
That said your code has many redundant parts and overall algorythm is far from efficient/best/pythonic one
Did complete re-write.
Thanks