Python Functions and Modules¶

Feng Li

School of Statistics and Mathematics

Central University of Finance and Economics

feng.li@cufe.edu.cn

https://feng.li/python

Build-in Functions¶

  • The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. Use e.g. help(abs) to see the function help.
abs() aiter() all() any() anext() ascii() bin() bool() breakpoint() bytearray() bytes() callable() chr() classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() isinstance() issubclass() iter() len() list() locals() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() vars() zip() __import__()
  • See https://docs.python.org/3/library/functions.html for a complete description of those functions.

Import modules¶

To import a module (like math) that is not in Python's default module, use

In [43]:
import math

Then you can use all the mathematical functions inside math module as:

In [44]:
math.exp(0)
Out[44]:
1.0
  • Alternatively, you can do the following module renaming when importing
In [45]:
import math as mt
mt.exp(1)
Out[45]:
2.718281828459045
  • If you just want to import one or two functions from a module
In [46]:
from math import exp
exp(3)
Out[46]:
20.085536923187668
In [47]:
from math import exp as myexp
myexp(1)
Out[47]:
2.718281828459045

Install third-party modules¶

through terminal¶

  • Use pip in a terminal to install a Python module from PyPi (https://pypi.org) on your user directory.
pip install numpy --user
  • You could also specify a faster mirror close to you
pip install numpy --user -i https://pypi.tuna.tsinghua.edu.cn/simple
  • Update a Python module
pip install pandas -U
  • Remove a Python module
pip uninstall numpy

trhough Jupyter notebook¶

You could issue the above commands within the Jupyter notebook. Just place the ! in front of the command

In [2]:
! pip3 install pandas -U
Looking in indexes: https://mirrors.163.com/pypi/simple/
Requirement already satisfied: pandas in /usr/local/lib/python3.9/dist-packages (1.3.4)
Collecting pandas
  Using cached https://mirrors.163.com/pypi/packages/48/b4/1081d66b71c4dfc1bc1e19d6f2abbf93ed42f69df7703eb323742d45423e/pandas-1.3.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.5 MB)
  Using cached https://mirrors.163.com/pypi/packages/03/ea/98d488a4047b3fd8075b5c1e00469ad42d715e2c1e4fd15fa1ffaef8d635/pandas-1.3.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.5 MB)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/lib/python3/dist-packages (from pandas) (2.8.1)
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.9/dist-packages (from pandas) (1.21.2)
Requirement already satisfied: pytz>=2017.3 in /usr/lib/python3/dist-packages (from pandas) (2021.3)

Control Flow Tools¶

The if statements¶

Perhaps the most well-known statement type is the if statement. For example:

In [4]:
x = 0

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')
  Cell In[4], line 6
    elif x == 0:
    ^
SyntaxError: invalid syntax

Note

  • the comma/colon sign(:) should be right after if, elif and else statement.
  • the indentation is very important. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string.

The for Statements¶

In [49]:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))
cat 3
window 6
defenestrate 12
In [ ]:
a = [3,5,0]
b = [1, 9, 7]
c = [2, 4, 4]

for i in [0,1,2]:
    a1 = a[i]
    b1 = b[i]
    c1 = ???
    d = ???
    if d > 0:
        print("two")
    elif d == 0:
        print???
    else 
        ???
In [ ]:
 
In [5]:
x = [1900, 2000, 2004, 2011, 2022]

for year in x:
    if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
        print(year, "is a leap year")
    else:
        print(year, "is not a leap year")
1900 is not a leap year
2000 is a leap year
2004 is a leap year
2011 is not a leap year
2022 is not a leap year

Defining Functions¶

  • We can create a function that writes the Fibonacci series to an arbitrary boundary.

  • The function should also include a proper help with the docstring

    • The first line should always be a short, concise summary of the object's purpose.

    • If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.

    • The following lines should be one or more paragraphs describing the object's calling conventions, its side effects, etc.

In [9]:
# 0, 1, 1, 2, 3, 5,
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n.
    
    par n: integer
    out  : list
    """ # the function help
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        #  better than print(a), why?
        a, b = b, a+b
In [10]:
help(fib)
Help on function fib in module __main__:

fib(n)
    Print a Fibonacci series up to n.
    
    par n: integer
    out  : list

In [11]:
fib(20000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 
  • Function could also have default values. The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
In [40]:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise IOError('too many tries')
        print(complaint)
In [ ]:
ask_ok("Do you really want to go, dear?", retries=2)
  • Anonymous functions Small anonymous functions can be created with the lambda keyword.

Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. The example uses a lambda expression to return a function

In [32]:
def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(42)
In [56]:
f(0)
Out[56]:
42
In [57]:
f(1)
Out[57]:
43

The anonymous function is very useful in manipulating the list and Python DataFrame (pandas)

  • If we save the function to a file named mycollections.py, we could import the function as follows
>>> import mycollections
>>> mycollections.fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> from mycollections import fib
>>> fib(2000)
In [3]:
import mycollections
In [4]:
mycollections.fib
Out[4]:
<function mycollections.fib(n)>
In [5]:
mycollections.fib(100)
0 1 1 2 3 5 8 13 21 34 55 89 
In [6]:
from mycollections import fib
In [1]:
import os
os.getcwd()
Out[1]:
'/home/fli/carbon/teaching/python/python-slides/P01-Python-from-Scratch'
In [8]:
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n.

        argument
            n: numeric number

        vaule
            return Fibonacci series
    """
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        #  better than print(a), why?
        a, b = b, a+b
In [9]:
fib(10)
0 1 1 2 3 5 8 
In [10]:
import feng
In [11]:
feng.fib(100)
0 1 1 2 3 5 8 13 21 34 55 89