Syntax

The syntax of Python is similar to those of other programming languages, below is a summary and a quick reference.

Comments

A single-line comment starts with the # character and extends to the end of the line.

# This is a single-line comment

A multi-line comment starts with """ and ends with """. It can span multiple lines.

"""
This is a multi-line comment
"""

Indentation

Python uses indentation to indicate block structure. Indentation is used to indicate that a block of code is part of a larger block of code.

if condition:
    # This is a block of code that is part of the if statement
    print("Hello world!")

In other languages, indentation is used to make the code look more readable. In Python, indentation is used to indicate the block structure of the code, hence why it is important.

Arithmetic

The following below are the primary arithmetic operators, which can be applied to literal numbers, variables, or some combinations:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • % for modulus (returns the remainder)
  • ** for exponentiation

Examples:

2 + 3
# 5
2 - 3
# -1
2 * 3
# 6
2 / 3
# 0.6666666666666666
2 % 3
# 2
2 ** 3
# 8

Plus-Equals Operator

The += operator is used to add and assign a value to a variable:

x += 1

If used on a string, it concatenates the string to the variable:

x = "hello"
# x is now "hello"
 
x += " world"
# x is now "hello world"

Variables

A variable is a named location in memory that can hold a value. It can be assigned a value using the = operator:

x = 5
# the variable x now holds the value 5

Data Types

Python has the following data types:

  • int for integers
  • float for floating-point numbers
  • str for strings
  • bool for booleans
  • list for lists
  • tuple for tuples
  • dict for dictionaries
  • set for sets
x = 5
# x is now an integer
 
x = 5.0
# x is now a float
 
x = "hello"
# x is now a string
 
x = True
# x is now a boolean
 
x = [1, 2, 3]
# x is now a list
 
x = (1, 2, 3)
# x is now a tuple
 
x = {"a": 1, "b": 2}
# x is now a dictionary
 
x = {1, 2, 3}
# x is now a set

Control Structures

Python has the following control structures:

  • if for conditional statements
  • for for loops
  • while for loops
  • range() for loops
if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
for i in range(5):
    print(i)
while x > 0:
    print(x)
    x -= 1
for i in range(5):
    print(i)

Reserved Words

Python has the following reserved words:

Reserved WordDescriptionExample
andLogical andx > 0 and x < 10
asAssignimport math as m
assertAssertassert x > 0, "x is negative"
breakBreakfor x in range(10): if x == 5: break
classClass definitionclass Person: pass
continueContinuefor x in range(10): if x % 2 == 0: continue
defFunction definitiondef add(x, y): return x + y
delDeletedel x
elifElse ifif x > 0: ... elif x < 0: ...
elseElseif x > 0: ... else: ...
exceptException handlingtry: ... except: ...
finallyFinallytry: ... finally: ...
forFor loopfor x in range(10): ...
fromImport fromfrom math import *
globalGlobal variablex = 5; global x
ifIfif x > 0: ...
importImportimport math
inInx in [1, 2, 3]
isIsx is y
lambdaLambda functionf = lambda x, y: x + y
nonlocalNonlocal variable
notNotnot x
orLogical orx > 0 or x < 10
passPassif x > 0: pass
raiseRaise exceptionraise ValueError("x is negative")
returnReturndef add(x, y): return x + y
tryTrytry: ... except: ...
whileWhile loopwhile x > 0: ...
withWithwith open("file.txt") as f: ...
yieldYield

Functions

Functions are defined using the def keyword:

def add(x, y):
    return x + y

Classes

Classes are defined using the class keyword:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Modules

Modules are defined using the import keyword:

import math

File I/O

File I/O is defined using the open function:

f = open("file.txt", "r")

Multiline Strings

Multiline strings are defined using triple quotes:

s = """This is a multiline string"""

Docstrings

Docstrings are defined using triple quotes:

def add(x, y):
    """
    This is a docstring
    """
    return x + y

User Input

User input is defined using the input function:

name = input("\nWhat is your name? ")
  • Note that the \n is used to create a new line.

Command Line Arguments

Command line arguments are defined using the sys.argv module:

import sys
print ('argument list', sys.argv)
name = sys.argv[1]
print ("Hello {}. How are you?".format(name))

This example is taken from this link.

The output of the above code will be:

C:\Python311>python hello.py user
argument list ['hello.py', 'user']
Hello user. How are you?