What is a function?
Think about "playing cricket". It's actually a bunch of steps:
- Invite friends
- Take the bat and ball
- Go to the ground
- Toss
- 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()
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
- You can have many functions in the same file
- If two functions have the same name, the latest definition wins
- You have to define a function before you call it
- You only call the ones you need
def add():
print(5 + 10)
def subtract():
print(10 - 5)
add() # only this runs
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
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)