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

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>

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!

Related

Why python doesn't see the members of quantumCircuit class qiskit

I`m trying to learn the programming on quantum computers.
I have installed qiskit in VS Code (all qiskit extentions available in VS Code market) , python compilator (from Vs Code market "Python" and "Python for VSCode"). I have set up my qikit API for correct working
When I run the exemple I get erros: "Instance of 'QuantumCircuit' has no 'h' member"
What shoud I do?
The code:
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
job_sim = execute(qc, 'local_qasm_simulator')
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
========================
The same error after adding comment # pylint: disable=no-member
The errors in question are coming from pylint, a linter, not from python itself. While pylint is pretty clever, some constructs (particularly those involving dynamically-added properties) are beyond its ability to understand. When you encounter situations like this, the best course of action is twofold:
Check the docs, code, etc. to make absolutely sure the code that you've written is right (i.e. verify that the linter result is a false positive)
Tell the linter that you know what you're doing and it should ignore the false positive
user2357112 took care of the first step in the comments above, demonstrating that the property gets dynamically set by another part of the library.
The second step can be accomplished for pylint by adding a comment after each of the offending lines telling it to turn of that particular check for that particular line:
qc.h(q[0]) # pylint: disable=no-member

Why can't I get the output in Python?

def travel():
travel.s=0
travel.frate=[]
travel.tr=[]
def accomodation():
print"""specialises
1.place 1
a.hotel 1
b.hotel 2
Hotel1:ac/non ac rooms
Ac.for ac...
Noac.for non ac...."""
hd=[5000,6000]
hg=[4000,7000]
TAc=[1000]
Nac=[400]
ch5=input("Enter your choice")
fav=raw_input("ENter hotel choice")
mode=raw_input("Enter ac/no ac")
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
else:
frate=hd[i]+Nac
if(ch5==2):
for i in range(0,2,1):
frate=hg[i]+TAc
else:
frate=hg[i]+Nac
accomodation()
travel()
When i run the program , i get the error as List Index out of range.but in hd and hg list,there are only two elements, so index number will be from 0 right?? Is there anything i should import?? I even gave statements like this:
travel.frate=travel.hg[i]+TAc
but it still doesn't come.Thank you for your effort.
the indentation is proper now,but the output is still not coming.
The specific issue you are encountering is caused by these lines here:
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
hd[i] looks at hd[5000] and hd[6000] which will throw an IndexError.
But if you fix that, you're going to run into another error, because
frate=hd[i]+TAc
tries to add a list TAc to an integer hd[i], which is an unsupported operation. You probably need frate=hd[i]+TAc[0], or even better, make TAc a number rather than a list. This issue occurs elsewhere in your code as well.
Finally, while not causing explicit issues in your code right now, there are two other problems:
ch5=input("Enter your choice") is dangerous since input tells Python to run whatever code snippet the user enters. In this case, much safer to do ch5=int(raw_input("Enter your choice"))
for i in range(0,2,1): is really for i in range(2): - only use the starting index and jump parameters if you need to change them from their default, namely 0 and 1.
There are other issues like variable scope (you're expecting travel.frate to be modified from within accommodation, but that's not happening) and defining variables in functions like travel.frate (not invalid syntax, but definitely strange) but those are probably better addressed outside of this question.

My python code runs a few times but as soon as I close my computer or do something else, it doesn't run again

Running this code a few times presents no issues. Upon attempting to show a friend, it doesn't work. It just hangs after the input. It's worked quite a few times before but never again unfortunately.
I've tried rewriting the code in brackets, rewriting the code to a local directory instead of the Google Drive folder I have and I've even tried rewriting from scratch in regular notepad. All this was tried in case some sort of encoding issue had occured. No such luck. I figure something is wrong with the interpreter but I'm not sure how to remedy the situation.
def bin2dec():
bin = []
a = int(input("What number are you converting to binary?: "))
while a > 0:
if a % 2 == 0:
bin.insert(0, 0)
a = a/2
elif a % 2 == 1:
bin.insert(0, 1)
a = a/2-0.5
else:
#repetition
print("Your binary equivalent is:", bin)
repeat = input("Would you like to convert another binary number?: ")
if repeat == "yes":
bin2dec()
bin2dec()
Oh....welp. It seems the problem was actually that I somehow installed two versions of pythons and I guess they had been interfering with each other. Reason I'm not deleting this Q is because I'm sure I'm not the only one who's made this mistake. However, others have probably made this mistake in an effort to ensure compatibility between versions. Bad idea.

Not allowing numbers in Glade with Python

I'm a fairly new Python programmer (started 3 days ago). I'm working as a apprentice for a civil engineer and he asked me to do some simpler tasks for his program, as of the objective I should work with is to not allow numbers from inputs in certain glade objects.
The code I've been struggling with creating is as such:
def testOmHeltal (self, number1):
textviewResultat = self.builder.get_object("textviewResultat")
text = gtk.TextBuffer()
try:
#print number1.get_text()
#temp = number1.get_text() + number1.get_text()
temp = float(number1.get_text())
except ValueError:
text.set_text("ERROR: Endast Nummer")
self.builder.get_object("hboxWarning").show()
self.builder.get_object("image12").show()
self.builder.get_object("textviewResultat").set_buffer(text)
return 0
self.builder.get_object("hboxWarning").hide()
self.builder.get_object("image12").hide()
def quit(self, widget):
sys.exit(0)
This code is called upon at the location of the glade object with this line:
self.testOmHeltal(entryGladeObject)
Now to the problem at hand, I allways get an Float error as such:
File "bvf.py", line 393, in utfora
+float(entryTjockleksskyddslager.get_text<>>>>
ValueError: invalid literal for float<>: 0.04e
0.04e is the invalid input and line 393 is a piece of my Chiefs code, since all he uses is float all the time and I shouldn't meddle with it too much I'm kind of panicking alittle..
I understand that float can only start and end with a number to not give an error, but since my "code" bit wants an error(or rather, an exception) to start the 'hboxWarning' and 'image12' of someone using a letter instead of the supposed number, I'm at a loss at what to do ><
Instead of showing my error with hboxWarning and image12, nothing happens at all...
Any hints or advice would help alot.
I don't know if I understood correctly, but the error is not on your code, right?
All I can assume is that there's a piece of code trying to convert the value to float before your verification. If that's the case, you should verify the value before any processing is done on it, or move the try-except code around the faulty code, depending on the processing itself (for example, if the processing implies database manipulation, it would be safer to do all the verifications previously).
If the error is happening before the line where you run self.testOmHeltal(entryGladeObject), the execution of the signal/method stops right away and your code is never excecuted; that's why the warning isn't showing.

gsm location in python

I have this script file in python running on S60:
import location
def current_location():
gsm_loc = location.gsm_location()
print gsm_loc
current_location()
instead of printing a tuple of mcc, mnc, lac and cellId it prints None.
on top of my python shell I see location between the capabilities included.
what can be the problem?
Development of the situation:
I thought maybe nevertheless, my problem is lack of capabilities. So I went to sign the PythonScriptShell file.
I used OPDA website - I know they sign all the capabilities but three - which I don't use.
I installed the signed PythonScriptShell file on my phone (N95). On the top the list of capabilities didn't change. tried to run the script again:
same result - prints None.
If anyone can help me with this, it's really important.
thank you.
I think I can answer now one part of the problem:
the reason for printing None is because there needed another capability: ReadDeviceData which wasn't included in the capabilities list on top of python shell.
still, remaining the other part of the problem, why this capability wasn't included when I signed PythonScriptShell file? It is not one of the three restricted capabilities.
I have same issue with all necessary scriptshell capabilities: 'PowerMgmnt', 'ReadDeviceData', 'WriteDeviceData', 'TrustedUI', 'ProtServ', 'SwEvent', 'Network services', 'LocalServices', 'ReadUserData', 'WriteUserData', 'Location', 'SurroundingsDD', 'UserEnviroment'.
Let's take a look at source code from PythonForS60/module-repo/dev-modules/location.py:
import e32
import _location
def gsm_location():
if e32.s60_version_info>=(3,0):
ret = _location.gsm_location()
if ret[4]==1: # relevant information ?
return (int(ret[0]),int(ret[1]),ret[2],ret[3])
else:
return None # information returned by _location.gsm_location() not relevant
else:
return _location.gsm_location()
On my Nokia E71 e32.s60_version_info == (3,1) and I get None value too.
I don't really know what means 'not relevant', but direct calling
>>> import _location
>>> _location.gsm_location()
(u'257', u'01', 555, 11, 0)
returns something close to my objective reality.

Categories

Resources