Python (programming language)

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

Data types

Category Type
Text str
Numeric int, float, complex
Sequence list, tuple, range
Boolean bool
Mapping dict
Set set, frozenset
Binary bytes, bytearray, memoryview
None NoneType

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:

  • Lists
  • Tuples
  • Sets
  • Dictionaries

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',
}

Control structures

if statements

if a < 0:
    print('Negative')
elif a > 0:
    print('Positive')
else:
    print('Zero')

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

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

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()

Accessing web data

Sockets

Python has built-in support for TCP sockets.

import socket

# `class socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)`
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# `address` is a 2-tuple `(host, port)`
mysocket.connect(address)

Working with URLs

urllib is a package that collects several modules for working with URLs:

  • urllib.request for opening and reading URLs
  • urllib.error containing the exceptions raised by urllib.request
  • urllib.parse for parsing URLs
  • urllib.robotparser for parsing robots.txt files

Web scraping

BeautifulSoup is used extract information from the HTML and XML files. It provides a parse tree and the functions to navigate, search or modify this parse tree.

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

Resources