Python Syntax Errors

Welcome to chapter 8 of our python tutorial. In the previous chapter, we learned about Python numbers and how to use them in expressions. Throughout this chapter, you'll look at frequent examples of incorrect Python syntax and learn how to fix them.

At the end of this tutorial, you will:

  • Distinguish incorrect syntax in Python
  • Get familiar with SyntaxError tracebacks
  • Fix improper syntax or avoid it altogether

In Python, what is an invalid syntax?

Before transforming your Python code to Python byte code, the interpreter parses it. The parsing stage is where the interpreter searches for any instances of improper syntax in the program. Using the wrong syntax in your Python code will lead the interpreter to be unable to decipher it. The interpreter will try to show you exactly where the issue occurred.

Learning Python and encountering a SyntaxError can be a frustrating experience. If you're having trouble figuring out where the grammatical errors are, Python can provide you with a traceback that can be helpful. It's not uncommon for the resulting code to be nothing short of spectacular.

Please keep in mind that even if your code is syntactically valid, you may encounter other issues.

In Python, unlike other exceptions, improper syntax cannot be tolerated. Even if a try and except block was used to enclose code with incorrect grammar, the interpreter would still throw a SyntaxError.

Traceback SyntaxError

When an erroneous syntax in Python code is encountered by the interpreter, SyntaxError is thrown, and a traceback is supplied with some important information to aid in tracking the issue. Here's a Python script using the wrong syntax:

Line 4 of the dictionary literal contains a syntax error. There is no comma after 'Jim' in the second entry. Running this code in its current form would result in the following error message:

According to the traceback message, the fault does not line 4, but line 5. The Python interpreter highlights any errors in the syntax. However, it can only accurately pinpoint the moment when a problem was first discovered. If you receive a SyntaxError traceback and the code it refers to appears to be correct, works backward until you figure out what is wrong in your code.

In the example above, depending on what comes after it, it is not an issue to leave out the comma. A missing comma following the name of the person in line 5 ('michael') is not an issue. The interpreter, on the other hand, can only point you in the direction of the first thing it couldn't understand.

A SyntaxError traceback contains a few features that can assist you to figure out where your code has the incorrect syntax:

  • The name of the file containing the invalid syntax.
  • A description of the error, including the line number and exact location in the code that caused it.
  • Caret () on the line below the repeated code shows the problematic position.
  • The error message appears after the exception type SyntaxError, which may provide useful information for solving the problem.

There was a caret in the dictionary key at the end of Michael's closing quotation in file name theofficefacts.py, line number 5. The SyntaxError traceback may not be the root cause of the problem, but it will be the first time the interpreter fails to understand the syntax.

Python also throws two additional exceptions. They're similar to SyntaxError, but they're called something else:

  • IndentationError
  • TabError

Both of these exceptions derive from the class named SyntaxError, although they only apply in special cases involving indentation. When your code's indentation levels aren't aligned, an IndentationError is thrown. When tabs and spaces are used together in the same file, a TabError is thrown. A detailed discussion of these exclusions will be provided in the next section.

Which are the common syntax errors?

When you first run into a SyntaxError, it's a good idea to look into what went wrong and how you may correct the Python code's syntax. Some of the most common causes and fixes for SyntaxErrors are covered in the following sections.

Misuse of Assignment Operator (=)

In Python, there are several situations where you won't be able to assign values to objects. Assigning to literals and calling functions are two instances. You can see a few examples of this in the code block below, along with the SyntaxError tracebacks that result:

In the first example, the value 5 is assigned to the len() method. In this case, the SyntaxError warning is really valuable. It notifies you that you can't give a function call a value.

In the third and second examples, literals are assigned a string and an integer, respectively. For other literal values, the same rule applies. According to the traceback messages, the issue appears to be caused by trying to set the value of a literal to a specific value.

Take notice that the traceback fault isn't indicated in the previous samples by caret () and repeated code line. You'll notice a different error and traceback depending on whether REPL is being used or running the code from a file. As you've seen in earlier examples, an error caret would indicate where the problem would be in the file if the code was contained therein.

Using a function or assigning a literal value is extremely unlikely. This can be caused by removing one equal symbol (=) from the expression, which transforms the assignment into a comparison. A comparison like the one that follows might be useful:

A Boolean expression may be the cause of Python's warning that you're assigning a value to a variable that cannot be assigned to. While assigning an object's value (which you'll learn about in the next section), you may encounter this same problem.

Misuse of Python Keywords, Spelling Errors, and Omissions

When using Python, you'll want to stick to terms that have a specific meaning. Identifiers, variables, and function names cannot contain any of the words listed below. The only environment in which they can be utilized is within Python.

There are three typical ways that you might improperly utilize keywords:

  • Spelling error of a keyword
  • Omission of a keyword
  • Use of keywords incorrectly

If you misspell a term in your Python code, then you’ll get a SyntaxError. For instance, this happens when you spell the keyword "for" wrong:

There is a notification that reads "SyntaxError: incorrect syntax," but it doesn't provide much assistance. Using the traceback, you can go back to the point where Python first discovered an issue. To fix this problem, check your Python code to make certain that all of its keywords are spelled correctly.

Another typical issue with keywords is when you overlook them altogether:

Because of this, traceback does its best to direct you to where you should be looking. You'll see that the for-loop syntax lacks the in keyword when you step back from the caret.

You could potentially make a mistake with a Python keyword that is protected. The use of keywords is restricted to specific contexts. The incorrect syntax will result if you use them incorrectly.

'Continue' or 'break,' for example, are frequently used outside of a loop. When you're working on something and move logic out of a loop, it's easy to run into this problem:

Python does an excellent job of describing what's wrong in this scenario. The messages "'break' outside loop" and "'continue' not suitably in the loop" will guide you to the next step. Python would have the caret pointing to the incorrect sentence if the code was stored in a file instead.

Another possibility is to use a keyword to construct a function or to attach a Python keyword to a variable:

If you attempt to set the value of pass or create a new function called pass, you will receive a SyntaxError and an "invalid syntax" message.

Because the code appears to be fine from the outside, it may be tough to correct this type of poor syntax with Python programming. A SyntaxError may occur even if your code appears to be correct. In this case, look up the variable or function name in the Python version's keyword list.

Every time a new version of Python is released, the list of protected keywords grows. The term "await" has been introduced to the list of keywords in Python 3.7 and is now available as a variable or function name in Python 3.6. Any attempt to use await as an object name in Python 3.7.1 or later will result in an error.

Another difference between Python 2 and Python 3 is the print function:

A value can't be provided for print in Python 2, since it is a keyword. The built-in function can take values in Python 3, though.

Running the following command in any Python version will return a list of keywords.

In addition, the keyword offers the relevant keyword .iskeyword(). Using the one-liner below, you can rapidly verify the value of the pass variable.

Your identification will be immediately flagged as either keyword or not by this code.

Missed brackets, parentheses, and Quotes

A missing or mismatched terminating parenthesis, bracket, or quotation is frequently the root of erroneous syntax in Python code. As a result, it may be difficult to tell nested parentheses from the rest of the text, especially in long lines. It is possible to discover mismatched or missing quotations with the use of tracebacks provided by Python.

The traceback leads to the wrong code, which includes a t' after a single closing quotation. One of two adjustments can be made to correct this:

  • Using backslash to escape a single quote ('don\'t')
  • Using double quotes to surround the entire string ("don't").

The failure to terminate the string is also a common problem. Regardless of whether a string is double-quoted or single-quoted, the following is true:

In the traceback, the caret now points straight to the incorrect code. "EOL during scanning string literal" is explicit and helpful in identifying the issue in the SyntaxError notice. Before a string may be ended, an interpreter must reach the end of a line. To remedy this, add a quote at the end of the string that is identical to the one you used at the beginning. In this scenario, there would be a double quotation (").

Syntax errors can also be caused by missing quotes from statements within the f-string:

An error has occurred when it comes to f-string output. The double quotation marks at the end of the age dictionary reference have been left out. The resulting traceback is as follows:

The f-string contains the problem, and Python tells you about it. The error message "unterminated string" also clarifies the situation. The caret simply symbolizes the beginning of the f-string in this example.

This isn't as beneficial as when the caret points to the f-issue string's area, but it does assist narrow down where you need to search. Inside that f-string, there's an unterminated string. All you have to do now is figure out where. Remove the error by including all of the f-string quotes and brackets inside.

Except for removing parenthesis and brackets, the scenario is essentially the same. An error message will appear if the ending square bracket of a list is left out in Python. There are, however, several variations on this theme. The first option is to leave out the final bracket:

There will be an error message when you run the above code when there is a problem with the print() call.

Print(foo()) returns a list with three items: 1, 2, and 3 according to Python. It employs whitespace to logically order things, and because 3 and print(foo()) don't have a comma or bracket between them, Python combines them as the list's third entry.

After the final item in the list, you can use a trailing comma instead of a closing square bracket:

Now you receive a different traceback

Previously, 3 and print(foo()) were combined into one component, but now there is a comma between them. The print(foo()) command has been added to this list because Python has reached its conclusion of the file without a final encasement. An EOF error was returned by Python, which was expecting a different outcome.

The repeated line and caret aren't very useful in this scenario because Python was anticipating a closing bracket (]). Python has a hard time detecting missing brackets and parenthesis. Starting with the caret and working backwards is sometimes the only way to figure out what's missing or incorrect.

Conclusion

Congratulations! You've made it to the end of this tutorial. You've been exposed to a few reasons why you may face syntax problems when programming in Python, and so in the following chapter, we will look at a few additional reasons for syntax issues. With this, you can create Python code with fewer syntax problems. Let's meet in the next tutorial for more.

Comparator Operators in Ladder Logic Programming

Hi friends. Today we are going to go through one of the most commonly used topics in writing ladder logic programming which is using comparator operations. This includes the logical and mathematical comparison between variables to decide where the logic goes.

There are many comparator operations like equal (==), not equal (<>), less than (<), greater than (>), less than or equal (<=), greater than or equal (>=). All these comparator operations might be used in different logic scenarios while writing a ladder logic program. In this tutorial, we are going to go over each operator showing the input operators and output as well. In addition, we will practice some examples with the simulator to familiarize how to use them flexibly while developing ladder logic programs.

Input and output parameters of Comparator operations

Because they are used for comparing two the value of input variables, there will be two operators which are being compared. these input variables could be of any data type i.e. integer, real, boolean, character, string et cetera. And the output will be a boolean data type which denotes true or false, or “0” or “1”. As shown in Fig. 1 a typical comparator operator has two operands and one output which is called the result of logic (RLO).

Fig. 1: Comparator operation bock diagram

Table 1 lists examples for one of the comparisons between two variables of different data types and their output. In table 1, a typical example of “==” comparator operation between two strings considering the case sensitivity. The first column shows the values of the first operand and the second column shows the values of the second operand while the result of a logical operation (RLO) is represented in the third column. Now let us go over the station of each comparator operation for elaborating their operators, result, and give an example with simulation.

Table 1: example of comparator operation’s operands and RLO

Equal operator (==)

The equal operator is used to check if two operands are equal or not. The input operands’ datatype could be any of the possible data types in the language you are using. For example, Table 2 shows the parameters of the Equal operator in siemens S7. As you can notice, the input operand’ datatype can be any of the listed data types in the third column. One thing we need to highlight here is that datatype could be an array or structure of elements of the basic datatypes. For example, it could be an array of integers. In this case, the comparison will be conducted between every single element in the array of both operands. And if any of these elements have been found not match their equivalent in the other operand, the RLO will be false. Furthermore, the comparison not only does it apply to variables but also could be conducted between memory areas as shown in the third column. It can be used to compare input, output, marker, counter, timer memory data.

Table 2: the parameters of the Equal comparator operator

Example of equal comparator operation

Figure 2 depicts an example of an Equal comparator operation. .it compares literal constant with the variable of type integer saved in marker memory MW4 which is the location of a memory word.

Fig. 2: Example of Equal comparator operator

Figure 3 shows the simulation result of an example of an equal comparator operator. In the case of operands are not equal as in the example shown by fig. 3. The first operand is equal to 5 while the second operand is “0”. So the RLO shows false or “0”.

Fig. 3: simulation result of equal comparator operation when its operands are not equal

Figure 4 shows the simulation of an equal comparator when its operands are equal. The RLO is true or “1”. So the output coil is TRUE.

Fig. 4: simulation result of an equal operator when operands are equal

Not equal comparator operator

This operator is used to compare two operands. When they are not equal it produces positive RLO with High logic and when they are equal it returns false or “0”. Figure 5 shows the test result on the simulator of the NOT operator when the operands are equal. It returns RLO with “0” or false.

Fig. 5: simulation result of Not equal operator when operands are equal

On the other hand, fig. 6 shows the result of the simulation of the NOT operator when its operands are not equal. It gave RLO with logic Tru or “1”.

Fig. 6: simulation result of an equal operator when operands are equal

Greater-than “>” comparator operation

The greater than comparator operator is used for checking if operand 1 is greater than operand 2 or not. Figure 7 shows the rung of a ladder logic program that utilizes greater than comparator operation in which two operands of the integer data type are compared using the greater-than operator. The first operand is at memory location MW4 and the second operand is at memory location MW2. And the RLO represents the retuned result of the greater than comparator operation.

Fig. 7” ladder logic rung example of usage of greater-than comparator operation

Figure 8 shows the results of greater than comparator operation when operand one B is not greater than operand A. on the left side of the figure, it shows the case when both operands are equal and the right side shows the case when operand one is less than operand 2. In both cases, greater than operator sees its condition is not fulfilled so it returns false or “0” at the RLO and hence the output is false.

Fig. 8: simulation results of a greater-than operator when operand 1 is not greater than operand 2

Less-than “<” comparator operation

The less than comparator operator is used for checking if operand 1 is less than operand 2. Figure 9 shows a rung of a ladder logic program that utilizes less than comparator operation “A<B” in which two operands of the real data type are compared using the less-than operator. The first operand is at memory location MD8 and the second operand is at memory location MD12. And the RLO represents the retuned result of the greater than comparator operation. Also, it shows that, when oper1 is not less than oper 2, the result of logic output RLO is false and output is not activated.

Fig. 9: ladder logic rung example of usage of less-than comparator operation

Figure 10 shows the results of less than comparator operation when operand “oper1” is less than operand “oper2” the returned RLO is high or “1” and the output is activated. Now, one may question the case if the two operands are equal? Well that is is a good question and the case of equality between the two operands is considered false for both less than and greater than comparator operations.

Fig. 10: simulation results of less than operator when operand “oper1” is less-than operand “oper2”

Please see fig. 11 which shows the less comparator operation returns false when the two operands are equal. The next section will show the case of greater than or equal comparator operators “>=” and the less-than or equal comparator operator “<=”. In those cases, the equality between the two operands is included and the returned RLO is True or “1”.

Fig. 11: the less-than operator returns false when the two operands are equal.

 

Greater-than or equal comparator operator “>=”

Figure 12 shows a run in a ladder logic program that uses greater-than or equal “>=” operator. As you can see, the output shows true when the two operands are equal.

Fig. 12: greater-than or equal “>=” when two operands are equal

Less-than or equal comparator operator “<=”

Figure 12 shows a run in a ladder logic program that uses less than or equal “<=” operator. As you can see, the output shows true when the two operands are equal.

Fig. 12: the less-than or equal “<=” when two operands are equal

In-range comparator operator

Do all comparator operations take two operands? The answer is almost yes. However, there are very few operators that take only one operand. For example, the in-range operator compares the input operand with upper and lower limits to check if it is located within a specific range or not. Figure 13 shows a ladder logic rung uses that comparator operator to check operand oper1 of type real to see if it is in the defined range which is between 0 to 10.0. because the value of the operand oper1 is 11.5 which is out of the defined range. The RLO shows false or zero. Therefore, the output is deactivated.

Fig. 13: in-range comparator operation for the real data type variable

Figure 14 shows the RLO is true when the operand’s value is located between the defined limits of the in-range block. Also, there is out range comparison operator that is the opposite of the in-range operator about the logic.

Fig.14: in-range comparator operation returns true when operand located in the range

 

Larger example

In this section, we want to show you how these comparator operators can be combined to achieve a logical expression in ladder logic programming. let us imagine a scenario that we have a garage with a full capacity of 100 parking spots and we utilize a counter to count up cars get in and count down the cars that get out of the garage. Figure 15 shows a very simple logic of the validation and comparison to decide if the garage has room for a further car or it is full and no further car is allowed at present. Assume that the output of the counter is an integer data type variable that is stored in memory location %MW20. Now you can see the logic is straightforward. In the first step, the counter output is validated to make sure that it plays in a valid range which is from 0 to 100 which denotes empty to full capacity of the garage. It applies the limit function to the counter in case it is out of range to reset it to be within the designed range. Then program checks in the second step the value if it is less than the full capacity of the garage which is designed to be one hundred cars, it states true indicated with green lamp output meaning there is still room for cars to get in the garage; otherwise, it checks if it is greater than or equal of the maximum limit meaning there is no room for further cars to enter, it shows false meaning garage is full at the current time by activating a red lamp.

Fig. 15: garage status ladder logic example

Figure 16 shows the case when the garage still has room for further cars and the green lamp is activated for incoming cars.

Fig. 16: when the garage has room for further cars

Figure 17 shows the case when the garage is full and has no room for further cars. So the red lamp is activated for telling users no further empty spots available at the moment.

Fig. 17: when the garage is full

What’s next

As usual, I want to express my delight in your following up our tutorial, and let me take this chance to announce one of the most important and exciting tutorials which are about processing the analog inputs and how to scale the analog inputs. Did I tell you my friends that will be the next chapter? So be ready for enjoying processing analog inputs with practicing real-life situations in the industry.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir