DEV Community

Mungai Erick Gachuhi
Mungai Erick Gachuhi

Posted on Edited on

LATEST AS A PYTHON BEGINNER : PYTHON FUNCTIONS

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.

  1. Built-in Functions—These come with Python and must be obeyed to perform properly.
  2. User-defined functions—Functions one creates to perform a specified task based on the requirement.

Importance of Functions Includes

  1. Code reasonability—You can use the function many times.
  2. Code readability—Which can tell the reader what happens without having to read every line of code to understand your code.
  3. 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
Enter fullscreen mode Exit fullscreen mode

Example 2: Avoiding Repetition

Without a function:

print('Go Arsenal!')
print('Go Chelsea!')
print('Go Liverpool!')
Enter fullscreen mode Exit fullscreen mode

With a function:

def cheer(team):          # team is the parameter
    print(f'Go {team}!')

cheer('Arsenal')          # 'Arsenal' is the argument
cheer('Chelsea')
cheer('Liverpool')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)