Python 101
In Python, a function is a block of code that performs a specific task and can be reused multiple times in a program. Functions are an essential part of Python, and they can help you to organize and structure your code, making it easier to understand and maintain.
To create a function in Python, you use the def
keyword, followed by the function name and a pair of parentheses. You can also specify parameters inside the parentheses, which are variables that will be passed to the function when it is called. For example:
def greet(name):
print("Hello, " + name)
This function, called greet
, takes one parameter, name
, and prints a greeting using that parameter.
To call a function in Python, you simply use its name, followed by a pair of parentheses and any required arguments. For example:
greet("John")
This will output “Hello, John”.
Functions can also return a value using the return
keyword. For example:
def add(a, b):
return a + b
result = add(2, 3)
print(result)
This function, called add
, takes two parameters, a
and b
, and returns the sum of those two values. When the function is called, it returns the value 5, which is then stored in the variable result
.
You can define as many functions as you need in your Python program, and you can call a function from within another function. Functions can also be defined inside other functions, which are called nested functions.
Functions are a powerful and flexible tool in Python, and they are an essential part of writing modular and reusable code.