[Tutor] Problem with 'IF' condition
Steven D'Aprano
steve at pearwood.info
Fri Dec 1 18:11:54 EST 2017
On Fri, Dec 01, 2017 at 07:02:47AM -0700, a.ajmera at incycleautomation.com wrote:
> I copied my program as plain text below,
Unfortunately you didn't, as the text you quote below will not run as
Python code due to indentation errors.
So you have (accidentally, I trust) messed up the indentation. Please
take more care to copy and paste accurately, without adding extra spaces
at the start of lines.
> tts.say("Hi")
Since tts is not defined, this fails immediately with a NameError.
How is this line tts.say() relevant to your problem? It just adds extra
code, and makes it impossible for us to run your code. There is no
need to show us irrelevant code.
> 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')
This line has a spurious space added to the start. That's what I mean
about accidentally messing up the indentation.
> z = f1.write("1")
> f1.close()
You have now over-written the contents of file 'x' with a single digit
'1'.
> 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()
And now you re-read the same file 'x', reading a single '1' (because
that is all that is inside the file). r0 and nao will always be '1'.
> import time
Another copy-and-paste error introducing spurious indentation.
> time.sleep(5) # delays for 5 seconds
What is the point of this sleep? This has nothing to do with your
problem. Take it out.
> ##f1 = open(x,'w')
> ##f1.write("0")
> ##f1.close()
> y = "C:/FTP_Folder/test3.txt"
> f2 = open(y)
> r1 = f2.read(500)
> abb = r1
Now you read from a completely different file.
> if nao == abb:
> print("Positions are same")
> print r, r1
> else:
> print("not same")
> print nao, abb
Why do you expect them to be the same? You are reading from two
completely different files, one has been overwritten by the digit '1'
each time. The only possible way for these to be the same will be:
(1) Start file x as anything.
(2) Start file y with *exactly* a single digit '1' and nothing else.
Be careful because some text editors will automatically add a newline to
the end of your file when they save.
(3) You read file x.
(4) Then you over-write x with a single digit '1'.
(5) Then you re-read x, reading the single digit '1' again.
(6) Now you read y, getting '1'. If you get *anything* else, even a
single space or newline, they won't match.
(7) If they do match, your code prints the ORIGINAL (now over-written)
contents of x, and the contents of y, which has to be '1' or else it
will never match the NEW (over-written) contents of x.
--
Steve
More information about the Tutor
mailing list