Page 1 of 1

If calculation confusion - distance

Posted: Sun Jun 12, 2016 6:15 pm
by Mettauk
I have the following in a python script to measure distance

Code: Select all

...
  def measure_average():
  # This function takes 3 measurements and
  # returns the average.
  distance1=measure()
  time.sleep(0.1)
  distance2=measure()
  time.sleep(0.1)
  distance3=measure()
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance
Then

Code: Select all

try:

  while True:

    distance = measure_average()
    print "Distance : %.1f cm" % distance
    time.sleep(1)

except KeyboardInterrupt:
  # User pressed CTRL-C
  # Reset GPIO settings
  GPIO.cleanup()
I want to insert

Code: Select all

    if distance()>= 5
    print 'words'
    end if
For some reason it does not like it? I get

Code: Select all

~ $ sudo python ultra2.py
  File "ultra2.py", line 87
    if distance()>=5
                   ^
SyntaxError: invalid syntax
Guessing i'm making a really simple error??

Re: If calculation confusion - distance

Posted: Sun Jun 12, 2016 6:30 pm
by DougieLawson
All conditional statements in python must end with a colon (:)

Code: Select all

    if distance() >= 5: 
Anything that's conditional must be indented by at least one space from the indentation level of the if statement

Code: Select all

      print ("words")
There's also no scope terminators. So

Code: Select all

    end if
is completely invalid.

Re: If calculation confusion - distance

Posted: Sun Jun 12, 2016 6:47 pm
by Douglas6
And distance is a variable, not a method, so use

Code: Select all

if distance >= 5:

Re: If calculation confusion - distance

Posted: Sun Jun 12, 2016 6:56 pm
by stderr
Mettauk wrote:udo python ultra2.py
File "ultra2.py", line 87
if distance()>=5
^
SyntaxError: invalid syntax
[/code]
Guessing i'm making a really simple error??
The first thing to do is post things using the correct indentation since python requires that to even parse properly all other things being correct. According to a quick google, the python if construct looks like this:

Code: Select all

if expression:
   statement(s)
else:
   statement(s)
Finally, what do you mean by "if distance()>=5"? Is "distance()" a function? It might help to put spaces between things as sometimes that is required.

Re: If calculation confusion - distance

Posted: Sun Jun 12, 2016 8:45 pm
by Mettauk
Thanks to you both, I think I was having a minor mind melt!