DEV Community

sridhar n
sridhar n

Posted on

Python Day 5 – Functions, Explained With Cricket

What is a function?

Think about "playing cricket". It's actually a bunch of steps:

  1. Invite friends
  2. Take the bat and ball
  3. Go to the ground
  4. Toss
  5. Bat or field

One name, many steps inside. That's a function:

A set of instructions (a block of code) that does a specific task, and has a name.

How to create one

You use the def keyword (short for definition).

def welcome():
    print("Welcome To Python3")

welcome()
welcome()
welcome()
Enter fullscreen mode Exit fullscreen mode

Write it once, call it as many times as you want.

Python uses indentation instead of { } to mark what's inside the function. Get the spacing wrong and you'll get an error.

Things I noted

  1. You can have many functions in the same file
  2. If two functions have the same name, the latest definition wins
  3. You have to define a function before you call it
  4. You only call the ones you need
def add():
    print(5 + 10)

def subtract():
    print(10 - 5)

add()   # only this runs
Enter fullscreen mode Exit fullscreen mode

Why use functions?

  • Reuse the same code
  • Easier to maintain
  • More readable
  • Modular, better organised
  • Easier to test and debug

Parameters and arguments

def add(no1, no2):      # no1, no2 are parameters
    print(no1 + no2)

add(100, 200)           # 100, 200 are arguments
Enter fullscreen mode Exit fullscreen mode

Function overloading?

In Java you can have add(a, b) and add(a, b, c) side by side. In Python, the second definition just replaces the first, so plain overloading doesn't work.

Built-ins like print() and bin() are functions too, just predefined ones.

Top comments (0)