Professional Documents
Culture Documents
CENG240-2021 - Week8 - Functions (Contd)
CENG240-2021 - Week8 - Functions (Contd)
Functions [continued]
Disclaimer: Figures without reference are from either from “Introduction to programming concepts
with case studies in Python” or “Programming with Python for Engineers”, which are both co-authored
by me.
0!
Functions in Python
4
N G2
CE
on
METU Computer Engineering
sly
u
vio
e
Pr
¢ Syntax is important!
¢ Indentation is extremely important!
sly
u
vio
e
Pr
sly
u
io
ev
Pr ¢ To access variables in the global workspace,
you should use “global <varname>”
ls y
u
vio
e
Pr ¢ Since you can nest
functions in Python,
understanding scope
is important
¢ LEGB rule:
Local < Enclosing <
Global < Built-in
2020 S. Kalkan & G. Ucoluk - CEng 111 5
Parameter 40! passing in functions in
2
on
CENG Python
METU Computer Engineering
sly
u
vio
e
Pr
on
CENG Python
METU Computer Engineering
sly
u
vio
e
Pr
on
CENG Python
METU Computer Engineering
sly
u
vio
e
Pr
ls y
u
vio
e
Pr
¢ Lab 5
¢ Midterm: 1 June, Tuesday, 17:40
¢ map(function, Iterator)
¢ filter(predicate, Iterator)
¢ What is recursion?
¢ Definition of factorial:
• More formally:
Factorial uses
its own definition!
2020 S. Kalkan & G. Ucoluk - CEng 111 15
Recurrence & Recursion
METU Computer Engineering
def factorial(N):
if N == 0: return 1
else: return N * factorial(N-1)
N = 1
M = 2
def f():
global M
N = 3
M = 4
print(N, M)
f()
print(N,M)
¢ Bankruptcy Countdown:
§ https://pp4e-workbook.github.io/chapters/functions/bankruptcy_countdown.html
¢ Perfect Number:
§ https://pp4e-workbook.github.io/chapters/functions/perfect_number.html