Functions are a fundamental concept in Python that allow you to encapsulate reusable blocks of code. In this tutorial, we'll explore how to define and use functions in Python.
A function is a block of code designed to perform a specific task. You can call the function whenever you need it, which makes your code more modular and easier to manage.
Use the def
keyword to define a function. Here's an example:
def greet():
print("Hello, world!")
To call this function, simply use its name followed by parentheses:
greet()
Output:
Hello, world!
Functions can accept parameters to make them more flexible:
def greet(name):
print(f"Hello, {name}!")
Call the function with an argument:
greet("Alice")
Output:
Hello, Alice!
Functions can return values using the return
keyword:
def add(a, b):
return a + b
Store the returned value in a variable:
result = add(5, 3)
print(result)
Output:
8
You can define default parameter values for a function:
def greet(name="stranger"):
print(f"Hello, {name}!")
If you call the function without an argument, it uses the default value:
greet()
Output:
Hello, stranger!
You can specify arguments by name, making your code more readable:
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce(age=25, name="Alice")
Output:
My name is Alice and I am 25 years old.
Practice creating your own functions with different parameters, return values, and default arguments. Functions are a powerful way to organize and reuse your code. Happy coding! Now that you know about function you should check out object orientated programming in python!