You are on page 1of 39

Seven Days Faculty Development and Training Programme on

GE8151 - Problem Solving and


Python Programming

FUNCTIONS
ADRI JOVIN J J
ASSISTANT PROFESSOR (SR. GR.)
DEPARTMENT OF INFORMATION TECHNOLOGY
SRI RAMAKRISHNA INSTITUTE OF TECHNOLOGY
WHO’S A GREAT TEACHER?

The mediocre teacher tells.


The good teacher explains.
The superior teacher demonstrates.
The great teacher inspires.

― William Arthur Ward


31/05/2018 FUNCTIONS-PYTHON | 2
OBJECTIVE

Creating a simple function with a parameter


Exploring functions with return values
Creating functions with multiple parameters
Control Flow/Sequence in Python

31/05/2018 FUNCTIONS-PYTHON | 3
EXPECTED LEARNING OUTCOMES

Create functions with a parameter


Create functions with a return value
Create functions with multiple parameters
Understand the control flow in Python
Cognitive level expected: “apply”

31/05/2018 FUNCTIONS-PYTHON | 4
RECOMMENDED TEACHING-AID

 Jupyter Notebook - Open Source (requires Anaconda


environment)

 http://notebooks.azure.com - Free cloud platform (requires


Microsoft account, probably a hotmail.com/live.com
account)

 Spyder – Open Source (requires Anaconda environment)

31/05/2018 FUNCTIONS-PYTHON | 5
LEARNING RESOURCES

 Official Python 3 Documentation - https://docs.python.org/3/library/index.html


 Dive Into Python - http://www.diveintopython3.net/
 Think Python - http://greenteapress.com/wp/think-python-2e/
 The Official Python Tutorial - https://docs.python.org/3/tutorial/
 Learn Python the Hard Way - http://learnpythonthehardway.org/book/
 PEP 8 - https://www.python.org/dev/peps/pep-0008/
 Python Tutor - http://www.pythontutor.com/
 Reserved Keywords in Python -
https://docs.python.org/3.0/reference/lexical_analysis.html#id8 [Don’t use]
31/05/2018 FUNCTIONS-PYTHON | 6
JUPYTER NOTEBOOK

http://notebooks.azure.com

Log-in with a Microsoft ID like


MSN/Hotmail/Live account

Easy to access from any where

24x7 availability

Easy transfer of notebooks


31/05/2018 FUNCTIONS-PYTHON | 7
JUPYTER NOTEBOOK

 Create Libraries

 Clone Libraries

 Libraries may contain


number of Notebooks

31/05/2018 FUNCTIONS-PYTHON | 8
JUPYTER NOTEBOOK

 Create Libraries

 Clone Libraries

 Libraries may contain


number of Notebooks

 Jupyter Notebook format


(.ipynb files)

31/05/2018 FUNCTIONS-PYTHON | 9
JUPYTER NOTEBOOK

 Create Libraries

 Clone Libraries

 Libraries may contain


number of Notebooks

 Jupyter Notebook format


(.ipynb files)

31/05/2018 FUNCTIONS-PYTHON | 10
JUPYTER NOTEBOOK

 Creating a new Notebook

 Click + symbol > Name the


Notebook
Here, it is
“MY_FIRST_NOTEBOOK”

 Click “New”
Note: Item Type must be
selected or the file will be
blank

31/05/2018 FUNCTIONS-PYTHON | 11
JUPYTER NOTEBOOK

 Code Cell
 Markdown Cell
 Raw NBConvert Cell
 Header Cell

31/05/2018 FUNCTIONS-PYTHON | 12
RUNNING A CELL

Methods for running the code in a cell


 Click in the cell below and press "Ctrl+Enter" to run the code
or
 Click in the cell below and press "Shift+Enter" to run the code and move to the next cell
 Menu: Cell...
 > Run Cells runs the highlighted cell(s)
 > Run All Above runs the highlighted cell and above
 > Run All Below runs the highlighted cell and below

31/05/2018 FUNCTIONS-PYTHON | 13
WORKING IN NOTEBOOK

EDIT MODE
 text cells in editing mode show markdown code
 Markdown cells keep editing mode appearance until the cell is run
 code (python 3) cells in editing look the same after editing, but may show different run output
 clicking another cell moves the green highlight that indicates which cell has active editing focus

CELLS NEED TO BE SAVED


 the notebook will frequently auto save
 best practice is to manually save after editing a cell using "Ctrl + S" or alternatively, Menu: File > Save
and Checkpoint
31/05/2018 FUNCTIONS-PYTHON | 14
ALTERING NOTEBOOK

ADD A CELL
 Highlight any cell and then... add a new cell using Menu: Insert > Insert Cell Below or Insert Cell Above
 Add with Keyboard Shortcut: "ESC + A" to insert above or "ESC + B" to insert below
CHOOSE CELL TYPE
 Format cells as Markdown or Code via the toolbar dropdown or Menu: Cell > Cell Type > Code or Markdown
 Cells default to Code when created but can be reformatted from code to Markdown and vice versa
CHANGE NOTEBOOK PAGE LANGUAGE
 The course uses Python 3 but Jupyter Notebooks can be in Python 2 or 3 (and a language called R)
 To change a notebook to Python 3 go to "Menu: Kernel > Change Kernel> Python 3"

31/05/2018 FUNCTIONS-PYTHON | 15
FUNCTIONS WITH ARGUMENTS

 Functions are used for code tasks that are intended to be reused
 Make code easier to develop and maintain

 Python allows
−User Defined Functions
−Built-in Functions (e.g.: print())

31/05/2018 FUNCTIONS-PYTHON | 16
FUNCTIONS WITH ARGUMENTS

 print()can be called using arguments (or without) and sends text to


standard output, such as the console.

 print()uses parameters to define the variable arguments that can be


passed to the Function.

 print()defines multiple string/numbers parameters which means we


can send a long list of arguments to print(), separated by commas.

31/05/2018 FUNCTIONS-PYTHON | 17
BASICS OF A USER DEFINED FUNCTION

 define a function with def


 use indentation (4 spaces)
 define parameters
def some_function() :
 optional parameters
 return values (or none)
 function scope (basics defaults)

31/05/2018 FUNCTIONS-PYTHON | 18
CERTAIN RULES

 use a function name that starts with a letter or underscore (usually a


lower-case letter)
 function names can contain letters, numbers or underscores
 parenthesis () follow the function name
 a colon : follows the parenthesis
 the code for the function is indented under the function definition
(use 4 spaces for this course)

31/05/2018 FUNCTIONS-PYTHON | 19
SYNTAX

def some_function():
#code the function tasks indented here

The end of the function is denoted by returning to no indentation

31/05/2018 FUNCTIONS-PYTHON | 20
EXAMPLE

def say_hi():
print("Hello World!")
print("say hi!")
say_hi()

Output:
Hello World!
say hi!

31/05/2018 FUNCTIONS-PYTHON | 21
CALLING FUNCTIONS

 Simple function can be called using the function name followed by


parentheses
print()
Example:
def say_hi():
print("Hello World!")
print("say hi!")
say_hi()

31/05/2018 FUNCTIONS-PYTHON | 22
TEST THIS…

Test:
def say_hi():
print("Hello World!")
print("say hi!")
def three_three():
print(33)
# calling the functions
say_hi()
print()
three_three()

31/05/2018 FUNCTIONS-PYTHON | 23
TEST RESULT…

Output:
Hello World!
say hi!

33

31/05/2018 FUNCTIONS-PYTHON | 24
TASK

Define and call a simple function shout()


shout() prints the phrase with "!" concatenated to the end
 takes no arguments
 indented function code does the following
 define a variable for called phrase and initialize with a short phrase
 prints phrase as all upper-case letters followed by "!"
 call shout at the bottom of the cell after the function def
(Tip: no indentation should be used)

31/05/2018 FUNCTIONS-PYTHON | 25
FUNCTION WITH PARAMETERS

 print()and type()are examples of built-in functions that have


parameters defined

 type() has a parameter for a Python Object and sends back the
type of the object

31/05/2018 FUNCTIONS-PYTHON | 26
ARGUMENT VS PARAMETER

 an argument is a value given for a parameter when calling a function


 type is called providing an Argument - in this case the string "Hello"
type(“Hello”)
 Parameters are defined inside of the parenthesis as part of a
function def statement
 Parameters are typically copies of objects that are available for use
in function code
def say_this(phrase):
print(phrase)
31/05/2018 FUNCTIONS-PYTHON | 27
Hi Hello

DEFAULT ARGUMENT

 Default Arguments are used if no argument is supplied


 Default arguments are assigned when creating the parameter list

def say_this(phrase = "Hi"): Hi


print(phrase) Hello
say_this()
say_this("Hello")

31/05/2018 FUNCTIONS-PYTHON | 28
Hi Hello

TASK

Define shout_this()and call with variable argument


 define variable words_to_shout as a string gathered from user
input()
 Call shout_this() with words_to_shout as argument
 get user input()for the string words_to_shout

31/05/2018 FUNCTIONS-PYTHON | 29
Hi Hello

FUNCTION WITH RETURN VALUE

 type()returns an object type


 type()can be called with a float the return value can be
stored in a variable
object_type = type(2.33)

31/05/2018 FUNCTIONS-PYTHON | 30
Hi Hello

FUNCTION WITH RETURN VALUE

 return keyword in a function returns a value after exiting


the function

def msg_double(phrase):
double = phrase + " " + phrase
return double

31/05/2018 FUNCTIONS-PYTHON | 31
Hi Hello

TASK

 Define function print_doctor() that takes a parameter


name
 get user input for variable full_name
 call the function using full_name as argument
 print the return value

31/05/2018 FUNCTIONS-PYTHON | 32
Hi Hello

FUNCTION WITH MULTIPLE PARAMETERS

 Functions can have multiple parameters separated by


commas
def make_schedule(period1, period2):
schedule = ("[1st] " + period1.title() + ", [2nd] " + period2.title())
return schedule
student_schedule = make_schedule("mathematics", "history")
print("SCHEDULE:", student_schedule)

31/05/2018 FUNCTIONS-PYTHON | 33
Hi Hello

TASK

Define make_schedule()adding a 3rd period to


 Start with the above example code
 add a parameter period_3
 update function code to add period_3 to the schedule
 call student_schedule()with an additional argument such as
'science'
 print the schedule

31/05/2018 FUNCTIONS-PYTHON | 34
Hi Hello

SEQUENCE/FLOW OF EXECUTION

 In programming, sequence refers to the order that code is


processed
 Objects in Python, such as variables and functions, are not
available until they have been processed
 Processing sequence flows from the top of a page of code to
the bottom
 This often means that function definitions are placed at the
beginning of a page of code

31/05/2018 FUNCTIONS-PYTHON | 35
In the statement have_hat = hat_available('green') the function hat_available() needs to be called after the function has been defined
Hi Hello

SEQUENCE/FLOW OF EXECUTION

have_hat = hat_available('green') ---------------------------------------------------------------------------

print('hat available is', have_hat) NameError Traceback (most recent call last)

def hat_available(color): <ipython-input-1-95ed6a786fca> in <module>()

hat_colors = 'black, red, blue, ----> 1 have_hat = hat_available('green')


green, white, grey, brown, pink' 2 print('hat available is', have_hat)
return(color.lower() in 3 def hat_available(color):
hat_colors)
NameError: name 'hat_available' is not defined

In the statement have_hat = hat_available('green')the function


hat_available()needs to be called after the function has been defined

31/05/2018 FUNCTIONS-PYTHON | 36
Hi Hello

TASK

Change the Sequence to fix the NameError


have_hat = hat_available('green')

print('hat available is', have_hat)

def hat_available(color):
hat_colors = 'black, red, blue, green, white, grey, brown, pink'
return(color.lower() in hat_colors)

31/05/2018 FUNCTIONS-PYTHON | 37
Hi Hello

TASK

Create and test market()


 market()takes 2 string arguments: commodity & price
 market returns a string in sentence form
 gather input for commodity_entry and price_entry to use in
calling market()
 print the return value of market()

Example of output: Commodity Type: Basket costs Rs. 100/-

31/05/2018 FUNCTIONS-PYTHON | 38
Hi Hello

TRAINING WORKBOOK

https://notebooks.azure.com/adrijovin/libraries/functions-
ge8151

Disclaimer:
All products and company names are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Jupyter is a registered U.S. Patent & Trademark Office of Project Jupyter, USA

Python is a registered trademark of the Python Software Foundation, USA

Microsoft Azure is a registered trademark of Microsoft Corporation, USA

31/05/2018 FUNCTIONS-PYTHON | 39

You might also like