← Python from Scratch
Lesson 47 of 78 · 10 XP
Scope and recursion
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Variables created inside a function live only there — they are local variables:
def f():
x = 10 # local
f()
print(x) # NameError: x doesn't exist outside
A function can read variables from outside, but if you assign to them inside, Python creates a new local variable. A good rule: pass data in through parameters and get the result back with return.
Recursion is when a function calls itself. It needs two parts:
- a base case — when the answer is known straight away and there's no need to call itself;
- a step — reduce the task to a smaller task of the same kind.
def countdown(n):
if n == 0: # base case
print("Liftoff!")
return
print(n)
countdown(n - 1) # step: the same task, but smaller
Without a base case the function will call itself forever, until Python stops it with a RecursionError.
Task. Write a recursive function factorial(n): factorial(5) = 5 · 4 · 3 · 2 · 1 = 120, and factorial(0) = 1.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.