Functions.pptx
Functions.pptx
Programming
Functions
<<Section Title>>
CSC1
Hussein Suleman
Department of Computer Science
[email protected]
<<Section
Title>>
Hussein Suleman
Department of Computer Science
University of Cape Town
[email protected]
Problem 1 Introduction
▪ Write a program to print out the reverse of a sentence.
▪ For example:
▪ Computer becomes retupmoC
▪ Use first principles - i.e., process the string
character-by-character.
▪ Use functions to make your program readable/modular.
4
Function
▪ A function is a named block of statements that can be
executed/called within a program.
▪ We have already used some functions:
▪ print, eval, round, ...
▪ Python stops what it is doing, runs the function, then continues
from where it stopped.
▪ Functions enable reuse and modularity of code.
▪ Functions help us to write longer/more complex programs.
5
So far:
# reverse an integer without using strings
number = eval (input ("Enter a number: "))
reverse = 0
while number > 0:
digit = number % 10
number = int(number / 10)
reverse = reverse * 10 + digit
print (reverse)
6
Function - example
# somewhere else
# reverse an integer without
def input (someString):
using strings
#function to read from standard
number = eval (input ("Enter
input
a number: "))
def eval (aStringNumber):
reverse = 0
#converts string to number
while number > 0:
def int(aString or aFloat):
digit = number % 10
#returns an integer using floor
number = int(number / 10)
function
reverse = reverse * 10 +
digit
def print(oneOrMoreStrings):
print (reverse)
#outputs the strings to standard
output
7
Function Definition / Use
▪ Functions can be defined and used in any order, as long as
they are used after definition.
▪ To define a function:
def some_function ():
statement1
statement2
...
▪ To use/call/invoke a function:
some_function ()
8
Code refactoring
▪ Functions can refactor code to avoid duplication
9
Parameters
▪ Parameters allow variation in function
behaviour
def welcome(grp):
print ("Welcome")
print ("to") print
("Welcome")
print ("CS1")
print ("Welcome") print ("to")
print ("to") print (grp)
print ("CS2")
print ("Welcome") welcome ("CS1")
print ("to")
welcome ("CS2")
print ("CS3")
welcome ("CS3")
10
Parameters
▪ Every function can have a list of parameters in its definition.
▪ called the formal parameters
▪ Whenever the function is called/invoked a value must be
provided for each of the formal parameters
▪ called the actual parameters or arguments
▪ Within the function body, the parameters can be used like
variables.
11
Formal and Actual Parameters
actual parameters
or “arguments”
12
Pass-By-Value
▪ Only a copy of the value of a parameter is ever sent to a
function.
▪ So if there is an original variable, it cannot be changed by the
function changing the parameter.
13
Pass-By-Value
def some_function
(a):
a=a+1
13
print (a) output
12
b = 12
some_function (b)
print (b)
14
Scope and Local Variables
▪ New variables can be created and used within functions but
they disappear when the function ends.
▪ called local variables
15
Scope and Local Variables
16
Scope and Local Variables
▪ Local variables names (and parameters) that are the same as
global variable names temporarily hide the global variables.
17
Scope and Local Variables
def some_function
(a,c):
a = 3
b = 3
3 3
print (a,b)
a = 1
output 1 2
b = 2
some_function
(1,2)
print (a,b)
18
Global Variables
▪ Global variables can be accessed but not changed.
▪ Use the global statement to allow changes to a global variable.
19
Global Variables
def some_function
(a):
global b
b = 4
a = 3 4
output
b = 2
some_function (b)
print (b)
20
Return Values
▪ Functions can return values just like mathematical functions.
▪ Use the return statement with an expression.
▪ Can be used anywhere in function and will return immediately.
21
Return Values
22
Problem 1
▪ Write a program to print out the reverse of a sentence.
▪ For example:
▪ Computer becomes retupmoC
▪ Use first principles - i.e., process the string
character-by-character.
▪ Use functions to make your program readable/modular.
23
docstring
▪ Functions should be documented by specifying their purpose in
a string immediately after the header.
▪ It is recommended that you use """ (triple quotes - for multi-line
strings) for all docstrings.
▪ Use func.__doc__ to check the docstring.
24
docstring
def cube (x):
"""Return the cube of x."""
return x*x*x
def square (x):
"""Return the square of x.
x can be any numerical value"""
return x*x
25
nested functions
▪ Functions can be composed similarly to mathematical
functions.
def cube (x):
return x*x*x
def square (x):
return x*x
def power (a, b):
return a**b
print (power (cube (2), square (2)))
26
main function
▪ Common practice is to wrap a program into a function called
"main", then invoke this function to execute the program.
# cube program
def cube (x):
return x*x*x
def main ():
print (cube (2))
main()
27
Writing your own modules
▪ Any file with functions can be imported.
▪ Check __name__ variable
▪ if it is "__main__", then this file was executed
▪ otherwise, this file was imported
28
Writing your own modules
# cube module
# test cube module
def cube (x):
return x*x*x
import a
def main ():
print (cube (2))
print (a.cube(3))
if __name__=="__main__":
main()
29
Problem 2
▪ Convert the free wifi program to use functions, with all the best
practices for using functions.
30
Problem 3 Intro 1/2
▪ Write an application to tell what country or body of water the
International Space Station is over right now. Use best
practices for functions.
▪ Extend your application to give the next time the ISS will fly
over South Africa
31
Problem 3 Intro 2/2
▪ http://api.open-notify.org/iss-now.json Will give the current
latitude and longitude of the International Space Station
▪ http://www.geonames.org/export/web-services.html#countrycod
e Can help us find a country name from a latitude and longitude
▪ http://www.geonames.org/export/web-services.html#ocean Can
help us find the ocean name from a latitude and longitude
32
International Space Station
▪ First component launched in 1998
▪ Modular space station
▪ Largest man-made body in orbit
▪ Can often be seen with the naked eye from Earth
▪ Science!
33
Default values for parameters
▪ Functions can have zero or more parameter with default values
in their definition.
▪ All parameters with default values must be at the end of the
parameter list.
▪ e.g., once you have a default value, all subsequent parameters must
have a default value as well.
34
Default values for parameters
▪ Evaluated at the time of function definition, not invocation.
▪ Whenever the function is called/invoked, the arguments with
default values are optional.
▪ Within the function body, parameters still used as variables.
35
Recall: Formal Parameters
actual parameters
36
Default values for formal parameters
def some_function (a, b, c=10):
print (a)
print (b+c) formal parameter
with default value
37
Problem 3
▪ Write an application to tell what country or body of water the
International Space Station is over right now. Use best
practices for functions.
▪ Extend your application to give the next time the ISS will fly
over South Africa
38
Unless otherwise stated, all materials are copyright of the University of Cape Town
© University of Cape Town