User defined function: defining, parameters, default values, return value

Functions are reusable mini-machines that take input parameters, apply default settings if values are missing, and deliver a clean return result.

11 min read · 12 cards · 3 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The Repeated Code Nightmare

In your Semester 1 BCA104 C labs, if you needed to calculate a percentage or format a currency symbol five different times, you had to rewrite or copy paste the exact same math lines. If you made a tiny formula mistake, you had to hunt through your entire main block to fix all five spots. Why can we not just package our calculation into a custom, named package once and call it whenever we want with new numbers?

Theory

The Juicer Machine

Think of a function like an electronic juicer machine in your kitchen. The machine itself is defined by its design (the code block). The fruits you drop into the top slot are the input parameters. The speed knob setting that defaults to medium unless you turn it manually acts like a default parameter value. Finally, the fresh juice pouring out of the spout into your glass is the returned value.

Theory

The Anatomy of a Function

A user defined function is a named, reusable block of statements that performs a specific computation. You define it using the def keyword, followed by the function name and parentheses containing optional parameters. Unlike C, Python uses dynamic typing for inputs, meaning you never declare argument data types. The code block runs only when called. It can return a final value back to the main program using the return statement.

At a glance

Table 1: Structural differences between C and Python function mechanics.

Component SyntaxBCA104 C Lang RuleBCA204 Python Rule
Declaration KeywordRequires explicit data type like int or float.Uses generic def keyword for all functions.
Parameter TypesMust explicitly declare each type inside arguments.Lists names only without any datatype prefixes.
Default ValuesStandard ANSI C does not allow default parameters.Allows assignments like param = value inside brackets.
Return StatementCan only return values matching declared header type.Can return any data object dynamically via return keyword.

Theory

A Worked Example: Automated Balance Deductions

Let us see how our PocketMoney application handles automated calculations. We want a function that subtracts an expense from our balance. We will configure it with a default category named miscellaneous so that the program runs smoothly even if the user forgets to type an expense description.

Practical

PocketMoney Function Ledger Engine

def calculate_remainder(balance, spend, category="Misc"):
    print("Category processed: " + category)
    remaining = balance - spend
    return remaining

# Call 1: Providing all parameters manually
wallet1 = calculate_remainder(500, 45, "Food")
print(wallet1)

# Call 2: Skipping the optional category parameter
wallet2 = calculate_remainder(100, 20)
print(wallet2)

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

Trace the Twin Function Calls

Analyze the Python script above mentally. What exact textual lines and numeric balances will display sequentially on the screen? Sketch your prediction before tapping.

Show the answer

The script will output:

Category processed: Food

455

Category processed: Misc

80

Why? In Call 1, the explicit string "Food" overwrites the default setting. In Call 2, omitting the third argument causes Python to fall back on the preset value "Misc". Both calculations complete and return their results cleanly to update wallet1 and wallet2 respectively.

Quiz

What will happen if you position a parameter with a default value before a mandatory parameter without a default value inside your def line?

  1. The script runs normally and assumes missing items are filled from right to left.
  2. Python throws an immediate SyntaxError: non-default argument follows default argument.
  3. The function works perfectly but automatically converts all parameters into strings.
  4. The program compiles like a standard C application but skips calculation steps.
Show the answer

Python throws an immediate SyntaxError: non-default argument follows default argument.

Python requires all mandatory parameters (those without default values) to be placed first. Any optional parameters with default values must be grouped at the very end of the parentheses checklist. Mixing up this order causes an instant syntax crash.

Quiz

Study this short function structure: def add_bonus(balance): total = balance + 50 print(add_bonus(500)) What will print on the screen?

  1. 550
  2. SyntaxError: missing return declaration
  3. None
  4. 500
Show the answer

None

In Python, if a function finishes executing its statements without encountering an explicit return keyword, it automatically sends back a special built-in object called None. This is a signature university viva question!

Watch out

The Classic Trap: The Vanishing Variable

A classic mark-losing mistake in university laboratory exams is writing a function variable like remaining = balance - spend inside a definition block, and then trying to print or inspect remaining outside in your main script body. Python will throw a NameError: name remaining is not defined because any variable created inside a function scope lives and dies completely inside that specific functional boundary.

Theory

Connecting Functions to Semester 3 Database Modules

Mastering dynamic parameters makes back-end development highly modular. In Semester 3 (BCA303), when you connect Python scripts to an SQLite database, you will encapsulate SQL execution lines inside single functions like def query_db(sql_string, limits = 10):. This allows you to fetch records on the fly anywhere in your system using simple single line triggers.

Summary

Key takeaways

  • Functions are declared using the def keyword followed by custom naming identifiers.
  • Python omits explicit parameters and return type declaration labels entirely.
  • Default values must be strictly positioned at the right end of argument lists.
  • Omiting an explicit return statement forces a function to automatically deliver a value of None.
  • Variables declared inside a function body remain local to that specific block scope.
  • Memory Hook: Packages contain procedures, returning values safely!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python Fundamentals

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

User defined function: defining, parameters, default values, return value · Programming Skills · Gri-Learn