python-icon

Python Reference

Uses:

  • Web Programming
  • Scripting
  • Scientific Computing
  • Artificial Intelligence

Lexicography: alphabetical order of words based on alphabetical order of component letters

Operator Precedence & Descriptions

Operator Description
** Exponentiation
~, +, - Complement, plus, minus
*, /, %, // Multiply, division, modulus, floor division
>>, << Right and left bitwise shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise OR
in, not in, is not, is
<, >, <=, >=, !=, == Less than, greater than, less than or equal to, greater than ot equal, not equal, equal to
not Boolean 'NOT'
and Boolean 'AND'
or Boolean 'OR'
=, +=, -=, %=, /=, //=, *=, **= Assignment operators

  • For single-line comment, use octothorpe(#)
  • For multi-line comments, use """....."""

If Statements

Syntax:

if expression:
    #statements
elif expression:
    #statements
else:
    #statements
if expression:
    #statements
elif expression:
    #statements
else:
    #statements

While Loops

The statements run repeatedly as long as condition holds. If it’s False, it moves to the next codeblock.
Syntax:

while expression:
        #statements
while expression:
        #statements

To end a loop prematurely, the break keyword is used. Using the continue keyword, the code jumps back to the top of the loop.

Range keyword

It is a function that generates a list of sequential numbers.
Syntax:

range(number)
range(start, end, stop)
range(start, end)
range(number)
range(start, end, stop)
range(start, end)

For Loop

for expression:
    #statement 
for expression:
    #statement 

The main data structures are:

  • list
  • tuples
  • dictionaries
  • sets

Lists

  • It is an object in python; used to store an indexed list of items. It is created using square brackets ([]) with commas separating them.

Syntax:

var = ["one", "two"]
var = ["one", "two"]
  • To access the values, use index starting from 0.
  • The in and not in operators checks if items are in the list.
Common List Functions:
  • append method addds an item to an existing list at the end.

E.g.

nums = [1, 2, 3]
nums.append(4)
nums = [1, 2, 3, 4]
nums = [1, 2, 3]
nums.append(4)
nums = [1, 2, 3, 4]
  • To get the number of items in a list, use len function.
    E.g. len(list)
  • insert method allows you to add an item to any position in a list.
    Syntax: list.insert(index, value)
  • index method finds the first occurence of an item in a list and returns its index.
    Syntax: list.index(obj_value)
  • max function returns the list item with the maximum value.
  • min function returns the list item with the minimum value.
  • list.count(obj) returns the count of how many times an item occurs in a list.
  • list.remove(obj) removes an object from a list.
  • list.reverse() function reverses objects in a list.
List Comprehensions:

It is a useful way of quickly creating lists whose contents obey a simple rule.
E.g.

cubes = [i**3 for i in range(5)]
    #output: [0, 1, 8, 27, 64]
cubes = [i**3 for i in range(5)]
    #output: [0, 1, 8, 27, 64]
List Slices:

E.g.

sq = [0, 1, 2, 3, 4, 5]
print(sq[1:5])
#output: [1, 2, 3, 4]
sq = [0, 1, 2, 3, 4, 5]
print(sq[1:5])
#output: [1, 2, 3, 4]
  • [1:5] starts from index 1 and stops at index 5(with index 5’s value excluded).
  • If the first number of a slice is omitted, it is taken from the start of the list. E.g. [:5]
  • If the second number of a slice is omitted, it is taken to the end of the list. E.g. [1:]
  • It can be applied to turples.
  • There is a third number for step. E.g. [2:3:3]
  • When negative values are used in slices, they count from the end of the list.

Turples

  • They are very similar to lists except that they cannot be changed.
    Syntax:
var = (val, val, val)
    #Or
var = val, val, val
var = (val, val, val)
    #Or
var = val, val, val
  • Turples are faster than lists.

Dictionaries

They are used to map arbituary keys to values.
Syntax:

var = {val: val1}
    #To access the value
var[val]
    #Adding new values
var[key] = value
var = {val: val1}
    #To access the value
var[val]
    #Adding new values
var[key] = value

Sets

  • They are similar to lists and dictionaries but are unordered, so they cannot be indexed.
    Syntax:
var = {val1, val2, val3}
    #Or
var = set([val1, val2, val3])
    #For empty set
var = set()
var = {val1, val2, val3}
    #Or
var = set([val1, val2, val3])
    #For empty set
var = set()
  • They cannot contain duplicate elements.
  • To add new value, use the add(val) method.
  • remove(val) method removes specific elements from a set.
  • pop() method removes the first element.
Set Operators
Operator Description
| Union
& Intersection
- Difference - gets items in the first set that is not in the second
^ Symmetric difference - gets items in either sets but not both

Note: When to use the different types of data structures


When To Use Lists:
  • When you have a collection of data that does not need random access.
  • When you need a simple iterable collection that is modified frequently.
When to use Dictionaries:
  • When you need a logical association between a key value pair.
  • When you need fast lookup on your data based on a custom key.
  • When data is constantly modified since they are mutable.
When to use Turples:
  • When your data cannot change
When to use Sets:
  • When you need uniqueness for data elements.

Functional Programming

It is a style of programming that is based around functions. Pure functions have no side effects but return a value that only depend on their arguements. Pure functions are more efficient and based on memoization.

Memoization is a technique in which partial results are recorded and then can be reused later without having to recompute them.

Declaring Functions

Define functions and variables before using them

Syntax:

def function_name(arguements):
    #Statements
def function_name(arguements):
    #Statements
  • Arguement is a value passed to a function when calling it
  • Return is used to return a variable in a function.
  • Docstrings ("""...""") is used to describe the operations of a function.

Modules

Modules are pieces of code that can be reused to fulfill common task.

Syntax:

#Add module
import module_name

#To use module objects normally
from module_name import object

#To use all objects in module
from module_name import *

#Import module name or object with different name using as keyword
import numpy as np
from math import pi as food
#Add module
import module_name

#To use module objects normally
from module_name import object

#To use all objects in module
from module_name import *

#Import module name or object with different name using as keyword
import numpy as np
from math import pi as food

Lambda Functions

Used to define functions that are normally one line of code.
Syntax:

lambda( var:expression )("var's value")
lambda( var:expression )("var's value")

Map & filter

  • The map function takes a function as an iterable and returns a new iterable with the function applied to each arguement.

Syntax:

map( function, "iterable arguement/list ")
map( function, "iterable arguement/list ")
  • The filter function filters and iterable by removing items that do not match a predicate function.

A predicate function is a function that returns a boolean.

Syntax:

filter( function, iterable )
filter( function, iterable )

Generators

  • They are a type of iterable.
  • It make use of the yield statement which replaces the return statement of a function to provide a result to it's caller without destroying local variables.

Syntax:

#example
def num(x):
    """Filter even numbers from a sequence of numbers 1 to x"""
    for i in range(x):
        if i % 2 == 0:
            yield i

print(num(11))
#outputs 2, 4, 6, 8, 10
#example
def num(x):
    """Filter even numbers from a sequence of numbers 1 to x"""
    for i in range(x):
        if i % 2 == 0:
            yield i

print(num(11))
#outputs 2, 4, 6, 8, 10

Decorators

It is a function that modifies another function.
Code sample:

def decor(func):
    def wrap():
        print('='*10)
        func()
        print('='*10)
    return wrap

@decor
def print_txt():
    print("Hello, World!")

print_txt()
#outputs
# ==========
# Hello, World!
# ==========
def decor(func):
    def wrap():
        print('='*10)
        func()
        print('='*10)
    return wrap

@decor
def print_txt():
    print("Hello, World!")

print_txt()
#outputs
# ==========
# Hello, World!
# ==========

Recursive functions are functions that call themselves.

Itertools module

It is a standard library containing useful functions. Some tools are:

  • count() - It counts up infinitely from a value
  • cycle() - Infinitely iterates through an iterable
  • repeat() - Repeats an object either infinitely or a specific number of times.
  • takewhile() - Takes an item from an iterable while a predicate function is true.
  • chain() - Combines several iterables into one long one.
  • accumulate() - Returns a running total of values in an iterable.
  • product() and permutation() - Used to return all possible combinations of some items.

Exceptions

  • ImportError: An import fails.
  • IndexError: A list is indexed out of range.
  • NameError: Unknown variable is used.
  • SyntaxError: Code can't be parsed properly.
  • TypeError: A function is called on a value of in inappropriate type.
  • ValueError: A function is called with the correct type but of an inappropriate value.

Handling Errors

Syntax

try:
    #Statements to be tested for errors
except:
    #Code to run if an error occurs
finally:
    #Code runs whether there's an error or not
try:
    #Statements to be tested for errors
except:
    #Code to run if an error occurs
finally:
    #Code runs whether there's an error or not

Exceptions can also be raised between code using logic; E.g.

raise exception_name("message")
raise exception_name("message")

Opening Files

Syntax

open('filename.txt')
    #Or
open('filepath')

#Read mode
open('filename.txt', 'r')

#Write mode
open('filename.txt', 'w')

#Binary write mode
open('filename.txt', 'wb')
open('filename.txt', 'r+')
open('filename.txt')
    #Or
open('filepath')

#Read mode
open('filename.txt', 'r')

#Write mode
open('filename.txt', 'w')

#Binary write mode
open('filename.txt', 'wb')
open('filename.txt', 'r+')
  • To close a file use the .close() method.

Reading Files

file = open('filename.txt')
readfile = file.read()
print(readfile)
file.close()
file = open('filename.txt')
readfile = file.read()
print(readfile)
file.close()
  • To read byte by byte, input byte number into () in read.
  • Negative arguements will return entire contents.
  • To retrieve each line in a file, use the readlines method to return a list in which each element is a line in a file. Syntax: file.readlines()
  • To write files, use .write() method.
  • To automatically close file after reading its contents:
with open('filename.txt') as f:
    print(f.read())
with open('filename.txt') as f:
    print(f.read())

Classes

  • It describes what the object will be, but is separate from the object itself; it is an object's blueprint, description or definition. They are created using the keyword class and an indented block which contains class methods (which are functions).
    E.g.
class Cat:
    def __init__(self, color, legs):
        self.color = color
        self.legs = legs

Garfield = Cat("ginger", 4)
Tom = Cat('blue', 4)
class Cat:
    def __init__(self, color, legs):
        self.color = color
        self.legs = legs

Garfield = Cat("ginger", 4)
Tom = Cat('blue', 4)
  • The above code defines a class Cat with color and legs as attributes. Garfield and Tom are objects of the class.
  • The __init__ method is the most important method in a class. All methods must have self as a parameter.
  • self refers to the instance calling of the method.
  • In the ___init___ method, self.attribute is used to set the initial value of an attribute.
  • The __init__ method is called the class constructor.

Inheritance

  • It provides a functionality between classes.
  • To inherit a class from another class, put the super class in parenthesis after the classname.
    E.g.
class Animal:
    #Statements
    
class Cat(Animal):
    #Statements
class Animal:
    #Statements
    
class Cat(Animal):
    #Statements
  • A class that inherits from another class is called the subclass; while the inherited class is called the super class.
  • If a subclass defines the same methods pre-exising in its super class, it overrides them.

Magic Methods

  • They are special methods which have double underscores at the beginning and end of their names. They are known as dunders.
  • Their common use is operator overloading.
    E.g.
# __add__ for addition
class Vector2D:
    '''Defines a class to perform vector addition'''
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)
    

'''Sample inputs'''
# >> f = Vector2D(5, 7)
# >> d = Vector2D(3, 9)
# >> a = f + d
# >> print(a.x, a.y)
# >> (8, 16)
# __add__ for addition
class Vector2D:
    '''Defines a class to perform vector addition'''
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)
    

'''Sample inputs'''
# >> f = Vector2D(5, 7)
# >> d = Vector2D(3, 9)
# >> a = f + d
# >> print(a.x, a.y)
# >> (8, 16)

List of some magic methods and their descriptions

Magic Method Description
__add__ addition (+)
__sub__ subtraction (-)
__mul__ multipication (*)
__truediv__ division (/)
__floordiv__ integer division (//)
__mod__ modulo (%)
__eq__ equality (==)
__ne__ not equal (!=)
__gt__ greater than (>)
__lt__ less than (<)
__ge__ greater than or equals (>=)
__le__ less than or equals (<=)
__pow__ exponent (**)
__and__ anintd (&)
__xor__ exclusive or (^)
__or__ or (|)
__len__ len()
__getitem__ for indexing
__setitem__ for assigning to indexed values
__delitem__ for deleting indexed values
__iter__ for iteration over objects
__contains__ for in
__call__ for calling objects as functions
__int__ integer
__str__ string
__del__ for delete

Object Lifecycle

  1. Creation or definition
  2. Instantiation
  3. Manipulation
  4. Destruction

  • They verify if strings matches a pattern.
  • They can also perform substitutions in a string.
  • It can be access through the re module.

Some Functions in the re module

  • re.match() determines whether a value matches the beginning of a text.
    E.g.
import re

# Use raw strings for patterns
pat = r'span'

if re.match(pat, 'spanner'):
    print('match')
else:
    print('no match')

# Outputs match
import re

# Use raw strings for patterns
pat = r'span'

if re.match(pat, 'spanner'):
    print('match')
else:
    print('no match')

# Outputs match
  • re.search() finds a match of a pattern anywhere in the string.
  • re.findall() and re.finditer() returns a list of all substrings that match a pattern.
  • re.sub() replaces all occurences in a string; a patttern replaces with repl unless count is provided.
    Syntax:
re.sub(pattern, repl, string, count=0)
re.sub(pattern, repl, string, count=0)

Python Regular Expression Quick Guide

Symbols Desciption
^ Matches the beginning of a string
$ Matches the end of the string
. (dot) Matches any character other than a new line
\s Matches whitespace
\S Matches any non-whitespace character
* Repeats a character zero or more times
*? Repeats a character zero or more times (non-greedy)
+ Repeats a character one or more times
+? Repeats a character one or more times (non-greedy)
[aeiou] Matches a single character in the listed set
[^XYZ] Matches a single character not in the listed set
[a-z0-9] The set of characters can include a range
( Indicates where string extraction is to start
) Indicates where string extraction is to end
{} Represents repetitions between two numbers

Making custom modules

To make a module from a script, add the following code to the end of the file.

if __name__ == '__main__':
    #preferably enter file name
    filename()
if __name__ == '__main__':
    #preferably enter file name
    filename()

Packaging a source code

  • To organise your code so it can be installed and used, use disutils and setuptools
  • File Structure:
    • Root directory/
      • LICENSE
      • README.md
      • setup.py
    • App directory
      • __init__.py
      • //python_files_for_app
  • Writing setup.py :
from disutils import setup

setup(
    name='Root directory',
    version='1.0',
    packages=['App directory'],
    license='license_name',
    long_description=open('README.md').read()
)
from disutils import setup

setup(
    name='Root directory',
    version='1.0',
    packages=['App directory'],
    license='license_name',
    long_description=open('README.md').read()
)

Building Binary Distribution

  • In the directory with setup.py, run:
>> python setup.py sdist
>> python setup.py bdist

# For windows
>> python setup.py bdist_wininst
>> python setup.py sdist
>> python setup.py bdist

# For windows
>> python setup.py bdist_wininst

Uploading A Package

>> python setup.py register
>> python setup.py sdist upload
>> python setup.py register
>> python setup.py sdist upload

Installing A Package

>> python setup.py install
>> python setup.py install

The Zen OF Python

  • To access this use:
import this

### Output is as follows:
'''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
import this

### Output is as follows:
'''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

String Formatting

  • Applied when you need to combine strings and non-strings.
    E.g.
name = David
age = 19
country = Ghana
msg = "My name is {0} and I am {1} of age and I come from {2}".format(name, age, country)

#OR
msg = f"My name is {name} and I am {age} of age and I come from {country}"

print(msg)
# Outputs
# My name is David and I'm 19 years of age and I come from Ghana.
name = David
age = 19
country = Ghana
msg = "My name is {0} and I am {1} of age and I come from {2}".format(name, age, country)

#OR
msg = f"My name is {name} and I am {age} of age and I come from {country}"

print(msg)
# Outputs
# My name is David and I'm 19 years of age and I come from Ghana.

String Functions

  • startswith() returns True or False.
  • endswith() returns True or False.
  • upper() returns in caps.
  • lower() returns in lower caps.
  • split() returns elemnts of a string as a list based on a separator.
  • join() adds strings to other strings based on a separator. It's more or less the opposite of split function.

Numeric Functions

  • abs() returns absolute value of a number.
  • sum() returns the sum of numbers.
  • round(num, no. of dp) rounds a number to a specified decimal places.

Function Arguements

  • There can be a varying number of arguements.
  • Using *args (or any name), the arguements are accepted as a turple.
    E.g.
def func(arg_name, *args):
    print(arg_name)
    print(args)
    
func(1, 2, 3, 4, 5)

#Outputs
# 1 
# (2, 3, 4, 5)
def func(arg_name, *args):
    print(arg_name)
    print(args)
    
func(1, 2, 3, 4, 5)

#Outputs
# 1 
# (2, 3, 4, 5)
  • When an arguement is not passed in, a default value is used.

Always pass in arguements with no default values first before arguements of the default value is named.
Sample:

func(x, y, a=0, b="we")
func(x, y, a=0, b="we")

Turple Unpacking

  • It allows you to assign each item in an iterable (often a turple) to a variable. E.g.
nums = (1, 2, 3)
a, b, c = nums

# a= 1, b = 2, c =3
nums = (1, 2, 3)
a, b, c = nums

# a= 1, b = 2, c =3
  • If a variable is prefaced with an asterisk (*), then it takes all values from the iterable left over by other variables. E.g. *c

Ternary Operator

  • They are conditional expressions in the assigning of variables, taking in three arguements. E.g.
a = 1
b = 1 if a >= 5 else 40

print(b)
#Outputs 40
a = 1
b = 1 if a >= 5 else 40

print(b)
#Outputs 40

Else statements in while and for loops are executed when the break statement fails to stop the loop.

  • If you want to make a copy of a list explicitly, use list_name[:]