Python (programming language)

Python is an interpreted high-level general-purpose computer programming language.

Data types

Text str
Numeric int, float, complex
Sequence list, tuple, range
Boolean bool
Mapping dict
Set set, frozenset

Basic operators

Arithmetic

Operator Description
+ addition
- subtraction
* multiplication
/ division
// floor division
% modulus
** exponent

Relational

Operator Description
== equality
!= inequality
<> inequality
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Logical

Operator Description
and logical AND
or logical OR
not logical NOT

Assignment

Operator Description
= assignment
+= add AND
-= subtract AND
*= multiply AND
/= divide AND
%= modulus AND
//= floor division AND
**= exponent AND

Membership

Operator Description
in true if value is found in sequence
not in true if value is not found in sequence

Data structures

Built in data structures:

  • list
  • tuple
  • set
  • dictionary

Lists

A list is an ordered (indexed), mutable data structure capable of storing non-unique elements of different data types.

list = ['el1', 'el2']

Python list object methods.

Tuples

A tuple is an ordered (indexed),immutable data structure capable of storing non-unique elements of different data types.

tuple = ('el1', 'el2')

Sets

A set is an unordered (non-indexed), mutable data structure capable of storing unique elements of different data types.

set = {'el1', 'el2'}

Dictionaries

A dictionary is an unordered (non-indexed), mutable data structure capable of storing non-unique elements of different data types accessed by unique keys.

dict = {
  'key1': 'value',
  'key2': 'value',
}

Functions

A function is a reusable block of code containing related statements that runs only when it is called.

syntax:

def function_name(arguments):
  statement(s)

The Python Standard Library built-in functions.

Lambda

A lambda is a small anonymous function that can accept any number of arguments but may have only one expression.

Syntax:

lambda arguments: expression

Loops

A loop statement allows us to execute a statement or group of statement multiple times.

Type Description
while Repeats while a given condition is true
for Repeats 'n' number of times

Loop control statements

Statement Description
break Terminates the loop
continue Skips the remainder of the block but continues the loop
pass Disregarded statement

Classes

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.

Syntax:

class Class
    def __init__(self, arg1, arg2):
        self.arg_a = arg1
        self.arg_b = arg2

    def method(self):
        print(self.arg_a + self.arg_b)

foo_instance = Class('bar', 'baz')
foo_instance.method()

Modules

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.

Importing modules:

import module
module.function()

# Alias module name
import module as foo
foo.function()

# Destructure imports
from module import function
function()

Virtual environments

Virtual environments are independent groups of Python libraries. Each virtual environment has its own Python binary and can have its own independent set of installed Python packages. Packages installed for one project will not affect other projects or the operating system’s packages.

Python comes bundled with the venv module to create virtual environments. Create a virtual environment in a project directory:

# Create an environment
python3 -m venv venv

# Activate the environment
. venv/bin/activate

# Deactivate the environment
deactivate

# Delete the environment
rm -r venv

Read the venv documentation.

Requirements

A requirements file is a list of project dependencies.

pip freeze lists the current dependencies to stdout. Generate a requirements.txt file by running:

pip freeze > requirements.txt

Install packages from a requirements.txt file by running:

pip install -r requirements.txt