End of statement expected python ошибка

The Error Message “End of Statement Expected”

During our Python coding journey, we get a lot of error messages from the compiler or IDE we are using; some of those errors are very tricky and unclear, and others are very straightforward and helpful in repairing our code. One of those clear and straightforward errors is the “End of statement expected” error message.

But errors have more than one type; they can be compile-time errors or run-time errors, and today’s error is a compile-time one.

The error is somewhat self-explanatory: it says there is a statement that the compiler expects to find its end. So, the question now is, what is a statement in Python?

What is a Statement in Python?

A statement in Python is a standalone instruction that Python can execute, which means an assignment statement like age = 20 is a Python statement, and a print statement like print(age)[/py] is also a Python statement.

Reasons for the “End of Statement Expected” Error Message

Reason 1: Python Statements are Not Separated

While coding with Python, the language expects from you one or more Python statements. It also expects you to separate those statements so that Python can execute them correctly without any conflict.

Python uses semicolons for statement separation, but unlike other programming languages that use a semicolon to separate statements, a semicolon in Python is not obligatory; instead, after finishing a Python statement, you can just write the new next statement in a newline as follows:

Python statement that reads: 
age = 20
print(age)

age = 20
print(age)

So, when you write those two above statements without statement separation, as: 

Python statement that reads: 
age = 20   print(age)

 age = 20 print(age) 

You get the error message:

Error message that reads "End of statement expected :1"

Where that error message tells you that there is a problem in a specific line and there are two or more Python statements written without separation. Python expects you to an end for each statement, whereas Python cannot decide by itself where is the end of the first statement and the start of the next one.

So, when you get that error message, you may have to check all statements’ beginnings and ends, then separate statements from each other if needed, and hence the error will disappear.

Python statement that reads: 
age = 20   
print(age)

age = 20
print(age)

Reason 2: Python Statements’ Syntax Errors

Do you think you may get the same error message “End of statement expected” when your program contains only one Python statement? 

The answer is yes. That happens when not writing Python statements themselves correctly, or in other words, when writing Python statements with syntax errors, where Python not only requires statements to be separated properly but to be written correctly as well.

Also, there are many reasons why the written Python statement is syntactically incorrect, also called having a syntax error.

Syntax Error 1: Python Versions’ Syntax Differences

Every day, Python is getting updated and improved, and hence, new versions of the language are being released. That sounds great until you know the consequences of that upgrade.

Nearly every version upgrade of the language results in a bit of change in the language syntax. One of the Python statements that is affected by those upgrades is the print statement from Python 2, which becomes a print function in Python 3.

And for simplicity, the apparent difference in the syntax between the print statement from Python 2 and the print function from Python 3 is that in Python 2, when printing any text, for example, printing “Hello world,” you just type that line of code:

code that reads print "Hello world"

 print "Hello world" 

While in Python 3, the printing function requires enclosing the data to be printed within a pair of parentheses, like that line of code:

Code that reads print ("Hello world")

 print ("Hello world") 

So, if you upgrade the Python version on your device to Python 3, you can only use the Python function [with parentheses], but you cannot use the Python statement anymore [without parentheses]; otherwise, the Python IDE will show the “End of statement expected” error message:

Error message that reads "End of statement expected :1"

Syntax Error 2: Control Flow Statements with Too Much Indentation

Each of Python’s control flow statements, like simple if, if-else, nested if, or if-elif-else statements, requires a proper indentation. Some of them have to be at the same indentation level as each other, and some others may have to get one indentation to the right, and whatever the case you’re facing, you have to use indentation wisely.

Where having too many indentations than required will result in the same mentioned error message “End of statement expected”.

Suppose we have those lines of code with the if-elif-else control flow statement:

if-elif-else control flow statement that reads: 
x = 5
if x < 5: 
   print("x is smaller than 5")
elif x > 5: 
   print("x is more than 5")
else:
   print("x is exactly 5")

x = 5
if x &< 5: 
   print("x is smaller than 5")
elif x &> 5: 
   print("x is more than 5")
else:
   print("x is exactly 5")

The statement works perfectly since the indentation here is correct, where each of “if,” “elif,” and “else” has to be at the same indentation level.

But, if one of them is got indented by one or more indentations as follows:

if-elif-else control flow statement that reads (with different indentation): 
x = 5
if x < 5: 
   print("x is smaller than 5")
elif x > 5: 
   print("x is more than 5")
else:
   print("x is exactly 5")

x = 5
if x &< 5:
    print("x is smaller than 5")
        elif x &> 5:
            print("x is more than 5")
else:
   print("x is exactly 5") 

The Python IDE will shout with the error message:

Error message that reads "End of statement expected :4"

Syntax Error 3: Returning Python Statements Rather Than Expressions

In all programming languages, the return keyword is used inside functions to return or save the output of the function, where that returning is done just by writing the keyword “return” followed by the value or the output of the function to be returned as follows:

Output function that reads:
def increment_x ( ):
x = 5
x += 1
return x

def increment_x ():
x = 5
x += 1 
return x

In the above code snippet, we make a function that increments the value of x by 1, then make the function return the new value of x. But what if we try to make the increment as well as the return in one line as follows?

Output function that reads:
def increment_x ( ):
x = 5
return x += 1

def increment_x (): 
x = 5   
return x += 1

The IDE will shout again with the same error message:

Error message that reads "End of statement expected :3"

But what is the reason for that? The answer is simple: Python returns only expressions, not statements [x +=1 is an augmented assignment statement], so trying to return a statement, as in our case, will lead to getting the error message “End of statement expected.” But in that example, you can still return the incrementation directly rather than incrementing and then returning the new value. You can do that using Python 3.8 assignment expression, also known as “the walrus operator” as follows: 

Output function that reads:
def increment_x ( ):
x = 5
return x := x + 1

def increment_x (): 
x = 5
return x := x + 1

Other Forms of the “End of Statement Expected” Error Message

Although different Python editors or IDEs have the same Python rules for separating statements or writing them correctly, they may differ a little bit in the form of the error message for that error type.

Where you can still get the same error message “End of statement expected” if you are using the PyCharm IDE, but when using VS Code, you may get a different error message such as “Statements must be separated by newlines or semicolons” instead.

Summary

Finally, when you face an error message like “End of statement expected” or “Statements must be separated by newlines or semicolons,” depending on the IDE you’re using, you have to check two main things: firstly, check that every Python statement is separated from its previous or next statement, and secondly, check that all Python statements are free from any syntax errors, either syntax errors due to changes in the syntax from a version to another, or having too much-unneeded indentation while using control flow statements, or even maybe you’re trying to return a Python statement rather than expression.

Tagged with: compile-time errors, elif, else, end of statement, end of statement error, Error, Errors, IF, print statements, Pyhton 3, python, Python 2, Python statements, run-time errors, statements

Why am I getting this error

Why am I getting this error (see linting) saying ‘End of statement expected’ in pycharm?

I am very new to python.

asked Jun 5, 2018 at 5:18

JavaYouth's user avatar

JavaYouthJavaYouth

1,5367 gold badges21 silver badges39 bronze badges

6

1 Answer

Try print with parenthesis in Python3 i.e. print(x) instead of print x

answered Jun 5, 2018 at 5:30

niraj's user avatar

nirajniraj

17.5k4 gold badges33 silver badges48 bronze badges

Writing code is a constructive process in which we tend to make mistakes and sometimes these mistakes throw out specific errors.

Errors are nothing but mistakes that are identified by the compiler or the interpreter at run time. Various errors occur in Python, which we will study in depth as ‘End of Statement Expected Error’.

Introduction to Python

Python is an established trend in the industry. It is gaining popularity due to its easy and user-friendly syntax,  endless libraries that make working on it easy, and Python is extremely easy to understand.

Python has a very robust error-handling mechanism that identifies that something is going wrong whenever we write a wrong code, and then it throws a relevant error which is very self-explanatory and understandable.

To know more about Python programming follow along with the linked article.

Importance of Understanding and Handling Errors in Python

Consider a situation where you have an error in your code, and whenever an error is found, the code just stops execution abruptly, and the process fails, leaving the program in an unstable state. This situation is very dangerous when working on a big project.

Error handling allows us to give an alternate way to the interpreter so that if an error occurs, there should be an alternate way to execute and the code should not execute abruptly, and the program should be in a stable state.

To add an error-handling mechanism, we need to understand what error we are handling, as we know that to solve a problem, it is very important to first understand that problem and then be better equipped to solve it. In this case, the error is the problem, and then error handling is the solution to that problem.

Hence it is important to understand the error and how these errors occur and then move ahead to understand how we can resolve these errors.

‘End of Statement Expected’

The ‘end of statement Expected’ is a common syntax error in Python, which occurs due to various reasons we will discuss extensively in the sections ahead.

This error mainly triggers when we do not follow the programming language’s syntax. Let’s understand and figure out how this ‘end of statement expected’ error occurs and likewise take a look at measures to avoid these errors.

The syntax is nothing but the way or the structure in which a certain language needs to be written. It is pre-determined by the programming language developers and cannot be changed after that. Syntax defines a set of rules to be followed when writing code in that specific language.

Syntax Rules

Python has certain specific rules with regard to syntax, which are pre-defined and cannot be changed. Python syntax is relatively easy to understand as it usually reads as normal English.

Some Important rule is as follow:

When using conditional statements, loops, functions, and classes, python expects indentation so that it identifies which piece of code belongs to which block.

Most programming languages that are being used require a semi-colon(;) so that the end of the statement is understood, but Python doesn’t require any sem-colon.

Comments in Python are shown in two methods: one is a single line which uses a hash(#), and the other is a multi-line, which is done using six double quotation marks (“”” ”””).

To get a better idea of Python syntax, you can check out The Python Tutorial.

Significance of Indentation and White-Spacing

Python follows a standard called PEP 8 which we will be discussing later, but for now, it is just a format in which Python code needs to be written.

Writing clean and understandable code was one of the major reasons behind the development of the Python programming language; indentations and white spacing play a very crucial role in maintaining readability and keeping the code clean. Indentation and white-spacing form an important part of Python syntax.

Statements in Python

Statements are the basic building blocks of Python code; everything from printing output to displaying output and something very basic, from assigning value to a variable to writing functions, can be considered a statement.

Some examples of statements are given below:

def greet(a):
      print("Hello", name)

These small units come together and form a Python program, as shown below.

def greet(a):
      print("Hello", name)
name = "George"
greet(name)

Statements Example

Statements Example

What is the ‘End of Statement Expected’ error?

This is a common error that is triggered when there are some mistakes in following the syntax. When the Python interpreter expects some specific symbols or characters at the end of a certain statement, it will throw this error.

We will see the different situations where this error can be triggered and see how to fix this error.

Causes of ‘End of Statement Expected’

Missing colons

Python’s basic syntax expects semi-colons at the end of every condition statement and loop

Below is an example of this error:

The above code will give the following error.

Missing Colo Eg

Output for a missing semi-colon

To fix this, we will simply add a semi-colon, and the error will be fixed.

if 10 == 10:
    print("YES")

Colo Eg

Output After adding a semi-colon

Incorrect Indentation

As we have discussed that indentations are important while writing Python code, if we are unable to indent code properly, it will error out.

Below is an example of this error:

if 10 == 10:
print("YES")

The above code will throw the following error.

Incorrect Indent

Output for Incorrect Indent

To fix this, either press the space bar 4 times or just press the tab once before the statement, which is not indented properly, as shown below:

if 10 == 10:
    print("YES")

Correct Indent

Output for Correct Indent

Missing Parenthesis

Parenthesis always exists in pair; forgetting to write one of the two will lead to an error, as shown in the below example:

Missing Paranthesis

Missing Parenthesis

An easy fix to this problem will be putting in the missing parenthesis.

Complete Parenthesis

Complete Parenthesis

Mismatch quotes in strings

We know that Python accepts strings via both double and single quotations, but it should either be single quotes or double quotes, not both in combination, do this will lead to the following error:

Quotes Mismatch

Output for Quotes Mismatch

To resolve this error, just identify the mismatch and choose either of the quotes and replace it with the matching quote as shown below:

Quotes Match

Output for Matched Quotes

Understanding Code-Blocks

What is a code block in Python?

A set or a group of statements that can be interacted with using a single name is called a code block. Conditional statements, loops, functions, and classes can be treated as the entry point of this code block. Every code block has an entry point, actual body, and exit point. We shall understand it better with the help of an example.

def calc(a,b, op):

	if op == '+':
		return a+b
	if op == '-':
		return a-b
	if op == '*':
		return a*b
	if op == '/':
		return a/b

I have implemented a simple function, this function takes two integers and one character as input parameters.

The above code is 10 lines long, but in practice, it can be accessed using a single line and a single name, as shown below:

As we can see, the above 10 lines of code are being treated as a single unit of code, which is nothing but a code block.

How can blocks be identified with indentation?

Python follows a formatting procedure in which a set of four spaces form an indent, and an element with the same number of indents belongs to the same block.

When a new block is encountered, the indentation level increases, and after successful execution, the block is exited, and the indentation level decreases.

In this way, you can identify which statement belongs to which code block with the help of indentation. Code blocks are determined with the help of indents.

Importance of Code-Blocks

Having well-maintained and properly indented code blocks is always a good practice to follow. As well organized code is easy to read and understand and looks very pleasant to see.

It becomes easy to track the flow of control and determine and identify bugs and errors, if at all there are any, in our program.

Best Practices to avoid the ‘End of Statement expected’ error

Using code editor with automatic indentation

Modern code editors or IDEs are well equipped with tools and extensions that assist you while writing code.

They become very handy as often they automatically add indents to places where required and give the code a proper format as per the language’s syntax. A code editor with excellent tools and extensions is an absolute life save for any developer.

Following the PEP 8 Guidelines

PEP 8 stands for Python Enhancement Proposal 8; it is a set of guidelines laid down by the Python community to set some standard practices for writing code to maintain the readability of code and keep the code clean

Some important guidelines in context to our point of concern are: 

Four spaces are identified as an indentation

Binary operators need to be padded by single spaces from both sides, i.e., before and after

The top level of functions needs to have two blank lines.

Consistent Indentation Practice

Inconsistent tabs, spaces, and incorrect indentation will lead to an ‘End to Statement Expected’ error. So it is important to follow a consistent format of using indents and stick to the guideline mentioned in PEP 8 to avoid these syntax errors.

Conclusion

Importance of Clean Code

As developers, it is important to understand the necessity of well-readable and understandable code as it is easy to work ahead and maintain such code rather than shabby and untidy code, which is not appreciated by anybody.

Hence it is important to have a clean and tidy code so that even when we work in a team environment others will be able to handle and work on our code and make things easier.

Summary

To conclude this article, let’s summarize whatever we’ve been through in this article. To begin with, we brushed up our knowledge about Python and its basic syntax. We also understood the importance of using indentations effectively in depth.

Later on, we took a deep dive into the ‘End of Statement Expected’ error, we saw the different reasons why the error occurs, and we also resolved those issues with examples.

We took an overview of what a code block is, then we came on to the best practices to be followed to avoid syntax errors, understood what PEP 8 is, and also the importance of maintaining clean code.

Reference

Stackoverflow Query

unexpected error even though there is no syntax error in the statement.

i have tried restarting Pycharm.
i tried coping and pasting the code into new tab where every word is pasted in a new line somehow.
can anyone help me find the issue?

this is the image of the error. https://i.stack.imgur.com/Gx8qZ.png

asked Sep 22, 2020 at 18:50

yadavender yadav's user avatar

1

Check to make sure that the name of your variable doesn’t contain any spaces. I recommend using snake or camel casing.

total_number_of_times = 1 #snake
totalNumberOfTimes = 1 #camel

answered Sep 22, 2020 at 19:00

Alvan Caleb Arulandu's user avatar

I am creating a line shapefile from a csv in a Python (2.7) script. I am assigning an ID field from the csv to a variable and then later using it in the Calculate Field tool. The ID field originally looks like this ‘011947-OCT-084’ which ArcGIS(10.1) does not seem to like, so I removed the ‘-‘s and when I use that variable in the tool I get an error:

ExecuteError: ERROR 999999: Error executing function.
Expected end of statement
Failed to execute (CalculateField).

Here is my code («temp» is the shapefile temporarily stored in in_memory):

with open(inCSV, 'rb') as input:
    with open(outCSV, 'wb') as output:
        csvwriter = csv.DictWriter(output, headers, delimiter = ',')
        csvwriter.writeheader()
        for row in csv.DictReader(input):
            uniqueID = row['Common_id']
            newID = uniqueID.replace("-", "")
            arcpy.AddField_management("temp", "uniqueID", "TEXT")
            arcpy.CalculateField_management("temp", "uniqueID", newID)
            row['Common_id'] = newID
            csvwriter.writerow(row)

I’m not entirely sure what the cause behind this is, as I’ve used variables in the Calculate Tool field before without a problem. Thoughts?

Понравилась статья? Поделить с друзьями:
  • End lock ошибка на стиральной машине haier
  • End if without block if ошибка vba
  • End hot ошибка на рефрижераторе кариер
  • Encountered a sharing violation while accessing ошибка
  • Encoding python ошибка