Functions are a crucial part of programming that allow you to encapsulate a set of instructions that you can reuse throughout your code. Functions take input(s) and return output(s) to the caller. They are a building block of any program and allow for better code organization and reusability. In this tutorial, we'll cover the basics of creating and using functions in Python.
Creating Functions:
In Python, you can create a function using the def
keyword followed by the function name, and parentheses containing the parameters passed to the function. The code block within the function starts with a colon (:) and is indented.
Here is the syntax for defining a function:
def function_name(parameters):
# function body
return value
In the above code, function_name
is the name of the function, parameters
are the inputs that the function takes, # function body
is where you write the instructions to be executed when the function is called, and return
statement is used to send the result back to the caller.
Easy Sample Code:
Here is an example of a simple function that takes in two numbers and returns their sum:
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(2, 3)
print(result)
Output: 5
In the above code, we defined a function add_numbers
that takes two parameters a
and b
. The function adds the two numbers and returns their sum. We called the function with the arguments 2
and 3
, and assigned the result to a variable named result
. We then printed the value of result
.
Medium Sample Code:
Here is an example of a function that takes in a list of numbers and returns their average:
def calculate_average(numbers):
sum = 0
for num in numbers:
sum += num
avg = sum / len(numbers)
return avg
result = calculate_average([2, 4, 6, 8])
print(result)
Output: 5.0
In the above code, we defined a function calculate_average
that takes a list of numbers as its parameter. We initialized a variable sum
to zero and used a for
loop to iterate through each number in the list and add it to the sum
variable. We then calculated the average by dividing the sum
by the length of the list, and returned the result. We called the function with the list [2, 4, 6, 8]
and assigned the result to a variable named result
. We then printed the value of result
.
Hard Sample Code:
Here is an example of a function that takes in a string and returns the reverse of the string:
def reverse_string(string):
reversed_str = ""
for i in range(len(string)-1, -1, -1):
reversed_str += string[i]
return reversed_str
result = reverse_string("Hello, World!")
print(result)