Code Blocks Performing Specific Tasks, Functions
In programming, a Function
is a predefined block of code designed to perform a specific task.
For example, if you need to multiply a given number by 10 and add 5 repeatedly in different parts of your program, you can define this task as a function and call it whenever needed.
def calculate(x):
# Store the result of multiplying the given number x by 10 and adding 5 in the variable result
result = x * 10 + 5
# Return the result
return result
A function is defined using the def
keyword, followed by the function name
and the parameters
which are variables that implement the function's logic.
In the example above, the function name is calculate
, and the parameter is x
.
The line where the function name and parameters are defined ends with a colon (:
), indicating the start of the code block that performs the function's task.
The code block in the above function multiplies the given number x
by 10, adds 5 to it, stores the result in the result
variable, and then returns this value.
How to Use Functions?
Once the calculate
function is defined as shown in the example above, you can use it in your program by calling calculate(3)
, calculate(7)
, etc.
def calculate(x):
result = x * 10 + 5
return result
result1 = calculate(3)
result2 = calculate(7)
# Print 35
print(result1)
# Print 75
print(result2)
The values 3 and 7 passed inside the parentheses are assigned to the function's parameter x
.
Hence, for 3, the calculation 3 * 10 + 5 = 35
is performed, and for 7, the calculation 7 * 10 + 5 = 75
is performed.
Using functions in this way enhances the reusability and readability of your code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.