Search code examples
pythonpython-3.xsyntax-errorraspbian

SyntaxError: syntax invalid in python but can't find the cause


I am 12 years old and working on my science fair project. 1000s of packages are stolen everyday so for my science fair project I am building a thing that goes on peoples porches. It detects a package and when the package is taken off without verification it beeps very loudly and takes a picture of the thief. I am writing the code in python 3 on my raspberry pi. I have never coded in python before but I know c and html and css. I haven't added the verification part yet but that will be somewhere in the code eventually and it will change the pin value to 0 or 1 if PIN is entered. **My code is giving me this error:

if pin == 1
          ^
SyntaxError: invalid syntax**



from Bluetin_Echo import Echo
import RPi.GPIO as GPIO
import time
import nexmo
import picamera

GPIO.setup(40,GPIO.OUT)
pin = 1
TRIGGER_PIN = 38
ECHO_PIN = 36
result = echo.read('in')
alarm = 40
speed_of_sound = 315

echo = Echo(TRIGGER_PIN, ECHO_PIN, speed_of_sound)

if pin == 1
    if result < '5'
        if result >= '10'
            GPIO.output(14, 1)
<code>

Solution

  • In Python, since there are no brackets when declaring a block, we rely on indentation and punctuation. The : symbol is used to start an indent suite of statements in case of if, while, for, def and class statements.

    if expression:
       # something
       pass
    
    
    while expression:
       # something
       pass
    
    
    for x in sequence:
       # something
       pass
    
    
    def fct():
       # something
       pass
    

    (pass is a null operation, it does nothing; useful in places where your code will eventually go, but has not been written yet)

    So, your code should actually be:

    if pin == 1:
        if result < '5':
            if result >= '10':
                GPIO.output(14, 1)
    

    Also, take care that:

    • You are comparing result with '5' and '10' as strings, not as numbers; I'm not saying this is really a mistake, but are you sure these should't be numbers?

    • You'll never reach the line with GPIO.output(14, 1). You check the result to be less than 5, but later, bigger than 10, which is impossible.

    Since you are a beginner with Python, I recommend you to search in the documentation the things you struggle with. There are also nice tutorials on Python on different websites such CodeAcademy or w3schools.

    I also recommend you to use an IDE for your projects, one that supports Python. Most of the time, they will point out the syntax errors you make before executing the code. I'm using Pycharm for my projects (you can download the Community version for free). You can also set up Sublime Text 3, Atom, Visual Code or Notepad++ with the appropriate plugins to help you.

    Good luck with your project!