Functions are essential building blocks in programming that allow you to reuse code and make your programs more modular. In this lesson, we will learn how to define functions in Python, understand the syntax, and explore some practical examples.
A function is a piece of reusable code that performs a specific task. To define a function in Python, you use the def
keyword followed by the function name, parentheses ()
, and colon :
:
def greet_user(name):
print("Hello, " + name)
Here, greet_user
is a function that takes one argument called name
. When we call this function with a specific value for the argument (e.g., 'Alice'
), it will print out a personalized greeting:
greet_user('Alice') # Outputs: Hello, Alice
A function can also have a return statement to provide a value when the function is called. The returned value can be used in other parts of your code. For example:
def add_numbers(a, b):
total = a + b
return total
result = add_numbers(3, 5) # Outputs: 8 (because the function returns the sum of 3 and 5)
Let's create a simple calculator using functions to perform basic arithmetic operations.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
print("Error: Division by zero is not allowed.")
return None
result = add(5, 3) # Outputs: 8
result = subtract(7, 2) # Outputs: 5
result = multiply(4, 6) # Outputs: 24
result = divide(10, 2) # Outputs: 5
What causes it: Using an undefined function name.
undefined_function() # Triggers a NameError
Error message:
Traceback (most recent call last):
File "example.py", line 4, in <module>
undefined_function()
NameError: name 'undefined_function' is not defined
Solution: Make sure the function is properly defined before calling it.
Why it happens: You didn't define the function or misspelled its name.
How to prevent it: Double-check your code and make sure you have defined all functions before using them.
What causes it: Incorrect syntax when defining a function, such as missing a colon :
at the end of the function header.
def addnumbers(a, b):
return a + b
Error message:
File "example.py", line 1
def addnumbers(a, b):
^
SyntaxError: invalid syntax
Solution: Add the missing colon :
at the end of the function header.
Why it happens: You forgot to include the trailing colon when defining a function.
How to prevent it: Always remember to add a colon at the end of the function header.
What causes it: Passing an incorrect data type as an argument to a function that expects another data type.
def multiply(a, b):
return a * b
result = multiply('3', '5') # Triggers a TypeError
Error message:
Traceback (most recent call last):
File "example.py", line 4, in <module>
result = multiply('3', '5')
TypeError: unsupported operand type(s) for *: str and str
Solution: Pass appropriate data types as function arguments.
Why it happens: The provided arguments do not match the expected data types of the function's parameters.
How to prevent it: Ensure that the correct data types are passed to your functions based on their requirements.
def
keyword followed by the function name, parentheses ()
, and colon :
.Now that you understand how to define functions in Python, it's time to start building more complex programs by combining multiple functions! Keep practicing and learning, and happy coding!