Invalid Syntax and I don't know why - python

I have this code in Python 3. I am a begginer so links to good sites will also be helpful. Anyway my goal is to find two duplicated numbers in a list and then find the number of elements between them. When I run my module it comes up as invalid syntax with no explanation. All it said was Invalid Syntax with nothing else. Any help is appreciated.
def pirate_list(thelist):
duplicate = set()
duplicate_add = duplicate.add
f = []
for i in thelist:
if i in duplicate or duplicate_add(i):
f.append(i)
print (f)
f.reverse()
print(f)
break
else:
f.append(i)
print ("fail")
pirate_list([6,1,0,2,1,6])
def count_list(f):
duplicate = set()
duplicate_add = duplicate.add
s = []
for x in f:
if x in duplicate or duplicate_add(x):
s.append(x)
print len(s)
break
else:
s.append(x)
count_list(f)

The text under each def statement should be indented.
The last line refers to countlist which is not defined, and f which is defined inside a different function.

The def statements are to be indented. countlist should be count_list, on the last line as Jonathon Clede said.
Make it a practice to learn to understand error messages. They are vital to debugging your code. Even though there was no real error message this time, be sure to do it other times. SyntaxError by itself is usually caused by a pesky error like this indentation one.

If it is python2 code, then the only error I find is the undefined variable f in the last line.
If it is python3 code, then you must change print len(s) to print(len(s)) as print is a function in python3 and not a separate statement keyword.

Thanks for all the help. It was a rookie mistake forgetting parentheses for the print len(s) and also bringing the f list outside the functions.

Related

File "<string>" SyntaxError: invalid syntax [duplicate]

This question already has answers here:
Why do I get the syntax error "SyntaxError: invalid syntax" in a line with perfectly valid syntax?
(4 answers)
Closed 4 months ago.
I've recently been trying to code a program which plays domino with two players and with input, but apparently my syntax is flawed at the line where I define a function. I think it might be because of my near-zero experience with coding 😅, but after I've searched on the internet, I haven't found any solution.
Here's the code :
def comptage():
occurences_of_numbers=[]
for i in range(7):
a=0
for k in range(7):
if i in list(hand[k]):
a=a+1
occurences_of_numbers.append(a)
return(occurences_of_numbers)
File "<string>", line 36
def comptage():
^
SyntaxError: invalid syntax
This function counts the numbers of occurrences of the numbers (0,1,2,3,4,5,6) in the tuples representing the dominos in the list named hand. I then use the function for other functions.
available_draws=14
opponent_hand=7
while comptage()[list(board[0])[0]]==0 and comptage()[list(board[len(board)-1])[1]]==0:
inpt_list=list(map(int,input(' Quel domino pioché ?')))
M.append((inpt_list[0],inpt_list[1]))
available_draws=available_draws-1
#board is a tuple list representing the board
def riposte():
probability=[]
for i in range(7):
b=0
for k in range(len(board)):
if i in list(board[k]):
b=b+1
probability.append((7-comptage()[i]-b)/(28-len(hand)-len(board))*(opponent_hand/(opponent_hand+available_draws)))
return(probability)
This error popped up after I changed something in the riposte() function (I added the b characteristic). But it shows the mistake for the comptage() function. I don't know why it showed that.
I've tried changing the code a bit, rewriting it, and using other variants, but the error message stands still.
The rest of the code is : (some unfinished stuff)
zero=[]
one=[]
two=[]
three=[]
four=[]
five=[]
six=[]
all_the_dominos=[zero,one,two,three,four,five,six]
for i in range(7):
for k in range(7):
all_the_dominos[i].append((i,k))
hand=[]
for i in range(1,8):
input_list=list(map(int,input(' Domino '+str(i)+' ?')))
hand.append((input_list[0],input_list[1]))
print(hand)
for i in range(7):
for k in range(7):
if hand[i] in all_the_dominos[k]:
del all_the_dominos[k][all_the_dominos[k].index(hand[i])]
elif tuple(reversed(list(hand[i]))) in all_the_dominos[k]:
del all_the_dominos[k][all_the_dominos[k].index(tuple(reversed(list(hand[i]))))
board=[(6,1),(1,2),(2,6),(6,6)]
#example of a board
available_draws=14
opponent_hand=7
while input(' Pioche adverse ?')=='oui':
opponent_hand=opponent_hand+1
available_draws=available_draws-1
The only thing that comes after what is problematic is the last bit.
Help would be greatly appreciated. 😁
!! UPDATE !!
I've trisd another version of the compatge function, but it still shows the same error :
def comptage():
F=[0,0,0,0,0,0,0]
for i in range(7):
for k in range(len(M)):
if i in list(M[k]):
F[i]=F[i]+1
return(F)
But something's strange : i can't even define a variable !
a=0
File "<string>", line 34
a=0
^
SyntaxError: invalid syntax
I definitely think there is a problem with my phone because i've downloaded several other coding programs and always got the same error.
It's strange because it was working fine and all of a sudden, it doesn't allow me to do anything.
Well maybe there's just a problem with the code 😂 but i really don't think so.
It looks like you have 1 more closing parenthesis ()) than opening parenthesis (() on this line: P.append((7-comptage()[i]-b)/(28-len(M)-len(J))*(aM/(aM+p)))
Actually, I've found the problem : there was just a missing bracket 😕. I'm new to Python so I didn't pay enough attention even though I thought I did.

problem with Python indentation with simple code, if, else

When I hit enter after typing else: to move to the next line, it gives error indentation, no matter how I align it, i tried 4 spaces, everything still not working. I made sure that else is aligned perfectly with if as in the book, but still error.
Can someone please explain to me how indentation works? I'm using Python 2.7
Code:
if x%2 == 0:
print "Even"
else:
print "Odd"
print "done with conditional"
Assume as if python has an reverse hierarchical structure like an inverted traingle.
when ever you want to write function/loop/conditions in 1st level, we write whatever the code we are writing inside those three sections in 2nd level.
In your code "if" and "else" comes in 1st level. so dont give any spaces infront of these.
print statements inside 'if' and 'else' should have same tab space or white space as they come under 2nd level.
outer print statement will not have a space because it again comes to 1st level.
Hope this helps
In Python console, everything works fine with a positive number of spaces, or a Tab;
so any of these example will work:
if True:
print('Hello')
else:
print('Not hello')
if True:
print('Hello')
else:
print('Not hello')
if True:
print('Hello')
else:
print('Not hello')
EDIT
For searching where is the problem, try this answer; call
python -m tabnanny <your_script>.py
and you will get an output telling you which lines are the problem.
Example output:
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 12)

python else syntax error

This Python script to process a string is suffering from Syntax error in line 24, else:.
Any ideas as to what it might be?
j=raw_input("Enter a string: ")
import os
def addtoClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
def parse(string):
result=""
lineList=string.split("\n")
for i in range(len(lineList)):
h=lineList[i].split("#")
if len(h)<2:
continue
if len(h)>2:
count=0
for x in range(len(h)):
if x==len(h)-1:
continue
re0=count+len(h[x])+(x*1)
re1=i+1
re3=str(re1)+"-"+str(re0)
result+=str(re3)+", "
count+=len(h[x])
else:
re0=len(h[0])
re1=i+1
re3=str(re1)+"-"+str(re0)
result+=str(re3)+", "
result =result[:-2]
addtoClipBoard(result)
print result
parse(j)
It's probably a problem with the indentation level of the else, make sure to align it at the same level of the corresponding if. Please use a good IDE or text editor to help you catch this kind of errors. As it is, it's nearly impossible to se what you intended to do with the code.
Python uses indentation to define what is inside of a block of code (for,if,elif,while,with) You want to keep everything at the same indentation within the block and then go back a level to write your else statement
Also it doesn't look like your else: statement even belongs there, there is no if statement preceding it that would imply the need for an else are you sure that else is what you want?
Here is my suggestion without knowledge of what you want your code to do, based on observation of patterns
for x in range(len(h)):
if x==len(h)-1:
continue
if (###My condition goes here###):
re0=count+len(h[x])+(x*1)
re1=i+1
re3=str(re1)+"-"+str(re0)
result+=str(re3)+", "
count+=len(h[x])
else:
re0=len(h[0])
re1=i+1
re3=str(re1)+"-"+str(re0)
result+=str(re3)+", "
result =result[:-2]
addtoClipBoard(result)
print result
parse(j)

Python unexpected indentaton error main()

I have no idea how to fix this. I've tried retyping the program.
I get an unexpected indentation error for the last main function.
resident = 81
nonresident = 162
def main():
# initialize counters and total tuition
resident_counter = 0
nonresident_counter = 0
total_tuition = 0
print("Name \tCode\tCredits\tTuition")
print
try:
# open the data file
infile = open('enroll.txt', 'r')
# read the first value from the file
student_name = infile.readline()
# continue reading from file until the end
while student_name != '':
# strip the new line character and print the student's name
student_name = student_name.rstrip('\n')
print(student_name, end='\t')
# read the code type, strip the new line, and print it
code = infile.readline()
code = code_type.rstrip('\n')
print(code_type, end='\t')
# read the number of credits, strip the new line, and print it
credits = infile.readline()
credits = int(credits)
print(format(credits, '3.0f'), end='\t')
# check the room type and compute the rental amount due
# increment the appropriate counter
if code_type == "R" or room_type == "r":
payment_due = credits * resident
resident_counter += 1
elif code_type == "N" or room_type == "n":
payment_due = credits * nonresident
nonresident_counter += 1
elif code_type != "R" or code_type != "r" or code_type != "N" or code_type != "n":
payment_due = 0
# accumulate the total room rent
tuition += payment_due
# print the appropriate detail line
if payment_due == 0:
print('invalid code')
else:
print('$', format(tuition, '8,.2f'))
# get the next studen't name
student_name = infile.readline()
# close the input file
infile.close()
# print the counters and payment total amount
print
print('total number of resident students: ', resident_counter)
print('total number of nonresident: ', nonresident_counter)
print
print('total students: ', end='')
print('$', format(tuition, ',.2f'))
# execute the main function
main()
You don't have an except clause to match the try.
Despite what everyone else is saying, if you have a try, you don't have to have an except: you must have an except or a finally.
That may seem nitpicky, but it's pretty plausible that the code you were copying was actually using finally (e.g., to make sure some cleanup code always gets run—given that it's doing C-/Java-style manual cleanup).
At any rate, adding an except clause is not the right answer. If you're actually looking to handle or ignore errors, then yes, add an except clause. If you're looking for somewhere to add cleanup code that gets run even on an error, add a finally clause instead. If you don't want either, just remove the try line.
you are mixing room type and code type in your if else statement. You are also missing your except statement. This should be your last two lines before calling main.
It should read:
except IOError:
print('an error occurred trying to open or read enroll.txt')
You are using the try statement. It means that you MUST have an except block
try:
some code
except:
pass
It is simplification, but will solve your problem.
The other answers have (correctly) pointed out that you need to have an except to go with your try: (or not use a try altogether). I'm going to try to explain how you could go about debugging similar issues in the future, since these can be very annoying to debug.
Your error message most likely looked something like this:
File "test.py", line 74
main()
^
IndentationError: unexpected unindent
At first glance, that doesn't seem too helpful, and it's definitely not very clear.
The fact that you "tried retyping the program" sounds like you saw IndentationError and thought, "this means my indents are messed up; maybe there's an extra space somewhere or a mixture of spaces and tabs or something." Those are definitely valid IndentationErrors, and retyping the program would fix them, if you didn't make the same typing error again. (On a side note, I believe that any text editor worth using will have the option to convert all of your tabs to 4 spaces to avoid a lot of indent headaches.)
However, looking at the error text, we see "unexpected unindent". To me this sounds kind of like gibberish, but what it means is that, when python was looking at your program, it ran into a line that it thought should be indented more than it was. (Unfortunately, this same kind of error can be called "unexpected unindent" or "expected an indented block", and it can even show up as a plain old SyntaxError: invalid syntax.)
So knowing what the error message means, we can look back through the code to see why python thought that main() was indented strangely- though we have to be careful because python isn't always right about where the problem actually is. Here would be something like my thought process:
There's a function definition right before main() is called, maybe that function wants main() to be inside it? No that isn't it, because python only really expects at least one line of code after a function definition.
What else "wants" code to be indented after it? if, elif, and while all do, but all of them have code after them as well.
The only other "indenter" is try:. At this point, you either know that try: needs to be followed by a except: or a finally: and you fix it, or you don't. If you don't know that, than you could still see that try: is followed by an indented block, and, given that it is a likely culprit for you error, decide that it's time to look up what try: does.
Well I hope that helps troubleshooting problems like this in the future, and check out abarnert's answer and my link for more on handling errors with try/except/else/finally statements.
As noted by LevLevitsky and david above, there's no except clause. The easiest way to solve this is adding a line like the following to your code before the call to main:
except: pass
The second comment I have to your code is more stylistic, but you could add the following, before your call to main and after the except clause:
if __name__ == '__main__':
main()
Besides the missing except or finally or the extra try... If you have a look at the edited code, you can see the strangely mixed color blocks in the indentation. It means that you are mixing tabs and spaces which can lead to problems like bad indentation. The reason is that the interpreter thinks differently about how the tabs should be interpreted (for example 8 vs. 4 column tab stops).
You must not mix tabs and spaces for the indentation. I personally would recommend to use only the spaces. Any decent editor is capable to expand TAB key to spaces and/or Untabify the existing mixture of tabs and spaces.

program for comparisons in python

I'm really new to programming (really, really new) and need help with the basics. I'm trying to write a program with python that will compare the contents of two .txt files, one a reference and the other the source. The contents are a simple random listing of names, and I want it to print out if there are any names in the source that are not in the reference.
I've looked at other stuff on this site but every time I tried it, the terminal would never actually give a result, even if there was a print command in the program.
I also have a hard time reading the language of a program and ascertaining it's exact function, so something with clear directions would be really appreciated.
As far as I have is:
ref = open("reference.txt")
sor = open("source.txt")
list1 = ref.read()
list2 = sor.read()
for i in list2:
if i != list:
print i
ref.close()
sor.close()
And when I try and run this, it says "expected an indented block"? at the 'print i' line. Why?
Please help me out, as I have to teach myself this stuff and am not doing too well.
Thanks.
If you are totally, completely new to programming then it will take you some time to be able to implement what you describe. Take a step back, pour yourself a beverage, and start here. Start at the beginning, and repeat each illustration until you understand.
http://docs.python.org/tutorial/
As previously mentioned, your inner if statement needs to be indented, as
for i in list2:
if i != list:
print i
This requires two indents because it is two nested blocks. As a basic rule of thumb, anywhere you're ending a line with a colon (:), you're starting a new code block, and should be indenting another level. This is so you can un-indent once to end the if block without ending the for block.
However, I doubt this will do what you want based on your description. It's likely you wanted something more like
sourceLines = set(sor.readLines())
for line in ref.readlines():
if line not in sourcelines:
print line
if blocks in python have to be indented, add another level of indent for your print i statement
for i in list2:
if i != list:
print i
These lines read the files as strings:
list1 = ref.read()
list2 = sor.read()
This loop iterates through the string one character at a time:
for i in list2:
This line compares the character to the list class:
if i != list:
I'll answer your indentation error first: you need another 4 spaces before the print statement. In Python indentation is important and you need to indent any block and dedent to end that block.
For your problem I am going to not give you written out code in advance but more of a flow on how to do it:
Create 2 sets (http://docs.python.org/library/stdtypes.html#set-types-set-frozenset)
Read both files into a seperate set (you can do this while iterating over a file and appending to your set).
Compare your two sets using the set1 - set2 syntax (see the link above) to show all items not common to both sets.
Hope you can make it work from this.
Now for the code:
with open('file1.txt') as file1:
set1 = set(line for line in file1)
with open('file2.txt') as file2:
set2 = set(line for line in file2)
print set1 - set2
This uses some principles you are probably not familiar with (look up: list comprehensions, generator comprehensions and the previously noted link about sets which are unique collections).

Categories