Python Syntax

Python Syntax

posted 9 min read

A. Introduction

Python syntax is the language grammar or structure of expressions or statements that are read by the Python parser before executing the full code. Python tokenizes the source code into keywords, operators, identifiers, etc to quickly determine if its syntax is correct. If there is an error, python would raise technically an exception called SyntaxError along with its equivalent error message. Through this error detection, it saves computer resources by holding the full code execution.

In subsequent sections, I will present example codes that illustrate correct syntax. Use of indentation to form a block of code, variable namings, basic data type usage, function and class definitions and others.

B. Indentation

Python uses indentations to define blocks of code. A block of code starts with indentation and ends with the first unindented line. The amount of indentation usually consists of four spaces and must be consistent throughout that block.

Bad indentation raises the IndentationError.

1. Indentation from if/else statement

country = input('Please enter your country: ')
if country == 'USA':
    print(f'Your beautiful country is {country}')
    print(f'Your country is {country}')

2. Indentation from for loop

for fruit in [('mango', 'yellow'), ('apple', 'red'), ('avocado', 'green')]:
    print(f'color: {fruit[1]}')

Execute the script in the terminal



color: yellow
color: red
color: green

3. Indentation from a function

Functions are used to organize code statements. All functions use an indentation. Here is an example of writing a correct syntax for functions.

def get_car_brand_names():
    cars = ['Toyota', 'Ford', 'Ferrari']
    new_car = 'Honda'
    return cars

car_brands = get_car_brand_names()

4. More than one level of Indentation

Python can handle multiple levels of indentations. A good programming practice however is to limit it to two to maintain readability.

gender = 'male'
age = 24
if gender == 'male':
    if age >= 18:
        print('male adult')
        print('male teenager')

5. Do not mix the number of spaces in indentations

This is bad.

if gender == 'male':
      if age >= 18:
        print('male adult')
        print('male teenager')

6. Indentations from space and tab

Indentation can be created in two ways.

  • space - using the space bar on your keyboard
  • tab - using the tab key on your keyboard


  • To create an indentation by four spaces, just press your space bar 4 times.
  • For tab indentation you need to check your code editor how many spaces are set to create a single tab. In Python a tab is represented by a character \t.
  • Do not mix tab and space usage to avoid errors. If you are using spaces, always use it. And if you use tabs, always use it as well.
  • The most common and recommended way is to use a space and it should be 4 spaces.

C. Statement Termination

A statement or expression is terminated by a newline character '\n'. Or in your code editor, just use the enter key. It is non-printable.

1. Basic example

prog_lang_name = 'Python'

2. A newline character does not always mean the end of a statement

a. Parenthesis, Bracket and Brace

If there are parenthesis, bracket or brace the statement does not end there. It would continue to the next line. Line statement continuations are usually used if using a single is too long.

Note: the line that starts with # is just a comment. It does not affect the code logic.
# parenthesis
get_sum = (10 + 
    10 + 15)
print(get_sum)  # 35

# brace
city_list = ['Paris', 'Oslo', 'Bangkok', 'Beijing', 'Chicago', 'Amsterdam' ,
    'Tokyo', 'Brusells']

# bracket
sports_dict = {'basketball': 'ball game', 'cliff diving': 'diving', 'softball': 'bat-and-ball',
    'chess': 'board game'}

b. Backslash or \

If there is a backslash or \ at the end of the line, that means a continuation of the statement will continue in the next line.

get_sum = 10 + \
          10 + \
print(get_sum)  # 35

D. Variables and Data Types

Variables are containers to hold data. Data types include integers, floating-point numbers, bool, strings, and more complex types like lists, dictionaries, objects, etc.

1. Variable Names

To write a statement or code expression, the variable name must be on the left-hand side of the equal sign and its intended value must be on the right-hand side of the equal sign.

num_computers = 25

Use the English alphabet to name a variable except keywords. It is a good programming practice to use the English letters in the alphabet and underscore _ characters to separate words to create a variable name.

Never use keywords as your variable names. Keywords are used internally by Python. They have special meanings in the language.

Let us generate keywords by python script.

import keyword

python_keywords = keyword.kwlist


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Caution: Do not use any of these keywords as a variable, function and class names.

Here are some examples of correct variable namings.

sky_color = 'blue'
planets = ['mars', 'saturn']
usd_oil_price_per_barrel = 78.5

Do not use a number as a character that starts the variable name and do not use special characters such question mark, etc. The following would result to a syntax error.

7elevel = 'good'
sun?shine = 'bright'

2. Data Types

a. Numeric and Boolean

Python has some data types such as integers, float, complex, boolean, fraction and decimal for numeric types. Here are some syntax how to use numeric types.

age = 24  # integer
price = 99.99  # float
cplx = 2 + 3j  # complex number
is_raining = False  # boolean can be either True or False

# Fraction
from fractions import Fraction
num = Fraction(75, 110)
print(num)  # 15/22

# Decimal
from decimal import Decimal
balance = Decimal(17.6)
print(balance)  # 17.60000000000000142108547152020037174224853515625

b. Sequence types

Python has some sequence types. They are list, range, tuple, binary and string data.

Do not forget to separate items inside the list, range and tuple with a comma. If you fail, it will generate a syntax error.

Correct usage to avoid syntax errors.

# list
game_stats = [15, 20, 18, 24]

# range
for r in range(1, 10, 2):

# tuple
population = (100, 600, 800)

For string and binary data, do not forget to enclose the value with single or double quotes.

# string
username = 'jupiter'
name = "romelo"

# binary, similar to string but with a `b` prefix.
address = b'xxx yyy zzz'

# syntax error in a string, notice the missing opening quote.
name = gina"

E. Control Flow Statements

The usual control flow statements uses if, elif, and else for conditional operations, and for and while loops for iteration.

Here are some examples of a correct syntax in control flow statements. The things to remember here are the colon or : after the if, elif, else, for and while lines; and the indentation which we already discussed in previous section.

1. The if, elif and else example

Give an award of 5000 if a team wins a game, 1000 for even and 100 for a loss.

result = 'win'
if result == 'win':
    award = 5000
elif result == 'even':
    award = 1000
    award = 100
print(f'award: {award}')  # award: 1000

2. The for loop example

Loop thru the list and print each item.

for num in [5, 9, 1, 3]:

3. The while loop example

Print a number as long as it is above 10. Start at 20.

num = 20
while num > 10:
    num = num - 1
Tip: Remember to add a colon or `:` at the end of the line where there is a control flow keywords.

F. Functions and Classes

Function uses the def keyword followed by the function name and parentheses (). Python supports both procedural and object-oriented programming (OOP). Classes are defined using the class keyword.

1. A sample add function

# Define a function
def add(a, b):
    total = a + b
    return total

# Use it
result = add(4, 8)
print(result)  # 12

Things to remember to avoid syntax errors.

* Function starts with a def keyword.
* The word `add` is called an identifier or function name and must not be a keyword.
* The function name must be a single word or two or more words connected using the underscore `_`.
* We have two parameters in this example, `a` and `b`.
* The parameters are enclosed in parentheses.
* There is a colon `:` after the closing parenthesis.
* There is indentation.

2. A sample Country class

# Define a class
class Country:
    def __init__(self, name, capital): = name = capital

    def info(self):
        print(f'The capital of {} is {}.')

# Use it
country_info = Country('France', 'Paris')  # The capital of France is Paris.

Things to remember to avoid syntax errors.

* A class definition starts with a class keyword followed by a name and ends with a colon `:`.
* The word Country is called the identifier or a class name.
* The rests are similar to the function definition.

G. Importing Modules

Modules can be libraries of functions, classes, or variables. You use the import statement to use a module.

Here is an example syntax for importing a module. Teachers want to calculate the students' grade average from a given list of grades. They use Python's module called statistics which has a function mean.

import statistics

grades = [85, 90, 89, 84]
average = statistics.mean(grades)
print(f'average: {average}')  # average: 87

H. Exception Handling

Python uses try-except blocks to handle exceptions. Code that might raise an exception is placed in the try block, and the handling of the exception is then implemented in the except block. when everything is done, codes in the finally block will be executed.

import random

rnum = random.randint(0, 9)
    result = 5 / rnum

except ZeroDivisionError as err:
    print("Cannot divide by zero.")

except Exception as err:
    print("Unexpected error")

    # without exception or error
    print("No exception occurred.")
    print(f'result: {result}')

    # This is always executed.
    print("finally block")

I. PEP 8

Python's coding style is guided by PEP 8, or Python Enhancement Proposal. It provides guidelines and best practices on how to format Python code. This will promote code consistency and readability. There is a lot that we can learn about Python's syntax as well.

J. Summary

The article provides a comprehensive guide to Python syntax, covering topics such as indentation, statement termination, variables, data types, control flow, functions, classes, module importing, exception handling, and adherence to PEP 8 coding standards.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Exploring Python Operators: Beyond the Basics

Ferdy - Jun 22

Basic operators in Python

Ferdy - May 19

Python Variables and Data Types

Ferdy - Mar 23

Data Visualization with Python: Using Matplotlib and Seaborn

Muzzamil Abbas - Jul 6

Mastering Web Scraping with Python

Tejas Vaij - Jun 27