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,4967 gold badges21 silver badges38 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.3k4 gold badges33 silver badges47 bronze badges

Последняя строка в блоке функции вызывает синтаксическую ошибку (end of statement expected). Если не затруднит, опишите пожалуйста причину возникновения ошибки

running = True

def center():
    s = input('Введите строку: ')
    if len(s) > 10:
        print(s.center(len(s)+2, '_'))
    elif (len(s)%2) == 0:
        print(s.center(10,'_'))
    else:
        print(s.center(9,'_'))
    question = input('Закончить программу?')
    if question == 'да':
        global running = False #Синтаксическая ошибка

while running:
    center()

enter image description here

I have the following variable assignment:

xpath_query="xpath='//a[@id="mylink"]'"

This is giving me an error in my pycharm editor and giving a syntax error when I run this code. What am I doing wrong?

when I hold the cursor over the red squiggle it says:»end of statement expected «

asked Oct 17, 2014 at 15:42

user1592380's user avatar

user1592380user1592380

33.7k89 gold badges279 silver badges505 bronze badges

1

You have double quotes inside your » » block. so it becomes:

«xpath=’//a[@id=» <— stick together with —> «]'»

Hence it is a string syntax error.

To include " inside " " block, you can use to escape the character:

xpath_query="xpath='//a[@id="mylink"]'"

answered Oct 17, 2014 at 15:59

Anzel's user avatar

AnzelAnzel

19.7k5 gold badges50 silver badges52 bronze badges

0

Codecademy Forums

Loading

Понравилась статья? Поделить с друзьями:
  • Encryption unsuccessful как исправить ошибку
  • Encrypting minecraft ошибка
  • Encountered an improper argument ошибка как исправить
  • Encountered a sharing violation while accessing ошибка
  • Encoding utf 8 ошибка