Open In Colab

Functions

Math Functions

  • A function is a block of code which only runs when it is called.
  • In Python, a function is defined using the def keyword. A function takes an argument and returns a result. The result is called the return value.
  • To call a function, use the function name followed by parenthesis.
  • Python has a math module that provides mathematical functions.
In [1]:
import sys
print(sys.version) # Check Python version.
3.6.9 (default, Oct  8 2020, 12:12:24) 
[GCC 8.4.0]
In [2]:
import math
math
Out[2]:
<module 'math' (built-in)>
In [3]:
math.sqrt(2)
Out[3]:
1.4142135623730951
In [4]:
7 * math.pi
Out[4]:
21.991148575128552

Python's built-in functions

In [5]:
print(7,8,9,sep='--') # Print in Python 3 is a function. sep is a keyword argument.
7--8--9
In [6]:
print('sandstone') # Here print is the function name, and 'sandstone' is the function's argument.
sandstone
In [7]:
float(77) # float converts integers and strings to floating-point numbers.
Out[7]:
77.0
In [8]:
int(70.98635) # int converts floating point values to integers by chopping off the fraction part.
Out[8]:
70
In [9]:
int('17')
Out[9]:
17
In [10]:
str(37) # str converts its argument to a string.
Out[10]:
'37'

Creating a function

  • def indicates that this is a function.
  • The empty parenthes after the name indicates that this function does not take any arguments.
  • Some functions require arguments. The arguments are assigned to varaibles called parameters.
  • Arguments are shortened to args in Python documents.
  • The terms parameter and argument can be used for the same thing: information that are passed into a function.
  • Keyword arguments are shortened as kwargs.
  • To end the function, enter an empty line.
  • You can use a function inside another function.
In [11]:
def print_rocks():
    print("I'm a sandstone.")
In [12]:
print(print_rocks)
<function print_rocks at 0x7fbec06bf2f0>
In [13]:
type(print_rocks)
Out[13]:
function
In [14]:
print_rocks() # call print_rocks
I'm a sandstone.
In [15]:
def repeat_rocks():
    print_rocks()
    print_rocks()
repeat_rocks()
I'm a sandstone.
I'm a sandstone.
In [16]:
def print_twice(basalt):
    print(basalt)
    print(basalt)
print_twice('breccia')
breccia
breccia
In [17]:
igneous = 'granite, basalt, and etc.' # igneous is a variable, as an argument. 
print_twice(igneous)
granite, basalt, and etc.
granite, basalt, and etc.

Fibonacci Numbers

  • The function's name is fibonacci.
  • The function takes a single argument (parameter) n.
  • The function returns a list of the first n Fibonacci numbers.
  • The Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...
In [18]:
def fibonacci(N):
    L = [0]
    a, b = 0, 1
    while len(L) < N:
        a, b = b, a + b
        L.append(a)
    return L

fibonacci(10)
Out[18]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]