A function is a named block of code that you can run whenever you need it. You have used several: print, len, input. Now you will write your own.
def greet(name):
print(f"Hello, {name}!")
greet("Noor")
greet("Luca")
def greet(name):defines the function. The indented block is its body. Nothing runs yet.nameis a parameter: a variable that receives a value each time the function is used.greet("Noor")calls the function."Noor"is the argument that goes intoname.
A function must be defined above the place where you call it.
Returning a value
Most functions calculate something and hand it back with return:
def area(width, height):
return width * height
room = area(4, 5)
print(room) # 20
print(area(2, 3)) # 6
The call is replaced by the value the function returns, so you can store it, print it or use it in a bigger calculation. return also ends the function at once.
Printing and returning are different. print shows a value to a person. return gives a value back to the code that called the function. A function without return gives back the special value None.
Default values
A parameter can have a default, used when the caller leaves it out:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024
Why functions matter
Functions let you write a piece of logic once and use it everywhere. They also give a name to an idea, which makes programs much easier to read.
Your Task
- Write a function
doublethat takes one number and returns that number times 2. - Write a function
is_eventhat takes a number and returnsTruewhen it is even andFalsewhen it is odd. (Remember the remainder operator%.) - Print the result of
double(21).
doublereturns twice its inputis_evenreturnsTruefor even numbers andFalsefor odd ones- Both functions use
return 42is printed by callingdouble(21)