Intermediate âĸ Python
Functions
âī¸ Creating a Function
A function is a reusable block of code. We create a function using the def keyword. The code inside the function runs when we call the function.
def say_hello():
print("Hello!")
say_hello()Hello!
đ Everything in Functions
Create reusable blocks of Python code. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
âī¸ Creating a Function
A function is a reusable block of code. We create a function using the def keyword. The code inside the function runs when we call the function.
def say_hello(): print("Hello!") say_hello()đĨ Function Parameters
Parameters allow us to send information into a function. The function can then use that information when it runs.
def greet(name): print("Hello", name) greet("Alex")đ¤ Returning a Value
A function can send a value back to the part of the program that called it. We use the return keyword to return a value.
def add(a, b): return a + b result = add(5, 3) print(result)đĄ Why Use Functions?
Functions help us organize programs into smaller pieces. They allow us to reuse code instead of writing the same instructions again and again. This can make programs easier to understand and maintain.
def say_hello(): print("Hello!") say_hello() say_hello() say_hello()đī¸ Default Parameters
A parameter can have a default value. If we call the function without giving that information, Python uses the default value instead. We set a default by writing = and a value after the parameter name.
def greet(name="friend"): print("Hello", name) greet("Alex") greet()đ Functions Calling Functions
A function can call another function. This lets us build bigger tools out of smaller ones, a bit like building a model out of blocks. Each function does one small job, and together they solve a bigger problem.
def double(number): return number * 2 def double_and_add_one(number): return double(number) + 1 print(double_and_add_one(5))â Returning True or False
A function can return a boolean value, either True or False. This is handy for asking yes-or-no questions, such as whether a number is even. The answer can then be printed or used in an if statement.
def is_even(number): return number % 2 == 0 print(is_even(4)) print(is_even(7))đ Where Variables Live (Scope)
A variable created inside a function only lives inside that function. This is called a local variable, and the rest of the program cannot see it. A variable created outside all functions can be read from inside a function. Think of a function as a room: things made inside the room stay in the room.
bonus = 10 def add_bonus(score): total = score + bonus return total print(add_bonus(5)) print(bonus)
