Python Functions
Functions allow you to group code into reusable blocks. Functions in Python are defined using the def keyword.
Defining a Function
Here's how to define and call a function:
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
This function takes one argument, name, and prints a greeting.
Returning Values
Functions can return values using the return keyword:
def add(x, y):
return x + y
result = add(5, 3)
print(result)
This function returns the sum of x and y.
Activity
Try It Yourself!
Create a function that takes a number as an argument and returns its square.
Quick Quiz
Quick Quiz
- What keyword is used to define a function in Python?
- What does the
returnkeyword do in a function?
Answers: Use def to define a function. The return keyword is used to return a value from a function.