Today you will learn to:
return) areBy the end, you will be able to write programs that are organized, shorter, and reusable.
A function is a block of code that performs a specific task.
Benefits:
Real-life example:
A coffee machine is like a function.
You press a button → coffee is made.
In programming:
You call a function → it executes code.
A function is created with def.
def hello():
print("Hello!")
Explanation:
def means definehello is the name of the function() are always includedTo execute a function, you must call it.
def hello():
print("Hello!")
hello()
Output:
Hello!
Parameters are information that a function receives.
def greeting(name):
print("Hello", name)
greeting("Anna")
greeting("Max")
Output:
Hello Anna
Hello Max
Explanation:
name is the parameterSometimes a function should return a result.
For that, use return.
def greeting(name):
return "Hello " + name
print(greeting("Anna"))
Output:
Hello Anna
Explanation:
return returns a resultFunctions are very useful for math or calculations.
def add(a, b):
return a + b
print(add(3, 4))
Output:
7
Explanation:
a and b are parametersreturn gives back the sum
def greeting(name):
return "Hello " + name
print(greeting("Anna"))
What happens here:
Example 1:
def square(number):
return number * number
print(square(5))
Output:
25
Example 2:
def welcome(name, age):
print("Hello", name)
print("You are", age, "years old")
welcome("Max", 20)
Write a function that adds two numbers and returns the result.
Steps:
Example structure:
def add_numbers(a, b):
return a + b
print(add_numbers(5, 3))
Output:
8