Python 3 syntax error invalid syntax - python

With this code I am trying to generate simple multiplication tables. The program should ask for input and multiple that number in a range up to 15 and the generate the multiplication table for the number. After the if_name_ == 'main': line I end up with a syntax error after the colon. I normally program in python 2, so python 3 is a bit new to me but I'm not sure what the difference is. Below I have listed the short but full code. Any help would be much appreciated.
'''Multiplication Table'''
def multi_table(a):
for i in range(1,16):
print(' {0} x {1} = {2} '.format(a, i, a*i))
if_name_ == '_main_':
a = input('Enter a number: ')
multi_table(float(a))

if_name_ == '_main_':
a = input('Enter a number: ')
multi_table(float(a))
should be :
if __name__ == "__main__":
a = input('Enter a number: ')
multi_table(float(a))
Notice that both variable __name__ and __main__ has two underscores around them and that there must be a space between the if keyword and the start of the condition.

As #Maroun Maroun said right, it has to be if __name__ == "__main__" . But you wont need it. Just write it at the bottom :
'''Multiplication Table'''
def multi_table(a):
for i in range(1,16):
print(' {0} x {1} = {2} '.format(a, i, a*i))
a = input('Enter a number: ')
multi_table(float(a))
Should work, too.
EDIT: In the official docs :
https://docs.python.org/3/library/main.html
if __name__ == "__main__":

In the example provided, (i) there's a space missing after if, and (ii) the symbol's name should have two pairs of underscores: __name__. If these two corrections resolve your problem, great.
But in case you still have another more mysterious unresolved syntax error, then read on...
Recently I encountered a very similar error message, and it was hard to root-cause, since the error message seems to point in the wrong direction. The error seems to indicate that the syntax error lies at the end of the if statement. However, with Python 3.x I noticed that in case a parentheses mismatch error happens in a python source file, the error might be reported at the beginning of the next block rather than where the mismatch actually occurs.
It's worth checking for mismatched parentheses in the entire source code file, prior to the if statement. Check if all your (s are matched by a closing ).

Related

User inputs reserved keyword in Python. There happens an error

I am working on a simple program (just for a joke). A program wants that the user input yes or no (it can be in different languages). But when he enters a reserved word (i. e. keyword) there happens an error because this keyword does some bugs in the code.
My truncated code (maybe it seems unclear because it's truncated):
x = input('Enter yes or no (you can do this in different languages...) ')
x = x.lower()
answersYes = ['yes','si','oui','ioe','inde','tak','ja','da']
answersNo = ['no','ayi','che','leai','nie','ne','nein']
if ' ' in x:
print('Input just one word!')
else:
if x in answersYes:
print('You enteres YES!')
elif x in answersNo:
print('You enteres NO!')
else:
print('Sorry, but this isn\'t YES nor NO!')
I have done some googling around, but there was no luck yet.
Thank you a lot for any answer!
P.S.
Just one little note:
When I have run the upper script in Python in basic Python IDLE, there wasn't any error, but when I have run this in Spyder, there displayed this message (when I typed 'yes in no' ("in" is a reserved word)):
File "<ipython-input-49-d1e48c3ddecb>", line 1
yes in no
^
SyntaxError: invalid syntax
I don't get an error. Make sure your spyder is python3-configured or try running with python3 file.py
You can also try replacing input() with raw_input()

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 Blackjack Run module IDLE error?

I try to run the following module written for a blackjack 21 game in Python but get an error saying:
Unindent does not match any outer indentation level.
Questions
Please help resolve the error.
Also is there a stable option to run modules and get them checked with a python checker which I know there is but an easy to use one without adding code in python , just running it to check where the code got broken?
example
if the screenshot is unclear:
koloda = [6,7,8,9,10,2,3,4,11] * 4
import random
random.shuffle(koloda)
print(' Lets play blackjack, shall we? ')
count = 0
while True:
choice = input(' Will you pick another card? y/n\n ')
if choice == ' y ':
current = koloda.pop()
print(' You got a higher card %d ' %current)
count += current
if count > 21:
print(' Sorry, you lost ')
break
elif count == 21:
print(' Congrats, you got 21! ')
break
else:
print(' You have %d points. ' %count)
elif choice -- 'n':
print(' You have %d points and you ended this game. ' %count)
break
print('See you again!')
Thanks in advance
Your indentations are inconsistent. In python, you can choose how you indent blocks (e.g. tabs, 4 spaces, 3 spaces...), but you should always stick to your initial choice. Otherwise you'll get indentation errors.
Regarding your other question, there are many IDEs that will report syntax errors (such as the ones in your code) while writing. I like Pycharm, but you can choose anything you like. PyCharm also has an option to convert indentation between spaces and tabs, which can help you fix your code.

Invalid Syntax and I don't know why

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.

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.

Categories