[Tutor] Problem with 'IF' condition

Peter Otten __peter__ at web.de
Fri Dec 1 12:50:24 EST 2017


a.ajmera at incycleautomation.com wrote:

> I am trying to compare two different values using "IF" condition in my
> program. Everything is working fine except this. I copied my program as
> plain text below

Your code has indentation errors, my analysis assumes

# the following was added to make it runnable
class TTS:
    def say(self, message):
        print "TTS says:", message
tts = TTS()
# end of my addition

tts.say("Hi")
x = "C:/FTP_Folder/test1.txt"
f = open(x)
r = f.read(500)
tts.say("Current position number in the text file is")
tts.say(r)
f.close()
f1 = open(x,'w')
z = f1.write("1")
f1.close()
tts.say("writing to file")
tts.say("A.B.B. robot; go to my directed position")
f = open(x)
r0 = f.read(500)
tts.say(r0)
nao = r0
f.close()
import time
time.sleep(5) # delays for 5 seconds
##f1 = open(x,'w')
##f1.write("0")
##f1.close()
y = "C:/FTP_Folder/test3.txt"
f2 = open(y)
r1 = f2.read(500)
abb = r1

if nao == abb:
    print("Positions are same")
    print r, r1
else:
    print("not same")
    print nao, abb

> , in the last section I used "IF" condition. - If you see
> in my code, I'm writing to "test1.txt" and saving that value in "nao" as
> well. On the other side, I'm reading from "test3.txt" and saving that
> value in "abb" just like above.
>  
> Now, my goal is to compare these two variables nao & abb. As it written
> below. However, result never gives me "true" when actually this both
> variable contain same values. 

No, they don't. nao will contain the first 500 bytes of the file 
"C:/FTP_Folder/test1.txt" while abb will contain the first 500 bytes of the 
file "C:/FTP_Folder/test3.txt". But even if you start with two files with 
the same contents -- with the following lines

> f1 = open(x,'w')
> z = f1.write("1")
> f1.close()

you overwrite "C:/FTP_Folder/test1.txt" which now contains only a single 
"1". Thus the nao == abb test will only compare equal if 
"C:/FTP_Folder/test3.txt" contains a single "1", too.

> This code always giving me "not same"
> result.
>  
> I'm not sure why this is not working.
> I would greatly appreciate your help.
>  
> Please let me know for any question.




More information about the Tutor mailing list