FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Python for Engineering Students

First year

Progress0 / 6 lessons
  1. 1. Why Python reads the way it does
  2. 2. Variables, types and f-strings
  3. 3. Lists, tuples, dicts and sets
  4. 4. Loops, comprehensions and enumerate
  5. 5. Functions, default arguments and *args
  6. 6. Files, exceptions and context managers

Courses › Python for Engineering Students

Functions, default arguments and *args

Writing functions properly, plus the mutable-default trap that silently corrupts data.

12 min read · Lesson 5 of 6 · Pro

Why functions exist

Not to save typing. To give a chunk of logic a name, so that the rest of the program reads like a description of what it does instead of how.

Python 3
def percentage(marks, total=100):
    """Return marks as a percentage of total, rounded to 2 places."""
    return round(marks / total * 100, 2)

print(percentage(72))          # 72.0
print(percentage(145, 200))    # 72.5

total=100 is a default argument. If the caller does not supply it, 100 is used. Defaults must come after non-default parameters, so def f(a=1, b) is a syntax error.

Positional and keyword arguments

The rest of this lesson is Pro

The free lessons of Python for Engineering Students finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.