Our aim in this tutorial is to help you understand how to create your own functions in Python and how to call them in your code.
By following this tutorial, you will learn:
- The fundamental concepts of functions
- How to create and define your own functions
- How to call and use these functions in your code
Prerequisites: Basic understanding of Python and its syntax.
Functions in Python are blocks of reusable code that perform a specific task. You can define your own functions, which helps you organize and reuse code. They can also make your code more readable and easier to maintain.
To create a function in Python, you use the def
keyword followed by the function name and parentheses ()
. Any input parameters or arguments should be placed within these parentheses. Finally, the function is started with a colon :
and the block of code is indented.
def my_function():
print("Hello from a function")
In the example above, we defined a function called my_function
that prints a string when called.
To call a function, you simply need to write the function's name followed by ()
.
my_function()
The output will be: Hello from a function
def greet():
"""
This function prints a greeting message
"""
print("Hello, World!")
# To call the function:
greet()
Output: Hello, World!
def greet(name):
"""
This function takes a name as a parameter
and prints a personalized greeting message
"""
print(f"Hello, {name}!")
# To call the function:
greet("Alice")
Output: Hello, Alice!
def add_numbers(num1, num2):
"""
This function takes two numbers as parameters,
adds them, and returns the result
"""
return num1 + num2
# To call the function:
result = add_numbers(3, 5)
print(result)
Output: 8
In this tutorial, we've covered the basics of creating and calling functions in Python. You've learned how to define your own functions, how to pass parameters to them, and how to make them return a value.
The next step would be to learn about different types of functions like anonymous (lambda) functions, recursive functions, and generator functions.
For more information, you can check out the official Python documentation on functions.
# Solution to Exercise 1
def to_uppercase(s):
return s.upper()
# Solution to Exercise 2
def multiply(a, b):
return a * b
# Solution to Exercise 3
def sum_list(numbers):
return sum(numbers)
Keep practicing and creating more complex functions to solidify your understanding. Happy coding!