ByteBoard Notes Notes

Compute simple interest using a function with default parameters

Computer Science XII · Experiment 02 of 29 · Python

12-CSPython programs
Expt. No.02
Page No.4

Default parameters

Aim

To write a Python program with a function simple_interest(principal, rate=8, time=2) and call it with positional and default arguments.

Concepts used

Algorithm

  1. Define simple_interest() with default values rate = 8 and time = 2; return principal × rate × time / 100.
  2. Input the principal.
  3. Call the function with all three arguments, with two, and with only the principal.
  4. Display the three results.

Program

# Simple interest using a function with default parameters def simple_interest(principal, rate=8, time=2):    return principal * rate * time / 100 p = float(input("Enter the principal: "))print("Rate 10%, time 3 years   :", simple_interest(p, 10, 3))print("Rate 10%, default time   :", simple_interest(p, 10))print("Default rate and time    :", simple_interest(p))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python default_parameters.py
Enter the principal: 5000 Rate 10%, time 3 years : 1500.0 Rate 10%, default time : 1000.0 Default rate and time : 800.0

✓ Printed by running this program, not typed by hand.

Result

For a principal of 5000 the interest was 1500.0 with rate 10 and time 3, 1000.0 with rate 10 and the default time of 2 years, and 800.0 with the default rate of 8% and time of 2 years.

Viva voce: what the examiner may ask

01What is a default parameter?

A parameter given a value in the function header; it is used when the call leaves that argument out.

02Why must default parameters come after the others?

Positional arguments are matched left to right. def si(rate=8, principal) is a SyntaxError.

03What are positional arguments?

Arguments matched to parameters by their position in the call.

Variations for the lab test

  1. Add a default value for the principal too and call the function with no arguments.
  2. Write a function area(length, breadth=None) that gives a square's area when breadth is left out.
  3. Call simple_interest(p, time=5) and explain which rate is used.
! Common mistake Putting a default parameter before a non-default one, e.g. def simple_interest(rate=8, principal), stops the program with a SyntaxError.
Back to the 12-CS index