Python Syntax

Python Indentation

In Python, indentation is used to indicate a code block. Code block is a group of statements executed as a unit, like function body or class definition.

Many programming languages (like Java, C, C++, C#) use braces {} to indicate a code block. Python uses indentation instead of braces.

Indentation is the leading whitespace at the beginning of code line. Space or tab character can be used for whitespace. According to the Style Guide for Python Code, it is suggested to use 4 spaces for indentation.

All statements in a block should have the same amount of indentation (i.e., they should be aligned). Otherwise, Python will give IndentationError.

IndentationError: expected an indented block

if a > 100:
print("a is greater than 100")
print("complete.")

IndentationError: unexpected indent

if a > 100:
    print("a is greater than 100")
        print("complete.")

Correct

if a > 100:
    print("a is greater than 100")
    print("complete.")

Python Variables

Variables are used to store information. Once you create a variable, you can access or change it throughout the program. When naming a variable you need to pay attention to some rules:

  • Variable names should start with a letter or underscore (_) character (e.g., name, _age, Address are valid names)
  • Variable names can contain alphabetic, numeric or underscore characters (e.g., address1, address2, zip_code are valid names)
  • Variable names cannot start with a number (e.g., 1team gives SyntaxError)
  • Variable names are case-sensitive (e.g., name and Name are two different variables)

In some languages, to create a variable you need to specify its data type (integer, decimal, string,…). In Python, you don’t need to specify a data type to declare a variable. To create a variable, you just need a variable name, the assignment operator (=) and the value of the variable.

# Variable Creation
number = 5
Name = "John"

Python Statements

Python statements are the instructions that can be executed by Python interpreter. You need different types of statements to create a program (like assignment, conditional or loop statements). You can find an example for each statement type below:

# Assignment Statement
pi = 3.14

# Conditional Statement
if pi > 3 :
    print("pi is greater than 3.")

# Loop Statement
while num < 5:
    num += 1
    print("num: ", num)

Multi-Line Statements

In Python, end-of-line indicates the end of a statement. However, a statement can span multiple lines with the line continuation character (\). This is called Explicit Line Continuation.

You can also construct multi-line statements by using parentheses ( ), brackets [ ] or braces { }. This is called Implicit Line Continuation.

Conversely, you can put multiple statements on a single line. To have multiple statements on a single line, you need to separate the statements with semicolons. However, this practice is not suggested because it makes code less readable.

# Explicit Line Continuation
total_numbers = 1 + 2 + \
3 + 4 + \
5 + 6

# Implicit Line Continuation
total_numbers = (1 + 2 +
3 + 4 +
5 + 6)

# Multiple Statements on a Single Line
print("Hello"); print("World!")

Comments

Comments are used to describe what the code does. They are ignored by Python interpreter. Comments increase the readability of your code and help other programmers to understand the code. It is a good practice to comment out your code as you write it.

In Python, hash mark(#) character indicates the beginning of a comment. Python interpreter will ignore all your comments from # character to the end-of-line.

Triple quotes are used for multi-line comments in Python. Triple quotes are usually used for multi-line strings but they can also be used for multi-line comments since Python interpreter ignores the string between triple quotes.

# This is a comment line and will be ignored by Python Interpreter
print("A sample print statement")

""""
 This is a multi-line comment
 and this block will also be
 ignored by Python Interpreter
"""

Docstring in Python

Docstring is short for documentation string in Python. A docstring is a special type of string to associate and create documentation for modules, classes, functions, and methods. It looks like multi-line comments. Python’s built-in functions also have docstrings. For instance, docstring for built-in pow function is defined as follows:

def pow(*args, **kwargs):
	"""
	Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

	Some types, such as ints, are able to use a more efficient algorithm when
	invoked using the three argument form.
	"""

You can access a documentation string for a module, function, class or method with __doc__ attribute. From Python Command Line Interpreter, execute the following command to print documentation of pow function:

>>> print(pow.__doc__)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
 
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
>>>

You can also access docstrings using Python’s help() function:

>>> help(pow)
Help on built-in function pow in module builtins:

pow(base, exp, mod=None)
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
>>>
SHARE