Why is python saying else invalid syntax?
I'm having this error: Show
The line which causes the problem is marked with a comment in the code:
To be honest I have no idea why I get this. Before everything was fine and now that error shows up after adding some extra instructions in other indented blocks. Any ideas? Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax Python is known for its simple syntax. However, when you’re learning Python for the first time or when you’ve come to Python with a solid background in another programming
language, you may run into some things that Python doesn’t allow. If you’ve ever received a By the end of this tutorial, you’ll be able to:
Invalid Syntax in PythonWhen you run your Python code, the interpreter will first parse it to convert it into Python byte code, which it will then execute. The interpreter will find any invalid syntax in Python during this first stage of program execution, also known as the parsing stage. If the interpreter can’t parse your Python code successfully, then this means that you used invalid syntax somewhere in your code. The interpreter will attempt to show you where that error occurred. When you’re learning Python for the first time, it can be frustrating to get a You can’t handle invalid syntax in Python like other exceptions. Even if you tried to wrap a SyntaxError Exception and TracebackWhen the interpreter encounters invalid syntax in Python code, it will raise a
You can see the invalid
syntax in the dictionary literal on line 4. The second entry,
Note that the traceback message locates the error in line 5, not line 4. The Python interpreter is attempting to point out where the invalid syntax is. However, it can only really point to where it first noticed a problem. When you get a
In the example above, there isn’t a problem with leaving out a comma, depending on what comes after it. For example, there’s no problem with a missing comma after There are a few elements of a
In the example above, the file name given was There are two other exceptions that you
might see Python raise. These are equivalent to
These exceptions both inherit from the Common Syntax ProblemsWhen you encounter a Misusing the Assignment Operator (=)There are several cases in Python where you’re not able to make assignments to objects. Some examples are assigning to literals and function calls. In the code block below, you can see a few examples that attempt to do this and the resulting >>>
The first example tries to assign the value The second and third examples try to assign a string and an integer to literals. The same rule is true for other literal values. Once again, the traceback messages indicate that the problem occurs when you attempt to assign a value to a literal. It’s likely that your intent isn’t to assign a value to a literal or a function call. For instance, this can occur if you accidentally leave off the extra equals sign ( >>>
Most of the time, when Python tells you that you’re making an assignment to something that can’t be assigned to, you first might want to check to make sure that the statement shouldn’t be a Boolean expression instead. You may also run into this issue when you’re trying to assign a value to a Python keyword, which you’ll cover in the next section. Misspelling, Missing, or Misusing Python KeywordsPython keywords are a set of protected words that have special meaning in Python. These are words you can’t use as identifiers, variables, or function names in your code. They’re a part of the language and can only be used in the context that Python allows. There are three common ways that you can mistakenly use keywords:
If you misspell a keyword in your Python code, then you’ll get a >>>
The message reads Another common issue with keywords is when you miss them altogether: >>>
Once again, the exception message isn’t that helpful, but the traceback does attempt to point you in the right direction. If you move back from the caret, then you can see that the You can also misuse a protected Python keyword. Remember, keywords are only allowed to be used in specific situations. If you use them incorrectly,
then you’ll have invalid syntax in your Python code. A common example of this is the use of >>>
Here, Python does a great job of telling you
exactly what’s wrong. The messages Another example is if you attempt to assign a Python keyword to a variable or use a keyword to define a function: >>>
When you attempt to assign a value to It might be a little harder to solve this type of invalid syntax in Python code because the code looks fine from the outside. If your code looks good, but you’re still getting a The list of protected keywords has changed with each new version of Python. For example, in Python 3.6 you could use Another example of
this is
You can run the following code to see the list of keywords in whatever version of Python you’re running:
>>>
This code will tell you quickly if the identifier that you’re trying to use is a keyword or not. Missing Parentheses, Brackets, and QuotesOften, the cause of invalid syntax in Python code is a missed or mismatched closing parenthesis, bracket, or quote. These can be hard to spot in very long lines of nested parentheses or longer multi-line blocks. You can spot mismatched or missing quotes with the help of Python’s tracebacks: >>>
Here, the traceback points to the invalid code where there’s a
Another common mistake is to forget to close string. With both double-quoted and single-quoted strings, the situation and traceback are the same: >>>
This time, the caret in the traceback points right to the problem code. The Quotes missing from statements inside an f-string can also lead to invalid syntax in Python:
Here, the
reference to the
Python identifies the problem and tells you that it exists inside the f-string. The message This might not be as helpful as when the caret points to the problem area of the f-string, but it does narrow down where you need to look. There’s an unterminated string somewhere inside that f-string. You just have to find out where. To fix this problem, make sure that all internal f-string quotes and brackets are present. The situation is mostly the same for missing parentheses and brackets. If you leave out the closing square bracket from a list, for example, then Python will spot that and point it out. There are a few variations of this, however. The first is to leave the closing bracket off of the list:
When you run this code, you’ll be told that there’s a problem with the call to
What’s happening here is that Python thinks the list contains three elements: Another variation is to add a trailing comma after the last element in the list while still leaving off the closing square bracket:
Now you get a different traceback:
In
the previous example, In this example, Python was expecting a closing bracket ( Mistaking Dictionary SyntaxYou saw
earlier that you could get a >>>
Once again, this error message is not very helpful. The repeated line and caret, however, are very helpful! They’re pointing right to the problem character. This type of issue is common if you confuse Python syntax with that of other programming languages. You’ll also see this if you confuse the act of defining a dictionary with a >>>
You can
use Using the Wrong IndentationThere are two sub-classes of
While other programming languages use curly braces to denote blocks of
code, Python uses whitespace. That means that Python expects the whitespace in your code to behave predictably. It will raise an
This might be tough to see, but line 5 is only indented 2 spaces. It should be in line with the There’s also a bit of ambiguity here, though. Is the
Even though the traceback looks a lot like the The other type of If your tab size is the same width as the number of spaces in each indentation level, then it might look like all the lines are at the same level. However, if one line is indented using spaces and the other is indented with tabs, then Python will point this out as a problem:
Here, line 5 is indented with a tab instead of 4 spaces. This code block could look perfectly fine to you, or it could look completely wrong, depending on your system settings. Python, however, will notice the issue immediately. But before you run the code to see what Python will tell you is wrong, it might be helpful for you to see an example of what the code looks like under different tab width settings:
Notice the difference in display between the three examples above. Most of the code uses 4 spaces for each indentation level, but line 5 uses a single tab in all three examples. The width of the tab changes, based on the tab width setting:
When you run the code, you’ll get the following error and traceback:
Notice the The solution to this is to
make all lines in the same Python code file use either tabs or spaces, but not both. For the code blocks above, the fix would be to remove the tab and replace it with 4 spaces, which will print Defining and Calling FunctionsYou might run into invalid
syntax in Python when you’re defining or calling functions. For example, you’ll see a >>>
The traceback here is very helpful, with the caret pointing right to the problem character. You can clear up this invalid syntax in Python by switching out the semicolon for a colon. In addition, keyword
arguments in both function definitions and function calls need to be in the right order. Keyword arguments always come after positional arguments. Failure to use this ordering will lead to a >>>
Here, once again, the error message is very helpful in telling you exactly what is wrong with the line. Changing Python VersionsSometimes, code that works perfectly fine in one version of Python breaks in a newer version. This is due to official changes in language syntax. The most well-known example of this is the >>>
This is one of the examples where the error message provided with the Another problem you might encounter is when you’re reading or learning about syntax that’s valid syntax in a newer version of Python, but isn’t valid in the version you’re writing in. An example of this is the f-string syntax, which doesn’t exist in Python versions before 3.6: >>>
In versions of Python before 3.6, the interpreter doesn’t know anything about the f-string syntax and will just provide a generic Python syntax is continuing to evolve, and there are some cool new features introduced in Python 3.8:
If you want to try out some of these new features, then you need to make sure you’re working in a Python 3.8 environment. Otherwise, you’ll get a Python 3.8 also
provides the new >>>
This In Python 3.8, this code still raises the >>>
The helpful message accompanying the new ConclusionIn this tutorial, you’ve seen what information the When you’re writing code, try to use an IDE that understands Python syntax and provides feedback. If you put many of the invalid Python code examples from this tutorial into a good IDE, then they should highlight the problem lines before you even get to execute your code. Getting a Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax How do I fix invalid syntax in Python for Else?Remove extra spaces/lines and re-indent the if/else statements.
Why is my Python saying invalid syntax?Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.
Why does else not work in Python?The keyword else needs to be followed by a colon : . Any code that is included as part of the else statement must be indented the same amount. Since a=5 assigns a value to a that is less than 10, a>10 is False and the code under the if statement does not run.
Is else if valid in Python?An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if.
|