SlideShare a Scribd company logo
functions!
The plan!
Basics: data types (and operations & calculations)
Basics: conditionals & iteration
Basics: lists, tuples, dictionaries
Basics: writing functions
Reading & writing files: opening, parsing & formats
Working with numbers: numpy & scipy
Making plots: matplotlib & pylab
… if you guys want more after all of that …
Writing better code: functions, pep8, classes
Working with numbers: Numpy & Scipy (advanced)
Other modules: Pandas & Scikit-learn
Interactive notebooks: ipython & jupyter
Advanced topics: virtual environments & version control
functions
# lets define a function
def print_hello(name):
print "Hello", name, ", it's a nice day for functions!"
# now we can call (or run, or execute) the function
print_hello("Marc")
functions
# lets define a function
def print_hello(name):
print "Hello", name, ", it's a nice day for functions!"
# now we can call (or run, or execute) the function
print_hello("Marc") Defining the function:
def function_name(arg1, arg2, ...):
do stuff here
Running the function:
function_name(value1, value2, ...):
indentation!
functions
# lets define a function
def print_hello(name):
print "Hello", name, ", it's a nice day for functions!"
# now we can call (or run, or execute) the function
print_hello("Marc")
# let's add some arguments
def print_hello(name, weather):
print "Hello", name, ", it's", weather.
print "Perfect weather for writing functions!"
print_hello("Marc", "Sunny")
print hello("Gengis", "Raining")
# arguments are optional
def print_hello():
print "Hello, this function is a little boring, right?"
# to run a function with 0 arguments, use empty parentheses
print_hello()
Defining the function:
def function_name(arg1, arg2, ...):
do stuff here
Running the function:
function_name(value1, value2, ...):
indentation!
functions
# the function definition can be any code!
def print_hello(name, weather, number):
print "Hello", name, ", it's", weather.
if weather == "Sunny":
print "Go outside and play!"
else:
print "Stay inside and program!"
print "Here are some numbers:"
for i in range(number):
print i
print "This is one hell of a long function!"
# nothing happens until the function is run!
print_hello("Marc","Raining", 200)
exercise! wohoo!
Write function that takes two arguments: a name and a number. The function then
prints the name "number" time.
---- names.py ----
def name_repeat(????):
????
????
????
name_repeat("Marc", 10)
functions: arguments
# positional arguments are defined by their position
def print_hello(name, weather,):
print "Hello", name, ", the weather is", weather.
print_hello("Marc", "Sunny")
print_hello("Stormy", "Thor")
functions: arguments
# positional arguments are defined by their position
def print_hello(name, weather,):
print "Hello", name, ", the weather is", weather.
print_hello("Marc", "Sunny")
print_hello("Stormy", "Thor")
# keyword arguments are optional, and have default values.
def print_hello(name, weather, drink= "Tea", snack= "Cookie"):
print "Hello", name, ", the weather is", weather
print "Why don’t you drink a ", drink, "with some", snack
print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos")
functions: arguments
# positional arguments are defined by their position
def print_hello(name, weather,):
print "Hello", name, ", the weather is", weather.
print_hello("Marc", "Sunny")
print_hello("Stormy", "Thor")
# keyword arguments are optional, and have default values.
def print_hello(name, weather, drink= "Tea", snack= "Cookie"):
print "Hello", name, ", the weather is", weather.
print "Why don’t you drink a ", drink, "with some", snack
print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos")
Defining arguments:
def function_name(arg1, arg2, … kwarg1=default1, kwarg2=default2, … ):
Code goes here
positional keyword
functions: arguments
# positional arguments are defined by their position
def print_hello(name, weather,):
print "Hello", name, ", the weather is", weather.
print_hello("Marc", "Sunny")
print_hello("Stormy", "Thor")
# keyword arguments are optional, and have default values.
def print_hello(name, weather, drink= "Tea", snack= "Cookie"):
print "Hello", name, ", the weather is", weather.
print "Why don’t you drink a ", drink, "with some", snack
print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos")
# keyword arguments are optional, and the order doesn’t matter
print_hello("Bob","Rainy")
print_hello("Bob","Rainy", snack="Cake", drink="Coffee")
functions: returning values
# functions are not usually used for printing
# typically they return a value
def times_two_plus_three(x):
return x * 2 + 3
# we can now use this function
n = times_two_plus_three(5)
print n
functions: returning values
# functions are not usually used for printing
# typically they return a value
def times_two_plus_three(x):
return x * 2 + 3
# we can now use this function
n = times_two_plus_three(5)
print n
Defining the function:
def function_name(arg1, arg2, ...):
do stuff here
return some_value
Running the function:
answer = function_name(value1, value2, ...):
functions: returning values
# functions are not usually used for printing
# typically they return a value
def times_two_plus_three(x):
return x * 2 + 3
# we can now use this function
n = times_two_plus_three(5)
print n
# let's make it a little more complicated.
# and add some documentation as well
def my_complex_calculation(a, b, c):
""" This returns the value of:
a * b + c
"""
result = x * b + c
return result
# we can now use this function
print my_complex_function(8, 1, 12)
Defining the function:
def function_name(arg1, arg2, ...):
""" Documentation (comment)
"""
do stuff here
return some_value
Running the function:
answer = function_name(value1, value2, ...):
exercises!
- Write function that takes three inputs (numbers x, y and z), and produces the
result of : a + b - c. Use return to be able to store and use the value later.
---- calc.py ----
def my_calculation(????):
????
????
????
x = my_calculation(12, 13, 14)
print "The complex calculation with 12, 13 and 14 resulted in", x
version 2: as above, but if no numbers for b or c are specified, use 5 and 10 as default
values.

More Related Content

What's hot (19)

PDF
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 
PDF
Functions in python
Ilian Iliev
 
PDF
Python Basic
Adityamelia Permana
 
PDF
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
PDF
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
PDF
Class 2: Welcome part 2
Marc Gouw
 
PDF
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
PDF
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
PDF
Class 5: If, while & lists
Marc Gouw
 
PDF
Begin with Python
Narong Intiruk
 
PDF
iOS와 케라스의 만남
Mijeong Jeon
 
PDF
Implode & Explode in PHP
Vineet Kumar Saini
 
PDF
프알못의 Keras 사용기
Mijeong Jeon
 
PPTX
Python Homework Help
Programming Homework Help
 
PPTX
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
 
PDF
Python decorators (中文)
Yiwei Chen
 
PDF
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
DOCX
PERL for QA - Important Commands and applications
Sunil Kumar Gunasekaran
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 
Functions in python
Ilian Iliev
 
Python Basic
Adityamelia Permana
 
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
Shift Conference
 
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
Class 2: Welcome part 2
Marc Gouw
 
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Class 5: If, while & lists
Marc Gouw
 
Begin with Python
Narong Intiruk
 
iOS와 케라스의 만남
Mijeong Jeon
 
Implode & Explode in PHP
Vineet Kumar Saini
 
프알못의 Keras 사용기
Mijeong Jeon
 
Python Homework Help
Programming Homework Help
 
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
 
Python decorators (中文)
Yiwei Chen
 
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
PERL for QA - Important Commands and applications
Sunil Kumar Gunasekaran
 

Viewers also liked (10)

PDF
Class 3: if/else
Marc Gouw
 
PDF
Class 4: For and while
Marc Gouw
 
PDF
Class 8b: Numpy & Matplotlib
Marc Gouw
 
PDF
Class 1: Welcome to programming
Marc Gouw
 
PDF
Class 8a: Modules and imports
Marc Gouw
 
PDF
Class 6: Lists & dictionaries
Marc Gouw
 
PDF
Class 7b: Files & File I/O
Marc Gouw
 
PDF
Introduction to SlideShare for Businesses
SlideShare
 
PDF
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
PDF
Getting Started With SlideShare
SlideShare
 
Class 3: if/else
Marc Gouw
 
Class 4: For and while
Marc Gouw
 
Class 8b: Numpy & Matplotlib
Marc Gouw
 
Class 1: Welcome to programming
Marc Gouw
 
Class 8a: Modules and imports
Marc Gouw
 
Class 6: Lists & dictionaries
Marc Gouw
 
Class 7b: Files & File I/O
Marc Gouw
 
Introduction to SlideShare for Businesses
SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Getting Started With SlideShare
SlideShare
 
Ad

Similar to Class 7a: Functions (20)

PPTX
powerpoint 2-7.pptx
JuanPicasso7
 
PPTX
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
PDF
Python_Functions.pdf
MikialeTesfamariam
 
PPTX
Introduction to Python External Course !!!
SlrcMalgn
 
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
PDF
Functions2.pdf
prasnt1
 
PDF
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
PDF
Chapter Functions for grade 12 computer Science
KrithikaTM
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PPTX
Python Lecture 4
Inzamam Baig
 
PPTX
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
PPTX
Functions, List and String methods
PranavSB
 
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
PDF
Functions and modules in python
Karin Lagesen
 
PDF
notes.pdf
Anant Mehrotra
 
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
PDF
Talk Code
Agiliq Solutions
 
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
PDF
python.pdf
SwapnilGujar10
 
PPT
Python Training v2
ibaydan
 
powerpoint 2-7.pptx
JuanPicasso7
 
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Python_Functions.pdf
MikialeTesfamariam
 
Introduction to Python External Course !!!
SlrcMalgn
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
Functions2.pdf
prasnt1
 
beginners_python_cheat_sheet_pcc_functions.pdf
GuarachandarChand
 
Chapter Functions for grade 12 computer Science
KrithikaTM
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python Lecture 4
Inzamam Baig
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
Functions, List and String methods
PranavSB
 
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functions and modules in python
Karin Lagesen
 
notes.pdf
Anant Mehrotra
 
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
Talk Code
Agiliq Solutions
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
python.pdf
SwapnilGujar10
 
Python Training v2
ibaydan
 
Ad

Recently uploaded (20)

PPTX
abdominal compartment syndrome presentation and treatment.pptx
LakshmiMounicaGrandh
 
PPTX
Immunopharmaceuticals and microbial Application
xxkaira1
 
PDF
A Man of the Forest: The Contributions of Gifford Pinchot
RowanSales
 
PDF
Annual report 2024 - Inria - English version.pdf
Inria
 
PPTX
Class12_Physics_Chapter2 electric potential and capacitance.pptx
mgmahati1234
 
PDF
FYS 100 final presentation on Afro cubans
RowanSales
 
PPTX
Q1 - W1 - D2 - Models of matter for science.pptx
RyanCudal3
 
PDF
Chemokines and Receptors Overview – Key to Immune Cell Signaling
Benjamin Lewis Lewis
 
DOCX
Critical Book Review (CBR) - "Hate Speech: Linguistic Perspectives"
Sahmiral Amri Rajagukguk
 
PPTX
Phage Therapy and Bacteriophage Biology.pptx
Prachi Virat
 
PDF
Plankton and Fisheries Bovas Joel Notes.pdf
J. Bovas Joel BFSc
 
PDF
The emergence of galactic thin and thick discs across cosmic history
Sérgio Sacani
 
PDF
Treatment and safety of drinking water .
psuvethapalani
 
PPTX
PEDIA IDS IN A GIST_6488b6b5-3152-4a4a-a943-20a56efddd43 (2).pptx
tdas83504
 
PPTX
Q1_Science 8_Week3-Day 1.pptx science lesson
AizaRazonado
 
PPTX
MODULE 2 Effects of Lifestyle in the Function of Respiratory and Circulator...
judithgracemangunday
 
PDF
Plant growth promoting bacterial non symbiotic
psuvethapalani
 
PPTX
ION EXCHANGE CHROMATOGRAPHY NEW PPT (JA).pptx
adhagalejotshna
 
PPTX
Pratik inorganic chemistry silicon based ppt
akshaythaker18
 
PDF
Asthamudi lake and its fisheries&importance .pdf
J. Bovas Joel BFSc
 
abdominal compartment syndrome presentation and treatment.pptx
LakshmiMounicaGrandh
 
Immunopharmaceuticals and microbial Application
xxkaira1
 
A Man of the Forest: The Contributions of Gifford Pinchot
RowanSales
 
Annual report 2024 - Inria - English version.pdf
Inria
 
Class12_Physics_Chapter2 electric potential and capacitance.pptx
mgmahati1234
 
FYS 100 final presentation on Afro cubans
RowanSales
 
Q1 - W1 - D2 - Models of matter for science.pptx
RyanCudal3
 
Chemokines and Receptors Overview – Key to Immune Cell Signaling
Benjamin Lewis Lewis
 
Critical Book Review (CBR) - "Hate Speech: Linguistic Perspectives"
Sahmiral Amri Rajagukguk
 
Phage Therapy and Bacteriophage Biology.pptx
Prachi Virat
 
Plankton and Fisheries Bovas Joel Notes.pdf
J. Bovas Joel BFSc
 
The emergence of galactic thin and thick discs across cosmic history
Sérgio Sacani
 
Treatment and safety of drinking water .
psuvethapalani
 
PEDIA IDS IN A GIST_6488b6b5-3152-4a4a-a943-20a56efddd43 (2).pptx
tdas83504
 
Q1_Science 8_Week3-Day 1.pptx science lesson
AizaRazonado
 
MODULE 2 Effects of Lifestyle in the Function of Respiratory and Circulator...
judithgracemangunday
 
Plant growth promoting bacterial non symbiotic
psuvethapalani
 
ION EXCHANGE CHROMATOGRAPHY NEW PPT (JA).pptx
adhagalejotshna
 
Pratik inorganic chemistry silicon based ppt
akshaythaker18
 
Asthamudi lake and its fisheries&importance .pdf
J. Bovas Joel BFSc
 

Class 7a: Functions

  • 2. The plan! Basics: data types (and operations & calculations) Basics: conditionals & iteration Basics: lists, tuples, dictionaries Basics: writing functions Reading & writing files: opening, parsing & formats Working with numbers: numpy & scipy Making plots: matplotlib & pylab … if you guys want more after all of that … Writing better code: functions, pep8, classes Working with numbers: Numpy & Scipy (advanced) Other modules: Pandas & Scikit-learn Interactive notebooks: ipython & jupyter Advanced topics: virtual environments & version control
  • 3. functions # lets define a function def print_hello(name): print "Hello", name, ", it's a nice day for functions!" # now we can call (or run, or execute) the function print_hello("Marc")
  • 4. functions # lets define a function def print_hello(name): print "Hello", name, ", it's a nice day for functions!" # now we can call (or run, or execute) the function print_hello("Marc") Defining the function: def function_name(arg1, arg2, ...): do stuff here Running the function: function_name(value1, value2, ...): indentation!
  • 5. functions # lets define a function def print_hello(name): print "Hello", name, ", it's a nice day for functions!" # now we can call (or run, or execute) the function print_hello("Marc") # let's add some arguments def print_hello(name, weather): print "Hello", name, ", it's", weather. print "Perfect weather for writing functions!" print_hello("Marc", "Sunny") print hello("Gengis", "Raining") # arguments are optional def print_hello(): print "Hello, this function is a little boring, right?" # to run a function with 0 arguments, use empty parentheses print_hello() Defining the function: def function_name(arg1, arg2, ...): do stuff here Running the function: function_name(value1, value2, ...): indentation!
  • 6. functions # the function definition can be any code! def print_hello(name, weather, number): print "Hello", name, ", it's", weather. if weather == "Sunny": print "Go outside and play!" else: print "Stay inside and program!" print "Here are some numbers:" for i in range(number): print i print "This is one hell of a long function!" # nothing happens until the function is run! print_hello("Marc","Raining", 200)
  • 7. exercise! wohoo! Write function that takes two arguments: a name and a number. The function then prints the name "number" time. ---- names.py ---- def name_repeat(????): ???? ???? ???? name_repeat("Marc", 10)
  • 8. functions: arguments # positional arguments are defined by their position def print_hello(name, weather,): print "Hello", name, ", the weather is", weather. print_hello("Marc", "Sunny") print_hello("Stormy", "Thor")
  • 9. functions: arguments # positional arguments are defined by their position def print_hello(name, weather,): print "Hello", name, ", the weather is", weather. print_hello("Marc", "Sunny") print_hello("Stormy", "Thor") # keyword arguments are optional, and have default values. def print_hello(name, weather, drink= "Tea", snack= "Cookie"): print "Hello", name, ", the weather is", weather print "Why don’t you drink a ", drink, "with some", snack print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos")
  • 10. functions: arguments # positional arguments are defined by their position def print_hello(name, weather,): print "Hello", name, ", the weather is", weather. print_hello("Marc", "Sunny") print_hello("Stormy", "Thor") # keyword arguments are optional, and have default values. def print_hello(name, weather, drink= "Tea", snack= "Cookie"): print "Hello", name, ", the weather is", weather. print "Why don’t you drink a ", drink, "with some", snack print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos") Defining arguments: def function_name(arg1, arg2, … kwarg1=default1, kwarg2=default2, … ): Code goes here positional keyword
  • 11. functions: arguments # positional arguments are defined by their position def print_hello(name, weather,): print "Hello", name, ", the weather is", weather. print_hello("Marc", "Sunny") print_hello("Stormy", "Thor") # keyword arguments are optional, and have default values. def print_hello(name, weather, drink= "Tea", snack= "Cookie"): print "Hello", name, ", the weather is", weather. print "Why don’t you drink a ", drink, "with some", snack print_hello("Marc", "Sunny", drink="Beer", snack="Tremocos") # keyword arguments are optional, and the order doesn’t matter print_hello("Bob","Rainy") print_hello("Bob","Rainy", snack="Cake", drink="Coffee")
  • 12. functions: returning values # functions are not usually used for printing # typically they return a value def times_two_plus_three(x): return x * 2 + 3 # we can now use this function n = times_two_plus_three(5) print n
  • 13. functions: returning values # functions are not usually used for printing # typically they return a value def times_two_plus_three(x): return x * 2 + 3 # we can now use this function n = times_two_plus_three(5) print n Defining the function: def function_name(arg1, arg2, ...): do stuff here return some_value Running the function: answer = function_name(value1, value2, ...):
  • 14. functions: returning values # functions are not usually used for printing # typically they return a value def times_two_plus_three(x): return x * 2 + 3 # we can now use this function n = times_two_plus_three(5) print n # let's make it a little more complicated. # and add some documentation as well def my_complex_calculation(a, b, c): """ This returns the value of: a * b + c """ result = x * b + c return result # we can now use this function print my_complex_function(8, 1, 12) Defining the function: def function_name(arg1, arg2, ...): """ Documentation (comment) """ do stuff here return some_value Running the function: answer = function_name(value1, value2, ...):
  • 15. exercises! - Write function that takes three inputs (numbers x, y and z), and produces the result of : a + b - c. Use return to be able to store and use the value later. ---- calc.py ---- def my_calculation(????): ???? ???? ???? x = my_calculation(12, 13, 14) print "The complex calculation with 12, 13 and 14 resulted in", x version 2: as above, but if no numbers for b or c are specified, use 5 and 10 as default values.