2A Slides
2A Slides
INTRODUCTION TO
FUNCTIONS
Sadia Sharmin, Department of Computer Science
Navigation tip for web slides: press ? to see keyboard navigation controls.
RECAP
THE SEVEN MAIN PYTHON DATA TYPES
Data type Description Operations
int, float Numeric data Arithmetic (e.g. +), comparisons (e.g. ==, <)
bool Boolean (True/False) data and, or, not
str Text data ==, +, in, indexing (s[...])
set Collection, no duplicates, no ==, in
order
list Collection, duplicates allowed, ==, +, in, indexing (s[...])
order matters
dict Collection of association pairs ==, in, key lookup (d[...])
LEARNING OBJECTIVES
In this part of the lecture, you will learn to:
1. Define terminology relating to functions in mathematics and
programming.
2. Name and describe some built-in Python functions.
3. Create sequences of integers in Python using the range function.
4. Recognize and write Python code for function call expressions.
FUNCTIONS IN PYTHON
Code we’ve seen so far:
literals (3, 'hello', [1, 2, 3])
operators (+, -, and)
variables and assignment statements (numbers = {1, 2, 3})
comprehension expressions ({x ** x for x in numbers})
How do we build up code with these elements to perform useful
computations?
Recall a mathematical definition of a function: a mapping of
elements from one set A (called the function’s domain) to a set B
(called the function’s codomain). Notation:
f unction : A → B
Example:
f : R → R
2
f (x) = x
f (0) = 0
f (−1.5) = 2.25
FUNCTIONS IN PYTHON
Python comes with many built-in functions that do the same thing:
take in input values and return an output value.
HOW TO USE PYTHON FUNCTIONS
Functions are structured like this: function_name(input)
When you type this in, the function does stuff to the input, and gives
you back an output.
For example, abs(number) is the name of the python function that
takes in a number and returns its absolute value
There are many, many Python functions available to use (and they
aren’t just limited to mathematical applications)!
DEMO: SOME BUILT-IN PYTHON
FUNCTIONS
abs
len
sum
sorted
max/min
type
help
Fun fact: dir(__builtins__) will show you all the built-in
functions available
USEFUL FUNCTION: HELP!
If you remember a function’s name, but forget exactly what it does,
you can ask Python for help like so:
>>> help(abs)
Dictionary comprehension:
List comprehension:
Dictionary comprehension:
Demo!
COMPREHENSIONS WITH MULTIPLE
VARIABLES
Consider this new set operation, the Cartesian product:
A × B = {(x, y) ∣ x ∈ A and y ∈ B}
Example:
{1, 2} × {10, 20} = {(1, 10), (1, 20), (2, 10), (2, 20)}