Popular Searches
Popular Course Categories
Popular Courses

Working with Parameters and Return Values

Working with Parameters and Return Values

Functions and Modular Programming

Working with Parameters and Return Values in Python

Course: Python Training

Topic: Working with Parameters and Return Values

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Free Course Demo

Website: Visit JustAcademy


1. Introduction to Parameters and Return Values

Functions are one of the most important building blocks in Python programming. They allow developers to organize code into reusable blocks that perform specific tasks. Parameters and return values make functions flexible by allowing them to receive information and produce results.

Parameters are variables defined in a function declaration that receive values when the function is called. Return values are the results a function sends back to the code that called it.

For example, a function that calculates the total price of products can receive the product price and quantity as parameters and return the calculated total.

def calculate_total(price, quantity):
    total = price * quantity
    return total

result = calculate_total(250, 3)
print(result)

Output:

750

In this example, price and quantity are parameters. The values 250 and 3 are arguments passed during the function call. The function returns 750, which is stored in the variable result.

2. Learning Objectives

  • Understand the difference between parameters and arguments.
  • Learn how to define functions with parameters.
  • Explore positional, keyword, default, and variable-length arguments.
  • Understand how the return statement works.
  • Learn the difference between returning a value and printing a value.
  • Return multiple values from a function.
  • Use parameters and return values in practical programs.
  • Identify common mistakes and follow function-writing best practices.

3. Understanding Parameters and Arguments

3.1 What Is a Parameter?

A parameter is a variable listed inside a function's parentheses when the function is defined. It acts as a placeholder for the input that the function will receive.

def greet(name):
    print("Hello,", name)

greet("Aarav")

Output:

Hello, Aarav

Here, name is the parameter. It receives the value supplied when greet() is called.

3.2 What Is an Argument?

An argument is the actual value or expression supplied to a function when calling it.

def square(number):
    return number * number

answer = square(5)
print(answer)

Output:

25

In this example, number is the parameter and 5 is the argument.

3.3 Parameters vs. Arguments

Feature Parameters Arguments
Meaning Variables defined in the function definition. Values or expressions supplied in a function call.
Location Inside the function definition. Inside the function call.
Purpose Receive input for the function. Provide data to the function.
Example def add(a, b): add(10, 20)

4. Defining Functions with Parameters

In Python, the def keyword defines a function. Parameters are written inside parentheses, separated by commas. The function body is indented below the definition.

def function_name(parameter1, parameter2):
    # Function body
    statement
    return result

Consider a function that calculates the area of a rectangle:

def rectangle_area(length, width):
    area = length * width
    return area

print(rectangle_area(8, 5))

Output:

40

The function receives two values, multiplies them, and returns the result. The same function can be reused with different dimensions.

print(rectangle_area(10, 4))
print(rectangle_area(7, 6))
print(rectangle_area(12, 3))

Output:

40
42
36

5. Types of Function Parameters and Arguments

5.1 Positional Arguments

Positional arguments are matched to parameters according to their order in the function call. The first argument is assigned to the first parameter, the second to the second parameter, and so on.

def introduce(name, age):
    return f"My name is {name} and I am {age} years old."

print(introduce("Riya", 22))

Output:

My name is Riya and I am 22 years old.

Changing the order of the arguments can change the meaning of the result.

def subtract(a, b):
    return a - b

print(subtract(10, 4))
print(subtract(4, 10))

Output:

6
-6

Important: Use positional arguments carefully when parameter order affects the result.

5.2 Keyword Arguments

Keyword arguments specify parameter names when calling a function. They make function calls easier to read and allow arguments to be supplied in a different order.

def student_details(name, course, city):
    return f"{name} studies {course} and lives in {city}."

print(student_details(
    city="Mumbai",
    name="Kabir",
    course="Python"
))

Output:

Kabir studies Python and lives in Mumbai.

Keyword arguments are useful when functions have multiple parameters with similar data types or when a call needs to be self-explanatory.

5.3 Default Parameters

A default parameter has a predefined value that Python uses when the caller does not supply that argument.

def greet(name, message="Welcome"):
    return f"{message}, {name}!"

print(greet("Anaya"))
print(greet("Anaya", "Good morning"))

Output:

Welcome, Anaya!
Good morning, Anaya!

The parameter message defaults to "Welcome". A supplied argument overrides the default.

Rule: In a function definition, parameters with default values must generally follow parameters without default values.

# Correct
def display(name, city="Pune"):
    return f"{name} lives in {city}"

# Incorrect: causes a SyntaxError
# def display(city="Pune", name):
#     return f"{name} lives in {city}"

5.4 Variable-Length Positional Arguments: *args

Use *args when a function needs to accept any number of positional arguments. Python collects the extra positional arguments into a tuple.

def calculate_sum(*numbers):
    return sum(numbers)

print(calculate_sum(10, 20))
print(calculate_sum(5, 10, 15, 20))
print(calculate_sum(1, 2, 3, 4, 5))

Output:

30
50
15

The name args is a convention; the asterisk is what enables variable-length positional arguments.

5.5 Variable-Length Keyword Arguments: **kwargs

Use **kwargs when a function needs to accept an arbitrary number of keyword arguments. Python collects them into a dictionary.

def display_profile(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

display_profile(
    name="Meera",
    course="Python",
    city="Thane"
)

Output:

name: Meera
course: Python
city: Thane

The names args and kwargs are conventional, but not mandatory. The symbols * and ** provide the relevant behavior.

5.6 Keyword-Only Parameters

Parameters written after a standalone * must be supplied by keyword. This can make function calls clearer and reduce mistakes.

def create_account(username, *, active=True):
    return {
        "username": username,
        "active": active
    }

print(create_account("sam"))
print(create_account("sam", active=False))

Output:

{'username': 'sam', 'active': True}
{'username': 'sam', 'active': False}

5.7 Positional-Only Parameters

Parameters written before / in a function definition are positional-only. They cannot be supplied by keyword.

def divide(a, b, /):
    return a / b

print(divide(20, 4))

# This call is invalid:
# divide(a=20, b=4)

Output:

5.0

Positional-only and keyword-only parameters can help API designers control how functions are called.

6. Introduction to Return Values

The return statement ends the current function call and sends a value back to the caller. That value can be assigned to a variable, used in a calculation, passed to another function, or displayed with print().

def multiply(a, b):
    return a * b

result = multiply(6, 7)
print(result)
print(result + 10)

Output:

42
52

The function returns 42. The calling code can then reuse the returned result.

6.1 Why Return Values Are Important

  • Reusability: A returned result can be used in several places.
  • Modularity: Functions can calculate results independently of how those results are displayed.
  • Testing: Tests can compare returned values with expected values.
  • Composition: The result of one function can become the input of another.
  • Maintainability: Separating calculations from output makes programs easier to update.

7. The Difference Between print() and return

A common beginner mistake is assuming that printing a value is the same as returning it. They serve different purposes.

Feature print() return
Purpose Displays information to the output stream, usually the console. Sends a value back to the caller.
Can the result be assigned? The call itself normally evaluates to None. Yes, the returned value can be assigned.
Ends the function? No, not by itself. Yes, when executed inside a function.
Typical use Showing messages or debugging information. Producing a result for later use.

Example using print():

def add_and_print(a, b):
    print(a + b)

result = add_and_print(5, 3)
print("Stored result:", result)

Output:

8
Stored result: None

The function displays 8, but it does not return that value. Therefore, the variable result receives None.

Example using return:

def add_and_return(a, b):
    return a + b

result = add_and_return(5, 3)
print("Stored result:", result)

Output:

Stored result: 8

Use return when the caller needs the calculated result. Use print() when the intention is to display information.

8. Returning Values of Different Data Types

A Python function can return integers, floating-point numbers, strings, Boolean values, lists, dictionaries, tuples, objects, or other values.

8.1 Returning an Integer

def get_age():
    return 25

print(get_age())

Output: 25

8.2 Returning a String

def get_message(name):
    return f"Hello, {name}!"

print(get_message("Aditi"))

Output: Hello, Aditi!

8.3 Returning a Boolean Value

def is_adult(age):
    return age >= 18

print(is_adult(21))
print(is_adult(15))

Output:

True
False

8.4 Returning a List

def get_even_numbers():
    return [2, 4, 6, 8, 10]

numbers = get_even_numbers()
print(numbers)
print(numbers[2])

Output:

[2, 4, 6, 8, 10]
6

8.5 Returning a Dictionary

def get_student():
    return {
        "name": "Rahul",
        "course": "Python",
        "score": 88
    }

student = get_student()
print(student["name"])
print(student["score"])

Output:

Rahul
88

9. Returning Multiple Values from a Function

Python allows a function to return multiple values separated by commas. These values are packaged into a tuple, which can be unpacked into separate variables.

def calculate(a, b):
    total = a + b
    difference = a - b
    product = a * b
    return total, difference, product

result = calculate(10, 4)
print(result)

total, difference, product = calculate(10, 4)
print("Total:", total)
print("Difference:", difference)
print("Product:", product)

Output:

(14, 6, 40)
Total: 14
Difference: 6
Product: 40

This technique is useful when one operation naturally produces several related results, such as minimum and maximum values or quotient and remainder.

def divide_with_remainder(dividend, divisor):
    quotient = dividend // divisor
    remainder = dividend % divisor
    return quotient, remainder

q, r = divide_with_remainder(17, 5)
print("Quotient:", q)
print("Remainder:", r)

Output:

Quotient: 3
Remainder: 2

Ensure that the caller unpacks the same number of values returned by the function, unless it deliberately uses an appropriate unpacking pattern.

10. Understanding the None Return Value

If a function finishes without executing a return statement with a value, Python returns None automatically. An explicit return without an expression also returns None.

def show_message():
    print("Learning Python")

def stop_process():
    return

first = show_message()
second = stop_process()

print(first)
print(second)

Output:

Learning Python
None
None

None represents the absence of a value. It is different from 0, an empty string, or False.

11. Using Return Statements with Conditional Logic

A function can return different values depending on conditions. Once a return statement executes, the function ends immediately.

def check_number(number):
    if number > 0:
        return "Positive"
    elif number < 0:
        return "Negative"
    else:
        return "Zero"

print(check_number(12))
print(check_number(-5))
print(check_number(0))

Output:

Positive
Negative
Zero

Every possible branch in this example returns a result. This makes the function's behavior clear and predictable.

11.1 Early Return

An early return handles a special case near the beginning of a function and avoids unnecessary nested conditions.

def calculate_average(numbers):
    if not numbers:
        return None

    return sum(numbers) / len(numbers)

print(calculate_average([10, 20, 30]))
print(calculate_average([]))

Output:

20.0
None

In this example, an empty list returns None because an average cannot be calculated from zero items. The caller should check for this case before using the result as a number.

12. Passing Arguments and Returning Results Between Functions

Functions can work together by passing a value returned from one function into another. This helps separate a complex task into smaller operations.

def get_discounted_price(price, discount_percent):
    discount = price * discount_percent / 100
    return price - discount

def calculate_tax(amount, tax_percent):
    return amount * tax_percent / 100

price_after_discount = get_discounted_price(2000, 10)
tax = calculate_tax(price_after_discount, 18)
final_price = price_after_discount + tax

print("Price after discount:", price_after_discount)
print("Tax:", tax)
print("Final price:", final_price)

Output:

Price after discount: 1800.0
Tax: 324.0
Final price: 2124.0

The discount function calculates the discounted price. That returned value becomes the input to the tax function. The final result is calculated from both operations.

13. Argument Validation and Type Considerations

Parameters allow input to be provided, but a function may need to validate that the input is appropriate. Python does not automatically enforce ordinary type annotations at runtime.

13.1 Validating Inputs

def calculate_percentage(part, whole):
    if whole == 0:
        raise ValueError("Whole must not be zero")

    if part < 0 or whole < 0:
        raise ValueError("Values must not be negative")

    return (part / whole) * 100

print(calculate_percentage(25, 100))

Output:

25.0

If the whole value is zero or either input is negative, the function raises a ValueError. Raising an exception makes invalid input explicit rather than returning a misleading result.

13.2 Using Type Hints

Type hints document the expected input and output types. They help readers, editors, and static analysis tools, but Python generally does not enforce them automatically.

def calculate_total(price: float, quantity: int) -> float:
    return price * quantity

total = calculate_total(149.50, 3)
print(total)

Output:

448.5

Here, the annotations indicate that price is expected to be a float, quantity an integer, and the return value a float. The actual numeric result may be an integer in some cases, because Python's runtime does not enforce the annotation.

14. Mutable Default Arguments: A Common Pitfall

Default parameter values are evaluated once when the function is defined, not each time the function is called. This can cause unexpected behavior when the default is a mutable object such as a list or dictionary.

Avoid this pattern:

def add_item(item, items=[]):
    items.append(item)
    return items

The same list may be reused across calls. A safer approach is to use None as the default and create a new list inside the function.

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

print(add_item("Pen"))
print(add_item("Book"))
print(add_item("Pencil", ["Eraser"]))

Output:

['Pen']
['Book']
['Eraser', 'Pencil']

Each call without an explicitly supplied list gets its own new list.

15. Practical Example: Student Grade Calculator

This example combines parameters, calculations, conditional logic, and return values to create a reusable grade calculator.

def calculate_average(marks):
    if not marks:
        raise ValueError("At least one mark is required")

    if any(mark < 0 or mark > 100 for mark in marks):
        raise ValueError("Marks must be between 0 and 100")

    return sum(marks) / len(marks)

def get_grade(average):
    if average >= 90:
        return "A"
    elif average >= 75:
        return "B"
    elif average >= 60:
        return "C"
    elif average >= 40:
        return "D"
    else:
        return "F"

marks = [85, 92, 78, 88, 90]
average = calculate_average(marks)
grade = get_grade(average)

print("Marks:", marks)
print("Average:", average)
print("Grade:", grade)

Output:

Marks: [85, 92, 78, 88, 90]
Average: 86.6
Grade: B

How it works:

  1. The marks list is passed to calculate_average().
  2. The function checks that the list is not empty and that all marks fall within the allowed range.
  3. The average is calculated and returned.
  4. The returned average is passed to get_grade().
  5. The grade is returned and printed by the main program.

16. Practical Example: Shopping Cart Total

A shopping cart function can accept a list of item prices and a discount percentage, then return the final amount after applying the discount.

def calculate_cart_total(prices, discount_percent=0):
    if not 0 <= discount_percent <= 100:
        raise ValueError("Discount must be between 0 and 100")

    if any(price < 0 for price in prices):
        raise ValueError("Prices must not be negative")

    subtotal = sum(prices)
    discount = subtotal * discount_percent / 100
    return subtotal - discount

cart = [499, 299, 199]
total = calculate_cart_total(cart, discount_percent=10)

print("Subtotal:", sum(cart))
print("Final total:", total)

Output:

Subtotal: 997
Final total: 897.3

This example demonstrates a list parameter, a default parameter, a keyword argument, input validation, and a returned numeric result.

17. Practical Example: Employee Salary Calculation

Parameters and return values can also be used to calculate employee salaries from basic pay and allowances.

def calculate_salary(basic_salary, allowance_percent, deduction):
    if basic_salary < 0 or deduction < 0:
        raise ValueError("Salary and deduction must not be negative")

    if not 0 <= allowance_percent <= 100:
        raise ValueError("Allowance percentage must be between 0 and 100")

    allowance = basic_salary * allowance_percent / 100
    net_salary = basic_salary + allowance - deduction
    return net_salary

salary = calculate_salary(30000, 20, 2500)
print("Net Salary:", salary)

Output:

Net Salary: 33500.0

The function accepts three parameters, performs the salary calculation, and returns the final result for use elsewhere in the application.

18. Scope of Parameters and Local Variables

Parameters and variables created inside a function are local to that function by default. They are normally available only while the function is executing.

def calculate_square(number):
    result = number ** 2
    return result

print(calculate_square(6))

# The following names are not defined in the outer scope:
# print(number)
# print(result)

Output:

36

The parameter number and the local variable result belong to the function's local scope. The returned value can be used outside the function even though those local variable names are not directly accessible there.

19. Common Errors When Working with Parameters and Return Values

Error Example Solution
Missing required argument add(5) when add(a, b) requires two arguments. Provide all required arguments or define suitable defaults.
Too many positional arguments add(1, 2, 3) for a two-parameter function. Pass the expected number of arguments or use *args when appropriate.
Incorrect argument order Calling subtract(3, 10) when intending subtract(10, 3). Check parameter order or use keyword arguments.
Printing instead of returning Assigning the result of a function that only calls print(). Use return when the caller needs the result.
Unreachable return Placing a needed return after an earlier return statement. Review the execution flow and move the return statement to the correct location.
Inconsistent return behavior Some branches return a number while another unintentionally returns None. Define the intended behavior for every execution path.
Mutable default value Using items=[] as a default parameter. Use None and create a fresh list or dictionary inside the function.
Invalid input Dividing by zero or using negative prices without checking. Validate inputs and raise meaningful exceptions where appropriate.

20. Best Practices for Parameters and Return Values

  • Choose descriptive parameter names, such as price, quantity, and discount_percent.
  • Keep functions focused on one clear task.
  • Use return for results that need to be reused.
  • Use keyword arguments when they make calls more readable.
  • Use default parameters only when the default behavior is sensible.
  • Avoid mutable objects as default parameter values.
  • Validate input when invalid values could cause incorrect results or exceptions.
  • Use type hints when they improve clarity and maintainability.
  • Document complex functions with docstrings describing parameters, return values, and exceptions.
  • Ensure that all branches have intentional return behavior.
  • Avoid unnecessary global variables when values can be passed as parameters.
  • Write tests for normal cases, boundary cases, and invalid input.

21. Function Documentation with Docstrings

A docstring explains what a function does and can describe its parameters and return value. It is written as a string immediately after the function definition.

def calculate_area(length: float, width: float) -> float:
    """Return the area of a rectangle.

    Args:
        length: The rectangle's length.
        width: The rectangle's width.

    Returns:
        The calculated area.
    """
    return length * width

print(calculate_area(5, 4))
print(calculate_area.__doc__)

First output:

20

A well-written docstring helps other developers understand a function without having to inspect every line of its implementation.

22. Exercises for Practice

Exercise 1: Add Two Numbers

Create a function called add_numbers() that accepts two numbers and returns their sum.

Expected result: Calling add_numbers(12, 8) should return 20.

Exercise 2: Convert Celsius to Fahrenheit

Create a function that accepts a temperature in Celsius and returns the Fahrenheit equivalent using the formula (celsius * 9 / 5) + 32.

Expected result: convert_temperature(0) should return 32.0.

Exercise 3: Find the Largest Number

Write a function that accepts three numbers and returns the largest value. Test it with positive, negative, and equal numbers.

Exercise 4: Calculate a Discount

Write a function that accepts a price and a discount percentage, then returns the discounted price. Include validation for negative prices and discount percentages outside the range from 0 to 100.

Exercise 5: Return Multiple Values

Create a function that accepts a list of numbers and returns the minimum, maximum, and sum. Decide how the function should behave when the list is empty.

Exercise 6: Calculate a Factorial

Create a function that accepts a non-negative integer and returns its factorial. Validate the input and return 1 for 0.

23. Mini Project: Simple Calculator Using Functions

Project objective: Build a calculator using parameters and return values to perform addition, subtraction, multiplication, and division.

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def calculate(a, operator, b):
    if operator == "+":
        return add(a, b)
    elif operator == "-":
        return subtract(a, b)
    elif operator == "*":
        return multiply(a, b)
    elif operator == "/":
        return divide(a, b)
    else:
        raise ValueError("Unsupported operator")

print(calculate(10, "+", 5))
print(calculate(10, "-", 5))
print(calculate(10, "*", 5))
print(calculate(10, "/", 5))

Output:

15
5
50
2.0

Project tasks:

  1. Add support for exponentiation using **.
  2. Validate that the inputs are numeric.
  3. Allow the user to enter values using input().
  4. Handle invalid operators and division by zero gracefully.
  5. Add unit tests for each operation.

24. Interview Questions and Answers

Q1. What is a parameter in Python?

A parameter is a variable defined in a function declaration that receives a value when the function is called.

Q2. What is an argument?

An argument is a value or expression supplied to a function call and assigned to a parameter.

Q3. What is the difference between a parameter and an argument?

A parameter is the named placeholder in the function definition, whereas an argument is the actual input provided in the call.

Q4. What does the return statement do?

The return statement ends the current function execution and passes a value back to the caller.

Q5. What happens if a function has no return statement?

If execution reaches the end without returning a value, Python returns None automatically.

Q6. What is the difference between print() and return?

print() displays information, while return provides a result to the calling code.

Q7. Can a Python function return multiple values?

Yes. A function can return multiple comma-separated values, which Python packages into a tuple. The caller can unpack the values into separate variables.

Q8. What are default parameters?

Default parameters have predefined values that are used when the caller omits the corresponding arguments.

Q9. What are *args and **kwargs?

*args collects additional positional arguments into a tuple. **kwargs collects additional keyword arguments into a dictionary.

Q10. What is a keyword argument?

A keyword argument supplies a value by naming its parameter, such as greet(name="Aarav").

Q11. Can a function return a list or dictionary?

Yes. Functions can return collections such as lists, dictionaries, tuples, and sets, as well as other Python objects.

Q12. Why should mutable default arguments be avoided?

Mutable defaults are created once when the function is defined and may be shared between calls. Using None and creating a new object inside the function avoids this problem.

Q13. What is an early return?

An early return exits a function as soon as a particular condition is met, often simplifying validation and conditional logic.

Q14. What are type hints?

Type hints document expected parameter and return types. They support readability and static analysis but are not automatically enforced by Python at runtime.

Q15. Why are return values useful in testing?

Tests can call a function and compare its returned value with an expected result, making the function's behavior easier to verify.

25. Quick Revision Checklist

  • Understand the difference between parameters and arguments.
  • Know how positional and keyword arguments work.
  • Understand default parameters and their ordering rules.
  • Use *args and **kwargs for variable-length inputs.
  • Use keyword-only and positional-only parameters where appropriate.
  • Use return to pass calculated results back to the caller.
  • Understand why print() is not a substitute for return.
  • Know that functions without a returned value produce None.
  • Return multiple values and unpack them when needed.
  • Validate inputs and handle special cases intentionally.
  • Avoid mutable default arguments.
  • Practice writing, documenting, and testing reusable functions.

26. Conclusion

Parameters and return values are essential for creating reusable, modular, and maintainable Python programs. Parameters allow functions to accept different inputs, while return values allow the results of calculations to be reused by other parts of a program.

By practicing positional and keyword arguments, default values, *args, **kwargs, conditional returns, multiple return values, validation, and type hints, you can write functions that are easier to understand and test. Apply these concepts in small projects such as calculators, grade systems, shopping carts, and salary calculators to strengthen your Python programming skills.

Continue learning: Explore the Python Training Course, register for a course demo, or visit the JustAcademy website for more learning resources.

whatsapp