A function is a named block of code that does one specified job such that once you write it, you can run it as many times as you want by calling it by its name (function name).
They can be categorized into two.
- Built-in Functions—These come with Python and must be obeyed to perform properly.
- User-defined functions—Functions one creates to perform a specified task based on the requirement.
Importance of Functions Includes
- Code reasonability—You can use the function many times.
- Code readability—Which can tell the reader what happens without having to read every line of code to understand your code.
- Avoids repetition: You write the logic once instead of copying it
Examples
Example 1: Built-in Functions
print(len("Arsenal")) # counts the letters, gives 7
print(max(28, 31, 25)) # picks the biggest number, 31
Example 2: Avoiding Repetition
Without a function:
print('Go Arsenal!')
print('Go Chelsea!')
print('Go Liverpool!')
With a function:
def cheer(team): # team is the parameter
print(f'Go {team}!')
cheer('Arsenal') # 'Arsenal' is the argument
cheer('Chelsea')
cheer('Liverpool')
Example 3: Reusing a Function
def calc_points(wins, draws):
return wins * 3 + draws # win = 3 points, draw = 1
print(calc_points(10, 4)) # Gor Mahia: 34
print(calc_points(8, 6)) # AFC Leopards: 30
Top comments (0)