Functions allow you to group code into reusable blocks. Functions in Python are defined using the def
keyword.
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.
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
.
Create a function that takes a number as an argument and returns its square.
return
keyword do in a function?Answers: Use def
to define a function. The return
keyword is used to return a value from a function.