SlideShare a Scribd company logo
1 of 97
Download to read offline
Python Functions 
Rick Copeland
Python Functions 
Rick Copeland
Python Functions 
Rick Copeland
Beginner’s 
Night 
Python Functions 
Rick Copeland
What is a function, anyway?
What is a function, anyway? 
• Reusable bit of Python code
What is a function, anyway? 
• Reusable bit of Python code 
• … beginning with the keyword def
What is a function, anyway? 
• Reusable bit of Python code 
• … beginning with the keyword def 
• … that can use parameters (placeholders)
What is a function, anyway? 
• Reusable bit of Python code 
• … beginning with the keyword def 
• … that can use parameters (placeholders) 
• … that can provide a return value
Define a Function 
>>> def x_squared(x):! 
... return x * x
Use a Function 
>>> def x_squared(x):! 
... return x * x! 
...! 
>>> x_squared(1)! 
1! 
>>> x_squared(2)! 
4! 
>>> x_squared(4)! 
16
Use a Function 
• To actually execute the 
function we’ve defined, we 
need to call or invoke it. 
>>> def x_squared(x):! 
... return x * x! 
...! 
>>> x_squared(1)! 
1! 
>>> x_squared(2)! 
4! 
>>> x_squared(4)! 
16
Use a Function 
• To actually execute the 
function we’ve defined, we 
need to call or invoke it. 
• In Python, we call functions 
by placing parentheses after 
the function name… 
>>> def x_squared(x):! 
... return x * x! 
...! 
>>> x_squared(1)! 
1! 
>>> x_squared(2)! 
4! 
>>> x_squared(4)! 
16
Use a Function 
• To actually execute the 
function we’ve defined, we 
need to call or invoke it. 
• In Python, we call functions 
by placing parentheses after 
the function name… 
• … providing arguments 
which match up with the 
parameters used when 
defining the function 
>>> def x_squared(x):! 
... return x * x! 
...! 
>>> x_squared(1)! 
1! 
>>> x_squared(2)! 
4! 
>>> x_squared(4)! 
16
Substitution 
x_squared(4)
Substitution 
x_squared(4) >>> def x_squared(x):! 
... return x * x
Substitution 
x_squared(4) >>> def x_squared(x):! 
... return x * x 
x = 4! 
return x * x
Substitution 
x_squared(4) >>> def x_squared(x):! 
... return x * x 
x = 4! 
return x * x 
4 * 4
Substitution 
x_squared(4) >>> def x_squared(x):! 
... return x * x 
x = 4! 
return x * x 
4 * 4 
16
Recursion
Recursion 
• Functions can call themselves
Recursion 
• Functions can call themselves 
• … we call this recursion
Recursion 
>>> def x_fact(x):! 
... if x < 2:! 
... return 1! 
... else:! 
... return x * x_fact(x-1)! 
...! 
>>> x_fact(3)! 
6
Recursion, step-by-step 
fact(3)
Recursion, step-by-step 
fact(3) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
return 3 * x_fact(3-1) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) return 3 * x_fact(3-1) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) 
(3 * (2 * fact(1))) 
return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) 
(3 * (2 * fact(1))) 
return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
return 1 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) 
(3 * (2 * fact(1))) 
(3 * (2 * (1))) 
return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
return 1 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) 
(3 * (2 * fact(1))) 
(3 * (2 * (1))) 
(3 * (2)) 
return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
return 1 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Recursion, step-by-step 
fact(3) 
(3 * fact(2)) 
(3 * (2 * fact(1))) 
(3 * (2 * (1))) 
(3 * (2)) 
return 3 * x_fact(3-1) 
return 2 * x_fact(2-1) 
return 1 
(6) 
def x_fact(x):! 
if x < 2:! 
return 1! 
else:! 
return x * x_fact(x-1)
Different ways to call 
functions
Different ways to call 
functions 
def my_awesome_function(something): …
Different ways to call 
functions 
def my_awesome_function(something): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): … 
def my_awesome_function(something, something_else, banana, apple): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): … 
def my_awesome_function(something, something_else, banana, apple): …
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): … 
def my_awesome_function(something, something_else, banana, apple): … 
def my_awesome_function(something, something_else, banana, apple, pear): ...
Different ways to call 
functions 
def my_awesome_function(something): … 
def my_awesome_function(something, something_else): … 
def my_awesome_function(something, something_else, banana): … 
def my_awesome_function(something, something_else, banana, apple): … 
def my_awesome_function(something, something_else, banana, apple, pear): ... 
>>> my_awesome_function(1, 4, 6, ... # now was it 
banana, apple, pear or apple, pear, banana?!
Named Arguments 
>>> my_awesome_function(! 
something=1,! 
something_else=4,! 
banana=6,! 
pear=9,! 
apple=12)
Default Arguments 
• When you’re calling a function, you have to give 
Python all the argument values (1 per 
parameter)
Default Arguments 
• When you’re calling a function, you have to give 
Python all the argument values (1 per 
parameter) 
• … but some of these can have default values
Default Arguments
Default Arguments 
def my_awesome_function(something, something_else,
Default Arguments 
def my_awesome_function(something, something_else, 
banana=1, apple=2, pear=3): ...
Default Arguments 
def my_awesome_function(something, something_else, 
banana=1, apple=2, pear=3): ... 
Now when you say this:
Default Arguments 
def my_awesome_function(something, something_else, 
banana=1, apple=2, pear=3): ... 
Now when you say this: 
>>> my_awesome_function(1, 4, 6)
Default Arguments 
def my_awesome_function(something, something_else, 
banana=1, apple=2, pear=3): ... 
Now when you say this: 
>>> my_awesome_function(1, 4, 6) 
It means this:
Default Arguments 
def my_awesome_function(something, something_else, 
banana=1, apple=2, pear=3): ... 
Now when you say this: 
>>> my_awesome_function(1, 4, 6) 
It means this: 
>>> my_awesome_function(! 
1, 4, 6,! 
apple=2, pear=3)
Variable Parameters 
• Sometimes it’s nice to be able to call a function 
with different numbers of arguments…
Variable Parameters 
• Sometimes it’s nice to be able to call a function 
with different numbers of arguments… 
• … something like sum(1,2,3) or sum(1,2)…
Variable Parameters 
def sum(*values):! 
result = 0! 
for v in values:! 
result += v! 
return result
Variable Parameters 
• Python “packs” all the 
remaining arguments into a 
tuple 
def sum(*values):! 
result = 0! 
for v in values:! 
result += v! 
return result
Variable Parameters 
• Python “packs” all the 
remaining arguments into a 
tuple 
• You can then pass any 
number of positional 
arguments to the function 
def sum(*values):! 
result = 0! 
for v in values:! 
result += v! 
return result
Variable Parameters 
• Python “packs” all the 
remaining arguments into a 
tuple 
• You can then pass any 
number of positional 
arguments to the function 
def sum(*values):! 
result = 0! 
for v in values:! 
result += v! 
return result 
A tuple is like a list you 
can’t modify, e.g. (1,2,3)
Variable Arguments 
>>> def sum(*values):! 
... result = 0! 
... for v in values:! 
... result += v! 
... return result! 
...! 
>>> sum(*[1,2,3])! 
6
Variable Arguments 
• Python “unpacks” the tuple/ 
list/etc. into separate 
arguments 
>>> def sum(*values):! 
... result = 0! 
... for v in values:! 
... result += v! 
... return result! 
...! 
>>> sum(*[1,2,3])! 
6
Variable Arguments 
• Python “unpacks” the tuple/ 
list/etc. into separate 
arguments 
• You can call functions that use 
variable or fixed arguments 
this way 
>>> def sum(*values):! 
... result = 0! 
... for v in values:! 
... result += v! 
... return result! 
...! 
>>> sum(*[1,2,3])! 
6
Variable Arguments 
• Python “unpacks” the tuple/ 
list/etc. into separate 
arguments 
• You can call functions that use 
variable or fixed arguments 
this way 
>>> def sum(*values):! 
... result = 0! 
... for v in values:! 
... result += v! 
... return result! 
...! 
>>> sum(*[1,2,3])! 
6 
>>> def x_times_y(x, y):! 
... return x * y! 
...! 
>>> x_times_y(*[4,2])! 
8
Keyword Parameters
Keyword Parameters 
• Sometimes I want a function, but I don’t know 
what I want to name the arguments…
Keyword Parameters 
• Sometimes I want a function, but I don’t know 
what I want to name the arguments… 
• … hard to come up with a really simple example, 
but hopefully this makes sense…
Keyword Parameters
Keyword Parameters 
>>> def make_dict(**kwargs):! 
... result = {}! 
... for k, v in kwargs.items():! 
... result[k] = v! 
... return result! 
...! 
>>> make_dict(a=5, b=6)! 
{'a': 5, 'b': 6}
Keyword Parameters 
• Python “packs” all the 
remaining named arguments 
into a dict 
>>> def make_dict(**kwargs):! 
... result = {}! 
... for k, v in kwargs.items():! 
... result[k] = v! 
... return result! 
...! 
>>> make_dict(a=5, b=6)! 
{'a': 5, 'b': 6}
Keyword Parameters 
• Python “packs” all the 
remaining named arguments 
into a dict 
• You can then pass any 
number of named arguments 
to the function 
>>> def make_dict(**kwargs):! 
... result = {}! 
... for k, v in kwargs.items():! 
... result[k] = v! 
... return result! 
...! 
>>> make_dict(a=5, b=6)! 
{'a': 5, 'b': 6}
Keyword Parameters 
• Python “packs” all the 
remaining named arguments 
into a dict 
• You can then pass any 
number of named arguments 
to the function 
A dict is like a directory 
mapping “keys” to 
“values” (e.g. {key: value}) 
>>> def make_dict(**kwargs):! 
... result = {}! 
... for k, v in kwargs.items():! 
... result[k] = v! 
... return result! 
...! 
>>> make_dict(a=5, b=6)! 
{'a': 5, 'b': 6}
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6)
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6) def make_dict(**kwargs):! 
result = {}! 
for k, v in kwargs.items():! 
result[k] = v! 
return result
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6) def make_dict(**kwargs):! 
result = {}! 
for k, v in kwargs.items():! 
result[k] = v! 
return result 
kwargs = {'a': 5, 'b': 6}! 
make_dict(**kwargs)
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6) def make_dict(**kwargs):! 
result = {}! 
for k, v in kwargs.items():! 
result[k] = v! 
return result 
kwargs = {'a': 5, 'b': 6}! 
make_dict(**kwargs) 
kwargs = {'a': 5, 'b': 6}! 
result = {}! 
for k, v in {'a': 5, 'b': 6}.items():! 
result[k] = v! 
return result
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6) def make_dict(**kwargs):! 
result = {}! 
for k, v in kwargs.items():! 
result[k] = v! 
return result 
kwargs = {'a': 5, 'b': 6}! 
make_dict(**kwargs) 
kwargs = {'a': 5, 'b': 6}! 
result = {}! 
for k, v in {'a': 5, 'b': 6}.items():! 
result[k] = v! 
return result 
result = {}! 
result = {'a': 5}! 
result = {'a': 5, 'b': 6}! 
return result
Keyword Parameters Step by 
Step 
>>> make_dict(a=5, b=6) def make_dict(**kwargs):! 
result = {}! 
for k, v in kwargs.items():! 
result[k] = v! 
return result 
kwargs = {'a': 5, 'b': 6}! 
make_dict(**kwargs) 
kwargs = {'a': 5, 'b': 6}! 
result = {}! 
for k, v in {'a': 5, 'b': 6}.items():! 
result[k] = v! 
return result 
result = {}! 
result = {'a': 5}! 
result = {'a': 5, 'b': 6}! 
return result 
{'a': 5, 'b': 6}
Keyword Arguments 
>>> make_dict(**{'a': 10, 'b': 20})! 
{'a': 10, 'b': 20}
Keyword Arguments 
• Python “unpacks” the dict into 
separate arguments 
>>> make_dict(**{'a': 10, 'b': 20})! 
{'a': 10, 'b': 20}
Keyword Arguments 
• Python “unpacks” the dict into 
separate arguments 
• You can call functions that use 
keyword or fixed arguments 
this way 
>>> make_dict(**{'a': 10, 'b': 20})! 
{'a': 10, 'b': 20}
Keyword Arguments 
>>> make_dict(**{'a': 10, 'b': 20})! 
{'a': 10, 'b': 20} 
• Python “unpacks” the dict into 
separate arguments 
• You can call functions that use 
keyword or fixed arguments 
this way 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct)! 
12
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct)
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct) 
def x_times_y(x, y):! 
return x * y
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct) 
x_times_y(x=2, y=6) 
def x_times_y(x, y):! 
return x * y
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct) 
x_times_y(x=2, y=6) 
def x_times_y(x, y):! 
return x * y 
x=2! 
y=6! 
return x * y
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct) 
x_times_y(x=2, y=6) 
def x_times_y(x, y):! 
return x * y 
x=2! 
y=6! 
return x * y 
return 2 * 6
Keyword Arguments Step by 
Step 
>>> dct = {'x': 2, 'y': 6}! 
>>> x_times_y(**dct) 
x_times_y(x=2, y=6) 
def x_times_y(x, y):! 
return x * y 
x=2! 
y=6! 
return x * y 
return 2 * 6 
12
Is there more?
Is there more? 
• Of course there’s more, but it’s beginner’s night ;-)
Is there more? 
• Of course there’s more, but it’s beginner’s night ;-) 
• But what can I do now?
Is there more? 
• Of course there’s more, but it’s beginner’s night ;-) 
• But what can I do now? 
• Write functions to reuse code (DRY)
Is there more? 
• Of course there’s more, but it’s beginner’s night ;-) 
• But what can I do now? 
• Write functions to reuse code (DRY) 
• Write recursive functions
Is there more? 
• Of course there’s more, but it’s beginner’s night ;-) 
• But what can I do now? 
• Write functions to reuse code (DRY) 
• Write recursive functions 
• Create and use functions with different kinds of 
arguments and parameters (named, *args, 
**kwargs)
“Any questions?” 
–Rick Copeland

More Related Content

What's hot

C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning ObjectsJay Patel
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
Python-oop
Python-oopPython-oop
Python-oopRTS Tech
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++Jawad Khan
 
Python functions
Python functionsPython functions
Python functionsAliyamanasa
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsPhilip Schwarz
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an examplePhilip Schwarz
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 

What's hot (20)

C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Python-oop
Python-oopPython-oop
Python-oop
 
Control statements
Control statementsControl statements
Control statements
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python recursion
Python recursionPython recursion
Python recursion
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Python functions
Python functionsPython functions
Python functions
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and Cats
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 

Similar to Python Functions (PyAtl Beginners Night)

Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsYashJain47002
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Lesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptLesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptssuser78a386
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Samuel Fortier-Galarneau
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc Gouw
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱Mohammad Reza Kamalifard
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].pptGaganvirKaur
 

Similar to Python Functions (PyAtl Beginners Night) (20)

PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Lesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptLesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.ppt
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
 
Python basic
Python basicPython basic
Python basic
 

More from Rick Copeland

Schema Design at Scale
Schema Design at ScaleSchema Design at Scale
Schema Design at ScaleRick Copeland
 
Building Your First MongoDB Application
Building Your First MongoDB ApplicationBuilding Your First MongoDB Application
Building Your First MongoDB ApplicationRick Copeland
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and PyramidRick Copeland
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDBRick Copeland
 
Chef on Python and MongoDB
Chef on Python and MongoDBChef on Python and MongoDB
Chef on Python and MongoDBRick Copeland
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioRick Copeland
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
 
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQRealtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQRick Copeland
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRick Copeland
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForgeAllura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForgeRick Copeland
 
MongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDBMongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDBRick Copeland
 

More from Rick Copeland (12)

Schema Design at Scale
Schema Design at ScaleSchema Design at Scale
Schema Design at Scale
 
Building Your First MongoDB Application
Building Your First MongoDB ApplicationBuilding Your First MongoDB Application
Building Your First MongoDB Application
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and Pyramid
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
 
Chef on Python and MongoDB
Chef on Python and MongoDBChef on Python and MongoDB
Chef on Python and MongoDB
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQRealtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForgeAllura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForge
 
MongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDBMongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDB
 

Recently uploaded

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Python Functions (PyAtl Beginners Night)

  • 4. Beginner’s Night Python Functions Rick Copeland
  • 5. What is a function, anyway?
  • 6. What is a function, anyway? • Reusable bit of Python code
  • 7. What is a function, anyway? • Reusable bit of Python code • … beginning with the keyword def
  • 8. What is a function, anyway? • Reusable bit of Python code • … beginning with the keyword def • … that can use parameters (placeholders)
  • 9. What is a function, anyway? • Reusable bit of Python code • … beginning with the keyword def • … that can use parameters (placeholders) • … that can provide a return value
  • 10. Define a Function >>> def x_squared(x):! ... return x * x
  • 11. Use a Function >>> def x_squared(x):! ... return x * x! ...! >>> x_squared(1)! 1! >>> x_squared(2)! 4! >>> x_squared(4)! 16
  • 12. Use a Function • To actually execute the function we’ve defined, we need to call or invoke it. >>> def x_squared(x):! ... return x * x! ...! >>> x_squared(1)! 1! >>> x_squared(2)! 4! >>> x_squared(4)! 16
  • 13. Use a Function • To actually execute the function we’ve defined, we need to call or invoke it. • In Python, we call functions by placing parentheses after the function name… >>> def x_squared(x):! ... return x * x! ...! >>> x_squared(1)! 1! >>> x_squared(2)! 4! >>> x_squared(4)! 16
  • 14. Use a Function • To actually execute the function we’ve defined, we need to call or invoke it. • In Python, we call functions by placing parentheses after the function name… • … providing arguments which match up with the parameters used when defining the function >>> def x_squared(x):! ... return x * x! ...! >>> x_squared(1)! 1! >>> x_squared(2)! 4! >>> x_squared(4)! 16
  • 16. Substitution x_squared(4) >>> def x_squared(x):! ... return x * x
  • 17. Substitution x_squared(4) >>> def x_squared(x):! ... return x * x x = 4! return x * x
  • 18. Substitution x_squared(4) >>> def x_squared(x):! ... return x * x x = 4! return x * x 4 * 4
  • 19. Substitution x_squared(4) >>> def x_squared(x):! ... return x * x x = 4! return x * x 4 * 4 16
  • 21. Recursion • Functions can call themselves
  • 22. Recursion • Functions can call themselves • … we call this recursion
  • 23. Recursion >>> def x_fact(x):! ... if x < 2:! ... return 1! ... else:! ... return x * x_fact(x-1)! ...! >>> x_fact(3)! 6
  • 25. Recursion, step-by-step fact(3) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 26. Recursion, step-by-step fact(3) return 3 * x_fact(3-1) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 27. Recursion, step-by-step fact(3) (3 * fact(2)) return 3 * x_fact(3-1) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 28. Recursion, step-by-step fact(3) (3 * fact(2)) return 3 * x_fact(3-1) return 2 * x_fact(2-1) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 29. Recursion, step-by-step fact(3) (3 * fact(2)) (3 * (2 * fact(1))) return 3 * x_fact(3-1) return 2 * x_fact(2-1) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 30. Recursion, step-by-step fact(3) (3 * fact(2)) (3 * (2 * fact(1))) return 3 * x_fact(3-1) return 2 * x_fact(2-1) return 1 def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 31. Recursion, step-by-step fact(3) (3 * fact(2)) (3 * (2 * fact(1))) (3 * (2 * (1))) return 3 * x_fact(3-1) return 2 * x_fact(2-1) return 1 def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 32. Recursion, step-by-step fact(3) (3 * fact(2)) (3 * (2 * fact(1))) (3 * (2 * (1))) (3 * (2)) return 3 * x_fact(3-1) return 2 * x_fact(2-1) return 1 def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 33. Recursion, step-by-step fact(3) (3 * fact(2)) (3 * (2 * fact(1))) (3 * (2 * (1))) (3 * (2)) return 3 * x_fact(3-1) return 2 * x_fact(2-1) return 1 (6) def x_fact(x):! if x < 2:! return 1! else:! return x * x_fact(x-1)
  • 34. Different ways to call functions
  • 35. Different ways to call functions def my_awesome_function(something): …
  • 36. Different ways to call functions def my_awesome_function(something): …
  • 37. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): …
  • 38. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): …
  • 39. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): …
  • 40. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): …
  • 41. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): … def my_awesome_function(something, something_else, banana, apple): …
  • 42. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): … def my_awesome_function(something, something_else, banana, apple): …
  • 43. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): … def my_awesome_function(something, something_else, banana, apple): … def my_awesome_function(something, something_else, banana, apple, pear): ...
  • 44. Different ways to call functions def my_awesome_function(something): … def my_awesome_function(something, something_else): … def my_awesome_function(something, something_else, banana): … def my_awesome_function(something, something_else, banana, apple): … def my_awesome_function(something, something_else, banana, apple, pear): ... >>> my_awesome_function(1, 4, 6, ... # now was it banana, apple, pear or apple, pear, banana?!
  • 45. Named Arguments >>> my_awesome_function(! something=1,! something_else=4,! banana=6,! pear=9,! apple=12)
  • 46. Default Arguments • When you’re calling a function, you have to give Python all the argument values (1 per parameter)
  • 47. Default Arguments • When you’re calling a function, you have to give Python all the argument values (1 per parameter) • … but some of these can have default values
  • 49. Default Arguments def my_awesome_function(something, something_else,
  • 50. Default Arguments def my_awesome_function(something, something_else, banana=1, apple=2, pear=3): ...
  • 51. Default Arguments def my_awesome_function(something, something_else, banana=1, apple=2, pear=3): ... Now when you say this:
  • 52. Default Arguments def my_awesome_function(something, something_else, banana=1, apple=2, pear=3): ... Now when you say this: >>> my_awesome_function(1, 4, 6)
  • 53. Default Arguments def my_awesome_function(something, something_else, banana=1, apple=2, pear=3): ... Now when you say this: >>> my_awesome_function(1, 4, 6) It means this:
  • 54. Default Arguments def my_awesome_function(something, something_else, banana=1, apple=2, pear=3): ... Now when you say this: >>> my_awesome_function(1, 4, 6) It means this: >>> my_awesome_function(! 1, 4, 6,! apple=2, pear=3)
  • 55. Variable Parameters • Sometimes it’s nice to be able to call a function with different numbers of arguments…
  • 56. Variable Parameters • Sometimes it’s nice to be able to call a function with different numbers of arguments… • … something like sum(1,2,3) or sum(1,2)…
  • 57. Variable Parameters def sum(*values):! result = 0! for v in values:! result += v! return result
  • 58. Variable Parameters • Python “packs” all the remaining arguments into a tuple def sum(*values):! result = 0! for v in values:! result += v! return result
  • 59. Variable Parameters • Python “packs” all the remaining arguments into a tuple • You can then pass any number of positional arguments to the function def sum(*values):! result = 0! for v in values:! result += v! return result
  • 60. Variable Parameters • Python “packs” all the remaining arguments into a tuple • You can then pass any number of positional arguments to the function def sum(*values):! result = 0! for v in values:! result += v! return result A tuple is like a list you can’t modify, e.g. (1,2,3)
  • 61. Variable Arguments >>> def sum(*values):! ... result = 0! ... for v in values:! ... result += v! ... return result! ...! >>> sum(*[1,2,3])! 6
  • 62. Variable Arguments • Python “unpacks” the tuple/ list/etc. into separate arguments >>> def sum(*values):! ... result = 0! ... for v in values:! ... result += v! ... return result! ...! >>> sum(*[1,2,3])! 6
  • 63. Variable Arguments • Python “unpacks” the tuple/ list/etc. into separate arguments • You can call functions that use variable or fixed arguments this way >>> def sum(*values):! ... result = 0! ... for v in values:! ... result += v! ... return result! ...! >>> sum(*[1,2,3])! 6
  • 64. Variable Arguments • Python “unpacks” the tuple/ list/etc. into separate arguments • You can call functions that use variable or fixed arguments this way >>> def sum(*values):! ... result = 0! ... for v in values:! ... result += v! ... return result! ...! >>> sum(*[1,2,3])! 6 >>> def x_times_y(x, y):! ... return x * y! ...! >>> x_times_y(*[4,2])! 8
  • 66. Keyword Parameters • Sometimes I want a function, but I don’t know what I want to name the arguments…
  • 67. Keyword Parameters • Sometimes I want a function, but I don’t know what I want to name the arguments… • … hard to come up with a really simple example, but hopefully this makes sense…
  • 69. Keyword Parameters >>> def make_dict(**kwargs):! ... result = {}! ... for k, v in kwargs.items():! ... result[k] = v! ... return result! ...! >>> make_dict(a=5, b=6)! {'a': 5, 'b': 6}
  • 70. Keyword Parameters • Python “packs” all the remaining named arguments into a dict >>> def make_dict(**kwargs):! ... result = {}! ... for k, v in kwargs.items():! ... result[k] = v! ... return result! ...! >>> make_dict(a=5, b=6)! {'a': 5, 'b': 6}
  • 71. Keyword Parameters • Python “packs” all the remaining named arguments into a dict • You can then pass any number of named arguments to the function >>> def make_dict(**kwargs):! ... result = {}! ... for k, v in kwargs.items():! ... result[k] = v! ... return result! ...! >>> make_dict(a=5, b=6)! {'a': 5, 'b': 6}
  • 72. Keyword Parameters • Python “packs” all the remaining named arguments into a dict • You can then pass any number of named arguments to the function A dict is like a directory mapping “keys” to “values” (e.g. {key: value}) >>> def make_dict(**kwargs):! ... result = {}! ... for k, v in kwargs.items():! ... result[k] = v! ... return result! ...! >>> make_dict(a=5, b=6)! {'a': 5, 'b': 6}
  • 73. Keyword Parameters Step by Step >>> make_dict(a=5, b=6)
  • 74. Keyword Parameters Step by Step >>> make_dict(a=5, b=6) def make_dict(**kwargs):! result = {}! for k, v in kwargs.items():! result[k] = v! return result
  • 75. Keyword Parameters Step by Step >>> make_dict(a=5, b=6) def make_dict(**kwargs):! result = {}! for k, v in kwargs.items():! result[k] = v! return result kwargs = {'a': 5, 'b': 6}! make_dict(**kwargs)
  • 76. Keyword Parameters Step by Step >>> make_dict(a=5, b=6) def make_dict(**kwargs):! result = {}! for k, v in kwargs.items():! result[k] = v! return result kwargs = {'a': 5, 'b': 6}! make_dict(**kwargs) kwargs = {'a': 5, 'b': 6}! result = {}! for k, v in {'a': 5, 'b': 6}.items():! result[k] = v! return result
  • 77. Keyword Parameters Step by Step >>> make_dict(a=5, b=6) def make_dict(**kwargs):! result = {}! for k, v in kwargs.items():! result[k] = v! return result kwargs = {'a': 5, 'b': 6}! make_dict(**kwargs) kwargs = {'a': 5, 'b': 6}! result = {}! for k, v in {'a': 5, 'b': 6}.items():! result[k] = v! return result result = {}! result = {'a': 5}! result = {'a': 5, 'b': 6}! return result
  • 78. Keyword Parameters Step by Step >>> make_dict(a=5, b=6) def make_dict(**kwargs):! result = {}! for k, v in kwargs.items():! result[k] = v! return result kwargs = {'a': 5, 'b': 6}! make_dict(**kwargs) kwargs = {'a': 5, 'b': 6}! result = {}! for k, v in {'a': 5, 'b': 6}.items():! result[k] = v! return result result = {}! result = {'a': 5}! result = {'a': 5, 'b': 6}! return result {'a': 5, 'b': 6}
  • 79. Keyword Arguments >>> make_dict(**{'a': 10, 'b': 20})! {'a': 10, 'b': 20}
  • 80. Keyword Arguments • Python “unpacks” the dict into separate arguments >>> make_dict(**{'a': 10, 'b': 20})! {'a': 10, 'b': 20}
  • 81. Keyword Arguments • Python “unpacks” the dict into separate arguments • You can call functions that use keyword or fixed arguments this way >>> make_dict(**{'a': 10, 'b': 20})! {'a': 10, 'b': 20}
  • 82. Keyword Arguments >>> make_dict(**{'a': 10, 'b': 20})! {'a': 10, 'b': 20} • Python “unpacks” the dict into separate arguments • You can call functions that use keyword or fixed arguments this way >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct)! 12
  • 83. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct)
  • 84. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct) def x_times_y(x, y):! return x * y
  • 85. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct) x_times_y(x=2, y=6) def x_times_y(x, y):! return x * y
  • 86. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct) x_times_y(x=2, y=6) def x_times_y(x, y):! return x * y x=2! y=6! return x * y
  • 87. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct) x_times_y(x=2, y=6) def x_times_y(x, y):! return x * y x=2! y=6! return x * y return 2 * 6
  • 88. Keyword Arguments Step by Step >>> dct = {'x': 2, 'y': 6}! >>> x_times_y(**dct) x_times_y(x=2, y=6) def x_times_y(x, y):! return x * y x=2! y=6! return x * y return 2 * 6 12
  • 90. Is there more? • Of course there’s more, but it’s beginner’s night ;-)
  • 91. Is there more? • Of course there’s more, but it’s beginner’s night ;-) • But what can I do now?
  • 92. Is there more? • Of course there’s more, but it’s beginner’s night ;-) • But what can I do now? • Write functions to reuse code (DRY)
  • 93. Is there more? • Of course there’s more, but it’s beginner’s night ;-) • But what can I do now? • Write functions to reuse code (DRY) • Write recursive functions
  • 94. Is there more? • Of course there’s more, but it’s beginner’s night ;-) • But what can I do now? • Write functions to reuse code (DRY) • Write recursive functions • Create and use functions with different kinds of arguments and parameters (named, *args, **kwargs)
  • 95.
  • 96.