Python Syntax Error in if statement - python

I'm stucked with a Python if-statement. I finished pretty much everything but when running my progarmm, it gives my an syntax error in the first line: I'm so sure I did everything right but as I'm very new to Python and programming at all, it might just be a very foolish mistake...
Thanks for helping guys!
if a == 2:
StartDeckNeighbourright = StartDeck[a + 1]
StartDeckNeighbourright2 = StartDeck[a + 2]

If this isn't the IndentationError that jramirez's answer fixes, but rather an actual SyntaxError, it's probably a problem with the line before the if statement.
In Python, you can continue an expression across multiple lines, as long as the expression is inside parentheses. So, if you accidentally leave off a ) at the end of a function call, or a tuple, or anything else, you often get a mysterious SyntaxError on the next line. For example, this code:
foo = (1, 2
if a == 2:
pass
… will give this error:
if a == 2:
^
SyntaxError: invalid syntax
And just adding another comma moves the error somewhere different!
foo = (1, 2,
if a == 2:
pass
if a == 2:
^
SyntaxError: invalid syntax
Why? Well, even when you understand exactly what these errors mean, they still aren't very helpful. So first, remember:
If you get a SyntaxError on a perfectly valid line, look for a missing ) (or ] or }, or an extra \, or a few other special cases) on the line above.
And if you can get an editor that helps you match up parentheses and brackets, it will make this problem much less likely. (For example, with emacs, at least the way I have it set up, it'll automatically try to indent the if line 7 characters for me, and if I "fix" it it'll fight back against me, and eventually it'll be hard not to notice something is wrong. Then I point at the first ( and it tells me it's unmatched.)
But if you want to know, here goes:
The first version builds a tuple with the value 1, then a value starting with 2 and continuing onto the next line. 2 if a == 2 is a perfectly good beginning for a ternary if expression, but 2 if a == 2: is not; the colon forces it to be an if statement, and you can't put a statement in the middle of an expression.
The second version builds a tuple with the value 1, the value 2, and more values continuing on the next line. if cannot be the start of any valid expression, so you get the SyntaxError earlier. But still not early enough to be useful, of course.

You should post the error you are seeing, however I think all you need is indentation after the if statment
if a == 2:
StartDeckNeighbourright = StartDeck[a + 1]
StartDeckNeighbourright2 = StartDeck[a + 2]
---- four spaces of indentation

In python You must use Indentation:
if a == 2:
StartDeckNeighbourright = StartDeck[a + 1]
StartDeckNeighbourright2 = StartDeck[a + 2]

Related

Using for loops in python interpreter

I'm trying to start a for loop after doing something else in python interpreter on the same line, and it throws a SyntaxError when I do so.
>>> a,b = 0, 1;\
... for i in range(1, 10):
File "<stdin>", line 2
for i in range(1, 10):
^
SyntaxError: invalid syntax
Of course I could just execute them separately here, but if I want to have this inside a function definition then I can't exactly do that. What is the correct syntax to do it in the interpreter?
When you have a backslash, you are telling it to ignore the new line. So Python thought your code was a,b = 0, 1 for i in range(1,10):. This is clearly invalid syntax. So, you must remove the semicolon and the backslash. When you want to go to the new line, use shift + enter key.
After that, it should work:

Python coding convention "Wrong continued indentation before block: found by pylint

I used pylint to check my python code, and found this convention problem:
C:11, 0: Wrong continued indentation before block.
+ this_time <= self.max):
^ | (bad-continuation)
I tried to refine for times but the problem is still present, can someone help? Thanks!
if len(remaining_obj_list) > 0:
for i in a_list:
this_time = self.__get_time(i)
for remaining_obj in remaining_obj_list:
if (remaining_obj.get_time() # to fit 78 char rule
+ this_time <= self.max):
i.append(remaining_obj)
remaining_obj.set_used(True)
if 0 == len(self.__get_unused_list):
break
Pylint doesn't want such continuation to start on the same column as the next indentation block. Also, notice that the message includes a hint on columns that it considers correct.
Try putting the + on the previous line:
if (remaining_obj.get_time() +
this_time <= self.max):
As a side note though, you might want to consider the factors that are causing your code to have to fit within ~40 characters - perhaps you have a few too many indentation levels and your code could be refactored to have fewer nested blocks.
Check for spurious tabs (in Sublime: Ctrl + F, then enter a single space) and replace them by the correct number of spaces. I had the same issue and while PyLint was complaining about line continuation, the error was actually triggered by misplaced tabs.
At indentations, PyLint seems to count spaces only and throws this error if the numbers don't add up to multiples of 4. Depending on the editor, misplaced tabs may not be immediately visible.
According to PEP8 the preferred place to break around a binary operator is before the operator. This did not used to be the case, but it changed to be consistent with mathematical formula conventions.

Syntax error with if statement in python 2.7

I'm having trouble with a "Syntax Error: invalid syntax" message in python code that keeps moving the goals posts on me.
Here's the sample code:
another_answer = int(raw_input("> ")
if another_answer == 1:
print "The pirate's body slowly goes limp and he whispers to you......."
print "Good luck my son. You might need this."
get_gold()
print: "Do you want to continue to the next room?"
When I run this in the shell I get the following:
File "ex36.py", line 179
if another_answer == 1:
^
SyntaxError: invalid syntax
I found this bizarre, and after removing the colon I got an error message on the next line:
File "ex36.py", line 180
print "The pirate's body slowly goes limp and he slowly whispers to you......."
^
SyntaxError: invalid syntax
Similar questions I've found on stackoverflow center around improper spacing and indentation, but I've looked that over and everything seems to be well.
The preceding line is missing a closing parenthesis:
another_answer = int(raw_input("> ")
# ^ ^ ^^
# \ \--//
# \-----------?
Python allows expressions to cross physical lines when enclosed in parentheses, so when you don't close parentheses Python continues to look for the rest of the expression. By the time it reaches the : the expression makes no sense anymore and a SyntaxError exception is raised.
You're missing a closing parenthesis on the first line. The colon is simply the first character which couldn't possibly be part of an actual function argument.
You have two problems, and you have to fix both.
The first is that you're missing a closing parenthesis:
another_answer = int(raw_input("> ")
This means that Python is still trying to compile the arguments to the call to int when it gets to the next line. Until the colon, everything is still legal, because you could have been writing this:
another_answer = int(raw_input("> ")
if another_answer == 1
else '42')
But once you get to the colon, there is no valid expression that could appear in, so that's where you get the SyntaxError.
In general, when you get a SyntaxError on a line where absolutely nothing looks wrong, look to the previous line—usually it's a missing ) (or ] or }).
However, if you fix that, you're going to have another problem. Although you claim this:
Similar questions I've found on stackoverflow center around improper spacing and indentation, but I've looked that over and everything seems to be well.
… everything is definitely not well:
another_answer = int(raw_input("> ")
if another_answer == 1:
That if statement is indented to the right of that another_answer statement. That's illegal, and will raise an IndentationError. You can only change indentation levels in Python to enter or exit a block controlled by a compound statement.
You've also got at least one more error in your code:
print: "Do you want to continue to the next room?"
This will raise a SyntaxError. print isn't a compound statement like if or def, so it doesn't take a colon.
It is easy to find you missed a closing parenthesis at the first line.

Incorporating multiple lists in one text file

I am new to coding and I ran in trouble while trying to make my own fastq masker. The first module is supposed to trim the line with the + away, modify the sequence header (begins with >) to the line number, while keeping the sequence and quality lines (A,G,C,T line and Unicode score, respectively).
class Import_file(object):
def trim_fastq (self, fastq_file):
f = open('path_to_file_a', 'a' )
sanger = []
sequence = []
identifier = []
plus = []
f2 = open('path_to_file_b')
for line in f2.readlines():
line = line.strip()
if line[0]=='#':
identifier.append(line)
identifier.replace('#%s','>[i]' %(line))
elif line[0]==('A' or 'G'or 'T' or 'U' or 'C'):
seq = ','.join(line)
sequence.append(seq)
elif line[0]=='+'and line[1]=='' :
plus.append(line)
remove_line = file.writelines()
elif line[0]!='#' or line[0]!=('A' or 'G'or 'T' or 'U' or 'C') or line[0]!='+' and line[1]!='':
sanger.append(line)
else:
print("Danger Will Robinson, Danger!")
f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger))
f.close()
return (sanger,sequence,identifier,plus)
Now for my question. I have ran this and no error appears, however the target file is empty. I am wondering what I am doing wrong... Is it my way to handle the lists or the lack of .join? I am sorry if this is a duplicate. It is simply that I do not know what is the mistake here. Also, important note... This is not some homework, I just need a masker for work... Any help is greatly appreciated and all mentions of improvement to the code are welcomed. Thanks.
Note (fastq format):
#SRR566546.970 HWUSI-EAS1673_11067_FC7070M:4:1:2299:1109 length=50
TTGCCTGCCTATCATTTTAGTGCCTGTGAGGTGGAGATGTGAGGATCAGT
+
hhhhhhhhhhghhghhhhhfhhhhhfffffe`ee[`X]b[d[ed`[Y[^Y
Edit: Still unable to get anything, but working at it.
Your problem is with your understanding of the return statement. return x means stop executing the current function and give x back to whoever called it. In your code you have:
return sanger
return sequence
return identifier
return plus
When the first one executes (return sanger) execution of the function stops and sanger is returned. The second through fourth return statements never get evaluated and neither does your I/O stuff at the end. If you're really interested in returning all of these values, move this after the file I/O and return the four of them packed up as a tuple.
f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger))
f.close()
return (sanger,sequence,identifier,plus)
This should get you at least some output in the file. Whether or not that output is in the format you want, I can't really say.
Edit:
Just noticed you were using /n and probably want \n so I made the change in my answer here.
You have all sorts of errors beyond what #Brian addressed. I'm guessing that your if and else tests are trying to check the first character of line? You'd do that with
if line[0] == '#':
etc.
You'll probably need to write more scripts soon, so I suggest you work through the Python Tutorial so you can get on top of the basics. It'll be worth your while.

Strange error about invalid syntax

I am getting invalid syntax error in my python script for this statement
44 f = open(filename, 'r')
45 return
return
^
SyntaxError: invalid syntax
I am not sure what exactly is wrong here? I am a python newbie and so will greatly appreciate if someone can please help.
I am using version 2.3.4
I had the same problem. Here was my code:
def gccontent(genomefile):
nbases = 0
totalbases = 0
GC = 0
for line in genomefile.xreadlines():
nbases += count(seq, 'N')
totalbases += len(line)
GC += count(line, 'G' or 'C')
gcpercent = (float(GC)/(totalbases - nbases)*100
return gcpercent
'return'was invalid syntax
I simply failed to close the bracket on the following code:
gcpercent = (float(GC)/(totalbases - nbases)*100
Hope this helps.
I got an "Invalid Syntax" on return when I forgot to close the bracket on my code.
elif year1==year2 and month1 != month2:
total_days = (30-day1)+(day2)+((month2-(month1+1))*30
return (total_days)
Invalid syntax on return.
((month2-(month1+1))*30 <---- there should be another bracket
((month2-(month1+1)))*30
Now my code works.
They should improve python to tell you if you forgot to close your brackets instead of having an "invalid" syntax on return.
Getting "invalid syntax" on a plain return statement is pretty much impossible. If you use it outside of a function, you get 'return' outside function, if you have the wrong indentation you get IndentationError, etc.
The only way I can get a SyntaxError: invalid syntax on a return statement, is if in fact it doesn't say return at all, but if it contains non-ascii characters, such as retürn. That give this error. Now, how can you have that error without seeing it? Again, the only idea I can come up with is that you in fact have indentation, but that this indentation is not spaces or tabs. You can for example have somehow inserted a non-breaking space in your code.
Yes, this can happen. Yes, I have had that happen to me. Yes, you get SyntaxError: invalid syntax.
i just looked this up because i was having the same problem (invalid syntax error on plan return statement), and i am extremely new at python (first month) so i have no idea what i'm doing most of the time.
well i found my error, i had forgotten an ending parentheses on the previous line. try checking the end of the previous line for a forgotten parentheses or quote?
>>> 45 return
File "<stdin>", line 1
45 return
^
SyntaxError: invalid syntax
>>>
That might explain it. It doesn't explain the 44 f = open(filename, 'r'), but I suspect that someone copied and pasted 45 lines of code where the indentation was lost and line numbers included.
Usually it's a parenthetical syntax error. Check around the error.
I encountered a similar problem by trying to return a simple variable assignation within an "if" block.
elif len(available_spots)==0:
return score=0
That would give me a syntax error. I fixed it simply by adding a statement before the return
elif len(available_spots)==0:
score=0
return score
I had the same problem. The issue in my case was, that i mixed up datatypes in my return statement. E.g.
return string + list + string

Categories

Resources