Functions
Pythons Tutorials
Think of functions as mini-programs within your program. They’re blocks of code that perform specific tasks, making your code less repetitive and more efficient. Let’s go through what you need to know about Python functions:
1. Defining and Calling Functions:
To create a function, you define its name, input (if any), and what it should do. Then you can call it whenever you need that specific task done.
Example: Defining and Calling a Function
# Defining a function
def greet(name):
print("Hello, " + name + "!")
# Calling the function
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
3. Return Statements:
Functions can also provide output using the return
statement. This output can be used in other parts of your code.
Example: Function with Return Statement
In this example, the result of the function “add” is stored in the variable sum_result.
def add(a, b):
result = a + b
return result
sum_result = add(5, 3)
print("The sum is:", sum_result) # Output: The sum is: 8
4. Parameters and Arguments:
When you call a function, you provide values called arguments. These values are received by the function through parameter variables that act as placeholders.
Example: Using Parameters and Arguments
In this example, two parameters/ arguments are passed into the exponent function.
def exponent(base, power):
result = base ** power
return result
result = exponent(2, 3)
print("Result:", result) # Output: Result: 8