Once your Python scripts grow past a few dozen lines, you start copying the same code in several places. Functions solve that. They let you give a piece of logic a name, test it once, and reuse it everywhere.
Defining and calling a function
def greet(name):
return f"Hello, {name}"
Calling greet("Asha") returns the text “Hello, Asha”. The word after def is the function name, and name is a parameter: a placeholder that receives the value you pass in.
return vs print
A very common beginner mistake is printing inside a function instead of returning. print only shows text on screen. return hands the value back so the rest of your program can use it, store it or test it. As a rule, let functions return values and print only at the top level of your script.
Default and keyword arguments
def price_with_tax(amount, rate=0.18):
return amount * (1 + rate)
Here rate has a default value, so price_with_tax(100) works. You can also pass arguments by name: price_with_tax(amount=100, rate=0.05). Named arguments make calls easier to read.
One trap: never use a mutable default such as a list (def add(item, items=[])). The same list is shared between calls. Use None and create the list inside the function instead.
Scope: where variables live
A variable created inside a function exists only inside that function. This is called local scope, and it is a good thing: functions do not accidentally change each other’s data. If a function needs a value, pass it in as an argument rather than reading a global variable.
Signs of a good function
- It does one job, and its name says what that job is.
- It takes inputs as parameters and returns a result.
- It is short enough to read without scrolling.
- You can test it with a couple of example inputs.
Practise by turning repeated code in an old script into two or three small functions. Then read clean code in Python and Python exception handling.
Python fundamentals open our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
Want structured practice with a mentor? See our Python course in Bangalore.
