0% found this document useful (0 votes)
11 views

3.functions

The document provides an introduction to Python functions, covering topics such as importing modules, defining and invoking functions, parameter passing, return values, and scope. It explains the syntax for defining functions, the difference between local and global variables, and how to pass parameters by value and by reference. Additionally, it includes examples of built-in functions from the math and random modules, as well as custom function definitions and their usage.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

3.functions

The document provides an introduction to Python functions, covering topics such as importing modules, defining and invoking functions, parameter passing, return values, and scope. It explains the syntax for defining functions, the difference between local and global variables, and how to pass parameters by value and by reference. Additionally, it includes examples of built-in functions from the math and random modules, as well as custom function definitions and their usage.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Python: Functions

Computer Science & Engineering Department


The Chinese University of Hong Kong

CSCI2040 INTRODUCTION TO PYTHON 1


Content
• Import module
• Define & Invoking functions
• Parameters passing
• Return value
• List Comprehension
• Scope
• Lambda function

CSCI2040 INTRODUCTION TO PYTHON 2


Importing Modules
• Remember those print(), input() and len() that we used before?
• They belong to built-in functions provided by Python environment
• To support more complicated usages, Python provide different
modules to be incorporated into our own program
• A few common modules:
1. math – mathematics functions
2. sys – system utilities such as file open, read/write etc
3. random – random number generator for simulations
• All we need is to use import statement to use them

CSCI2040 INTRODUCTION TO PYTHON 3


import Statement (Example #1)
1 import math
2
3 while (1):
4 str1 = input("x? ")
5 x = float(str1)
6 if (x <= 0):
7 break;
8 print("square root = ", math.sqrt(x))
9 print("Bye!");
10
x? 15
11 square root = 3.872983346207417
12 x? 16
square root = 4.0
x? -3
Bye!

CSCI2040 INTRODUCTION TO PYTHON 4


Some of functions in math module
Functions Description Examples

ceil( x ) rounds x to the smallest integer ceil(9.2) is 10.0


not less than x ceil(-9.8) is -9.0
⌈x⌉
floor ( x ) rounds x to the largest integer floor(9.2) is 9.0
not greater than x floor(-9.8) is -10.0
⌊x⌋
exp( x ) exponential function exp(1.0) is 2.71828
ex
fabs( x ) absolute value of x fabs(5.1) is 5.1
|x| fabs(0.0) is 0.0
fabs(-8.76) is 8.76
pow( x, y ) x raised to power y pow(2, 7) is 128.0
xy pow(9, .5) is 3.0
sqrt( x ) square root of x sqrt(900.0) is 30.0
√x
CSCI2040 INTRODUCTION TO PYTHON sqrt(9.0) is 3.0 5
Some of functions in math module
Functions Description Examples
log ( x ) natural logarithm of x (base e) log(2.718282) ≈ 1.0
loge x or ln x log(exp(3.0)) is 3.0
ln e = 1
ln ex = x * ln e = x
log10 ( x ) logarithm of x (base 10) log(10.0) is 1.0
log10 x log(100.0) is 2.0

sin( x ) trigonometric sine, cosine and tangent of x sin(0.0) is 0.0


cos( x ) (x in radians) cos(0.0) is 1.0
tan( x ) sin x tan(0.0) is 0.0
cos x
tan x Let pi = 3.141592654
90° = π/ 2 sin(pi / 2) ≈ 1.0
180° = π cos(pi / 2) ≈ 0.0
270° = 3 * π / 4 tan(pi / 2) ≈ a large #

CSCI2040 INTRODUCTION TO PYTHON 6


import Statement (Example #2)
• random module provide a random number generation
• randint() provide a random integer ranged between input parameters

1 import random
2 for i in range(5):
3 print(random.randint(1, 6))
4
5 2
6 4
2
1
6

CSCI2040 INTRODUCTION TO PYTHON 7


import Statement (Example #3)
• sys.exit() provide an early ending program option i.e. terminate

1 import sys
2
3 while True:
4 print('Type exit to exit.')
5 response = input()
6 if response == 'exit': Type exit to exit.
7 sys.exit() hello
You typed hello.
8 print('You typed ' + response + '.')
Type exit to exit.
exit
>>>

CSCI2040 INTRODUCTION TO PYTHON 8


From import statement
1 from random import *
2 for i in range(5):
• When we used those functions, 3 print(randint(1, 6))
we always need to provide the 4
prefix of the module name eg. from random import randint, random
math.sqrt()
import tensorflow

• Alternative way is to use from

• Not recommended in big


project using *

CSCI2040 INTRODUCTION TO PYTHON 9


Functions
• What we have used in previous slides are "functions"
• Besides using those provided, we can write our own!
• Writing our function is defining it
• In terms of Python operation, we first define a function to
Python, then used it

• A function is a block of organized, reusable code to perform a


single, related action

CSCI2040 INTRODUCTION TO PYTHON 10


Function Syntax
• functionName : a valid identifier
• Parameters : information passing to function
• '''function docstring''': an optional statement - the documentation
string
• return : exit a function, optionally passing back an expression to caller

1 def functionName( parameters ):


2 '''function_docstring'''
3 statements
4 return [expression]

CSCI2040 INTRODUCTION TO PYTHON 11


Functions
• Functions must be defined before use
• Can be called more than once
1 def printBar():
2 print("*****************")
3
4 printBar()
5 print(" Hello World!")
6 printBar() *****************
7 Hello World!
*****************
8
>>>

CSCI2040 INTRODUCTION TO PYTHON 12


Functions
• Every function can have its own variables
• Variables declared in a function are said to be local to that function
1 def foo(): x in foo() and x in main()
2 x = 0; are two different variables.
3 print("In foo(): x = ", x)
0 5
4
x x
5 x = 5 (foo) (main)
6 print("Before: In main program: x = ", x);
Before: In main program: x = 5
7 foo();
In foo(): x = 0
8 print("After: In main program: x = ", x); After: In main program: x = 5
>>>

CSCI2040 INTRODUCTION TO PYTHON 13


Variables defined in one function are not directly accessible in another
function. Formatted output, y will
1 def bar(): replace placeholder {}
2 y = 0;
3 print("In bar(): y = {}" .format(y))
4
5 Traceback (most recent call last):
File "python/function6.py", line 7, in
6 bar() <module>
7 print("y = {}" .format(y)) # error ! print("y = {}" .format(y)) # error !
8 NameError: name 'y' is not defined
9
10
Variables declared in a function are local variables and are only
accessible in that function.

y, being declared in bar(), is not accessible in main program.


CSCI2040 INTRODUCTION TO PYTHON 14
1 def foo(n): Variables for holding the values
2 print("{}".format(n))
passed into a function are called
3
4
formal parameters.
5 They have local scope in the
6 x = 10 function.
7
8 foo(3)
The values, variables, or
9 foo(x)
expressions specified in the
10 foo(x + 3)
11
function calls are called the
12 actual arguments.
13

2. Parameters
• Allows a function to accept data from its caller
• Allows programmers to reuse code for different values
CSCI2040 INTRODUCTION TO PYTHON 15
1 def foo(n):
2 print("{}".format(n)) n = 13
3
n=3
4
5
n = 10
6 x = 10
7
8 foo(3)
9 foo(x)
10 foo(x + 3)
11 3
10
12
13
13

• Values of the actual arguments are copied to the


corresponding formal parameters.

CSCI2040 INTRODUCTION TO PYTHON 16


Passing Parameter
Copy
x (main) 10 10 n (bar)

x = 10 def bar(n):
bar(x) print("n is {}" .format(n))
print("x is {}" .format(x)) n = n + 1

Output
n is 10
x is 10

For numeric values, only value is passed.


During the function call, only the value of x is
copied to n. Changing n does not affect x.
CSCI2040 INTRODUCTION TO PYTHON 17
Passing Parameter by Reference

x (main) [1,2,3,4] n (bar)

x = [1, 2, 3, 4] def bar(n):


bar(x) print(n)
print(x) n.append( [5, 6, 7])

Output
[1, 2, 3, 4]
[1, 2, 3, 4, [5, 6, 7]]

n keep the reference (location) of x (a list)


During the function call, any changes affecting n
therefore also take effect on x.
CSCI2040 INTRODUCTION TO PYTHON 18
Pass By Reference
• You can make the following assumption for parameter passing in
Python

1. For simple data such as integer and floating point numbers, pass by
value

2. For all other data types such as list, …, pass by reference

CSCI2040 INTRODUCTION TO PYTHON 19


Defining Functions with Parameters
def function_name( parameter_list ):
doc string
statements

⚫ parameter_list
 Zero or more parameters separated by commas in the form
param1, param2, …, paramN

CSCI2040 INTRODUCTION TO PYTHON 20


1 def printBar(n, ch):
2 "A function that prints ch n times"
3 while (n > 0):
4 print(ch, end="")
5 n = n - 1 Documentation string
6 print("")
7
8 printBar(17, '#')
9 print(" Hello World!")
10 printBar(17, '*')
11
12 #################
13 Hellow World!
14 *****************
15

Example:
An improved version of printBar()
CSCI2040 INTRODUCTION TO PYTHON 21
1 def foo(x, y):
2 print("{} {}" .format(x, y))
3
4 x = 3
5 y = 2
6
7 foo(x, y)
8
9 foo(y, x)
10

Example: Defining and calling a function with multiple parameters

• What is the output produced in the above example?

• Arguments and parameters are matched by positions


(not by names !).
CSCI2040 INTRODUCTION TO PYTHON 22
1 def foo(x, y):
2 print("{} {}" .format(x, y))
3
4 foo(x=3, y=2)
5
6 foo(y=2, x=3)
7
8 foo(3, y=2) 3 2
9 3 2
10 3 2

Keyword arguments

• Arguments in function call can also be in the form of


keyword (match by names)
• Must use keyword argument for all others once used for
the first of them
CSCI2040 INTRODUCTION TO PYTHON 23
1 def foo(x, y=2):
2 print("{} {}" .format(x, y))
3
4 foo(x=3)
5
6 foo(3)
7
3 2
8 foo(x=2, y=3)
3 2
9 2 3
10 foo(2, 3) 2 3

Default arguments

• an argument that assumes a default value if a value is not


provided in the function call for that argument
• Default argument must appear later than those without
default value i.e. (x=3, y) is not allowed
CSCI2040 INTRODUCTION TO PYTHON 24
3. Returning a Value From a Function
1 def cube(x) : A function can return a value to its
2 return x * x * x caller.
3
4 We need to explicitly specify what
5 value (of the proper type) to be
6 returned using the keyword return .
7
8
9 print( "Cube of 3 is {}" .format(cube(3)) )
10 print( "Cube of 8 is {}" .format(cube(8)) )

Cube of 3 is 27
Cube of 8 is 512

CSCI2040 INTRODUCTION TO PYTHON 25


Defining Functions That Returns a Value
def function_name( parameter_list ):

return expression

⚫ return expression
 return is a keyword, it returns the value of expression to
the caller.
 expression is evaluated first before return is executed.

CSCI2040 INTRODUCTION TO PYTHON 26


Evaluating functions that return a value

def cube(x) :
return x * x * x

cube(3) is called first


print( "Cube of 3 is {}" .format(cube(3)) )

When cube(3) finishes, the value it returns becomes the


value of the expression represented by "cube(3)", which is
27.
print( "Cube of 3 is 27" )
CSCI2040 INTRODUCTION TO PYTHON 27
Evaluating functions that return a value
In general, functions are called first if they are part of an
expression.
x = cube(1) + cube(2) * cube(3);

x = 1 + cube(2) * cube(3);

x = 1 + 8 * cube(3);

x = 1 + 8 * 27;

x = 1 + 216;

x = 217;

CSCI2040 INTRODUCTION TO PYTHON 28


Interrupting Control Flow with return

A return statement can also force execution to leave a function and


return to its caller immediately.

def smaller(x, y): When "return y" is executed,


if (x > y): execution immediately stops in
return y smaller() and resumes at its
return x
caller.
So in this example, if (x > y) is
true, "return x" will not be
executed.

CSCI2040 INTRODUCTION TO PYTHON 29


Example (with multiple return's)
def daysPerMonth(m, y):
" Returns number of days in a particular month "
if (m == 1 or m == 3 or m == 5 or
m == 7 or m == 8 or m == 10 or m == 12):
return 31

if (m == 4 or m == 6 or m == 9 or m == 11):
return 30;

# if y is a leap year
if (y % 4 == 0 and y % 400 == 0):
return 29
Only one of the "return"
return 28 statements will be executed.
CSCI2040 INTRODUCTION TO PYTHON 30
Example (with only one return)
def daysPerMonth(m, y):
" Returns number of days in a particular month "
if (m == 1 or m == 3 or m == 5 or
m == 7 or m == 8 or m == 10 or m == 12):
days = 31

elif (m == 4 or m == 6 or m == 9 or m == 11):
days = 30;
else:
# if y is a leap year
if (y % 4 == 0 and y % 400 == 0):
days = 29
A function is easier to debug if there
else:
is only one return statement
days = 28
return days
because we know exactly where an
execution leaves the function.
CSCI2040 INTRODUCTION TO PYTHON 31
The return keyword
• If there is no data to be returned, write
return

def askSomething( code ):


if (code != 7):
print("Who are you?")
return # Leave the function immediately
print("How are you today, James?");
return; # This return statement is optional

If nothing to return, placing a return as the last


statement is optional (it is implied).
CSCI2040 INTRODUCTION TO PYTHON 32
None Value
• In Python, there is a value called None, which means absence of value
• In other language , it is called Nil, null , etc.
• For function return nothing, None is being returned
def answerNothing( ):
print("do something")
return

>>> code = answerNothing()


do something
>>> code == None
True
None is being returned

CSCI2040 INTRODUCTION TO PYTHON 33


1 def outerFun(a, b):
2 def innerFun(c, d):
3 return c + d
4 return innerFun(a, b)
5
6 res = outerFun(5, 10)
7 print(res)
8 15
9
10

Nested Function

• Allows function defined within a function


• innerFun only available within outerFun

CSCI2040 INTRODUCTION TO PYTHON 34


Return List and Tuple
• Used as body of a function
def ListofSquares( a ):
b = []
for x in a: b.append(x*x)
return b
>>> ListofSquares([1,2,3])
[1, 4, 9]

• Return multiple values as a tuple, the braces are optional


def TupleofGP( a ):
return (a, a*a, a*a*a)
>>> TupleofGP(3)
(3, 9, 27)
CSCI2040 INTRODUCTION TO PYTHON 35
List Comprehensions
• Used as body of a function

def ListofSquares( a ):
return [x*x for x in a]
>>> ListofSquares([1,2,3])
[1, 4, 9]

• Operations on dictionaries (to be discussed) performed by selecting


values from range of keys, then returning items with selected keys

d = {1:'fred', 7:'sam', 8:'alice', 22:'helen'}


>>>[d[i] for i in d.keys() if i%2==0]
['alice', 'helen']
CSCI2040 INTRODUCTION TO PYTHON
Name Scope
• Names defined outside functions have global scope
• Any local names will shadow the global (same name)
• All values & names destroyed after return

>>> x=4 >>> x=4


>>> def scopetest(a): >>> def scopeTest(a):
... return x + a ... x=7
... ... return x + a
>>> print (scopetest(3)) ...
7 >>> print (scopeTest(3))
>>> 10

CSCI2040 INTRODUCTION TO PYTHON 36


Recursive Function
• Python also accepts function recursion, which means a defined function
can call itself.

def f( n ):
if( n==1):
result = 1
else:
result = n * f(n-1)
return result
>>> print (f(3))
6

CSCI2040 INTRODUCTION TO PYTHON 37


Using globals
• To have assignment access on global variables, use global statement
>>> def scopeTest (a):
... global b
... b = 4
... print ('inside func, b is ', b)
...
>>> a = 1
>>> b = 2
>>> scopeTest(a)
inside func, b is 4
>>> print ('after func, b is ', b)
after func, b is 4
CSCI2040 INTRODUCTION TO PYTHON 38
Raise exception
• When a program is running at a point that the current scope/function cannot
solve the problem, we can raise an exception
• Raise exception will cause program execution halted, thus programmer can
check for the error using information provided

def compoundYear( balance, rate, numYears):


if rate < 0:
raise RuntimeError("-ve interest rate")
if numYears < 0:
raise RuntimeError("-ve number of years")
for year in range(9, numYears):
balance = compound(balance, rate)
return balance
print ('after 10 yrs,', compoundYear(1000, -5, 3))

Traceback (most recent call last):


File "COURSE/python/function20.py", line 10, in <module>
print ('after 10 yrs,', compoundYear(1000, -5, 3))
File "COURSE/python/function20.py", line 3, in compoundYear
raise RuntimeError("-ve interest rate")
RuntimeError: -ve interest rate
CSCI2040 INTRODUCTION TO PYTHON 39
Lambda function
• Passing function to another function, say filter, we may do it this way
def even(x):
return x % 2 == 0
a = [1,2,3,4,5]
print (list(filter(even, a)))
>>> [2, 4]

• We may just want to define a very simple function


• using def function becomes quite cumbersome
• lambda is used to pass simple function
print (list(filter( lambda x : x % 2 == 0, a)))
[2, 4]

CSCI2040 INTRODUCTION TO PYTHON 40

You might also like