Defining and calling a function
def add(a, b):
return a + b
result = add(3, 4)
print(result) # 7def only defines the function. Nothing runs until you call add(3, 4). Then a becomes 3, b becomes 4, and return sends 7 back.
print vs return
print shows a value on screen. return hands the value back so the rest of your program can use it.
Common beginner mistakes
- Forgetting the brackets when calling:
addinstead ofadd(3, 4). - Forgetting
return, so the function gives backNone. - Using a variable made inside the function from outside it (scope).
Practice exercises
Try each one yourself first, then open it in the Visualizer to watch every line run.
Exercise 1
Square a number
Write a function square(n) that returns n * n, then print square(6).
def square(n):
# return the answer
pass
print(square(6))Hint
Replace pass with return n * n.
Show solution and explanation
def square(n):
return n * n
print(square(6)) # 36Calling square(6) jumps into the function with n = 6. return sends 36 back to the line that called it, where print shows it.
Watch the solution step by stepExercise 2
Greeting with a default
Write greet(name, greeting="Hello") and call it with and without the second value.
def greet(name, greeting="Hello"):
pass
greet("Sara")
greet("Omar", "Salam")Hint
Print greeting and name inside the function.
Show solution and explanation
def greet(name, greeting="Hello"):
print(greeting, name)
greet("Sara")
greet("Omar", "Salam")When no greeting is passed, the default "Hello" is used. Each call gets its own fresh variables.
Watch the solution step by stepExercise 3
Is it prime?
Write is_prime(n) that returns True or False, and test it on a few numbers.
def is_prime(n):
# check divisors from 2 to n - 1
pass
print(is_prime(7), is_prime(9))Hint
Return False as soon as a divisor is found; return True after the loop.
Show solution and explanation
def is_prime(n):
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False
return True
print(is_prime(7), is_prime(9)) # True Falsereturn ends the function immediately. For 9 the loop stops at d = 3; for 7 it checks every divisor and reaches return True.
Watch the solution step by step