🔍 Quick Lesson
In Python, functions are blocks of reusable code that perform a specific task. They help make your programs modular, organized, and easier to understand and maintain.
1. Defining a Function
Use the def
keyword to define a function. Here's the basic syntax:
def greet():
print("Hello, wizard!")
Calling greet()
will output: Hello, wizard!
2. Function Parameters
Functions can accept inputs called parameters. These allow you to pass data into your function:
def greet(name):
print(f"Hello, {name}!")
Calling greet("Merlin")
will output: Hello, Merlin!
3. Returning Values
Functions can also return values using the return
keyword:
def add(a, b):
return a + b
add(3, 5)
will return 8
. You can store the result in a variable for later use.
4. Default Parameters
Parameters can have default values, which are used if no value is provided during the function call:
def greet(name="wizard"):
print(f"Hello, {name}!")
greet()
will print Hello, wizard!
. greet("Gandalf")
will print Hello, Gandalf!
.
5. Scope of Variables
Variables defined inside a function are local to that function. They cannot be accessed outside of it:
def cast_spell():
spell = "Fireball"
print(spell)
cast_spell()
print(spell) # This will cause an error!
The last line will raise a NameError
because spell
is not defined outside the function.
6. The pass
Statement
If you're still planning your function and want it to do nothing (for now), use the pass
statement:
def future_function():
pass
This keeps your code valid without executing anything inside the function body.