Default Values

All of the functions that we have looked at to this point, you had to ensure that you were sending the exact same number of parameters to the function as it was expecting. To help us do this a good IDE will have, “auto-complete” giving us a little pop out window to show us what should be passed over to the function.

Some built in functions we have been using can be accessed in multiple different ways though. For example in Python there is a built in function called random.randrange(). It is kind of like random.ranint() that we have used in the past. Here is the definition for random.ranint():

random.randint(a, b)
// Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

Notice that “a & b” are our starting and ending points.

Here is the definition for random.randrange():

random.randrange(start, stop[, step])
// The positional argument pattern matches that of range().

First off there is actually 2 seperate ways we could call this function:

  • random.randrange(start, stop)

  • random.randrange(start, stop, step)

It seems that step is, “optional” which it is. By default, if you do not provide it, then python assumes the value is just 1. You can choose for example to place in a 2, and then only even numbers will be chosen. Here is how we would define the function random.randrange() to get this optional parameter:

def randrange(start, stop, step = 1):

Notice that right in the declaration of the function the, “default optional parameter” is being set. If it is not provided as a parameter, the default value is just used. Each programming language has its own syntax to make this kind of optional parameter work. Here is an example:

Code for Function with Default Values

1
// No default values for functions in C
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program prints out your name, using default function parameters

#include <iostream>

std::string FullName(std::string firstName, std::string lastName,
                     std::string middleName = "") {
    // return the full formal name

    std::string fullName;

    fullName = firstName;
    if (middleName.size() != 0) {
        fullName = fullName + " " + middleName[0] + ".";
    }
    fullName = fullName + " " + lastName;

    return fullName;
}


int main() {
    // gets a users name and prints out their formal name

    std::string firstName;
    std::string question;
    std::string middleName = "";
    std::string lastName;
    std::string fullName;

    // input
    std::cout << "Enter your first name: ";
    std::cin >> firstName;
    std::cout << "Do you have a middle name? (y/n): ";
    std::cin >> question;
    if (question == "Y" || question == "YES" || question == "y") {
        std::cout << "Enter your middle name: ";
        std::cin >> middleName;
    }
    std::cout << "Enter your last name: ";
    std::cin >> lastName;
    std::cout << std::endl;

    // call functions
    if (middleName != "") {
        fullName = FullName(firstName, lastName, middleName);
    } else {
        fullName = FullName(firstName, lastName);
    }
    std::cout << "Your formal name is " << fullName << "." << std::endl;

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program prints out your name, using default function parameters
*/

using System;

/*
 * The Program class
 * Contains all methods for performing how local and global variables work
*/
class Program {

    static string FullName(string firstName, string lastName, string middleName = "") {
        // this function calculates the full name
        string fullName;

        if (middleName == "") {
            fullName = firstName + " " + lastName;
        } else {
            fullName = firstName + " " + middleName + " " + lastName;
        }
        return fullName;
    }

    public static void Main (string[] args) {
        // this function gets a users name and prints out their formal name
        string firstName;
        string question;
        string middleName = "";
        string lastName;
        string fullName;

        //input
        Console.Write("Enter your first name: ");
        firstName = Console.ReadLine();
        Console.Write("Do you have a middle name? (y/n): ");
        question = Console.ReadLine();
        if (question.ToUpper() == "Y" || question.ToUpper() == "YES") {
            Console.Write("Enter your middle name: ");
            middleName = Console.ReadLine();
        }
        Console.Write("Enter your last name: ");
        lastName = Console.ReadLine();
        Console.WriteLine();

        // process & output
        if (middleName != "") {
            fullName = FullName(firstName, lastName, middleName);
        } else {
            fullName = FullName(firstName, lastName);
        }
        Console.WriteLine($"Your formal name is {fullName}.");

        Console.WriteLine ("\nDone.");
    }
}
1
// No default values for functions in Go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
 * This program shows how local and global variables work
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner; // Import the Scanner class

final class Main {
  private Main() {
    // Prevent instantiation
    // Optional: throw an exception e.g. AssertionError
    // if this ever *is* called
    throw new IllegalStateException("Cannot be instantiated");
  }

  /**
   * Main entry point into program.
   *
   * @param args nothing passed in
   */
  public static void main(final String[] args) {
    // this function calculates total from subtotal and tax
    final float HST = 0.13f;
    float tax;
    float subTotal;
    float total;

    Scanner scanner = new Scanner(System.in);

    // input
    System.out.print("Enter the subtotal: $");
    subTotal = scanner.nextFloat();

    // process
    tax = subTotal * HST;
    total = subTotal + tax;

    // output
    System.out.println();
    System.out.printf("The HST is: $%.2f.\n", tax);
    System.out.printf("The total cost is: $%.2f.\n", total);

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Copyright (c) 2020 Mr. Coxall All rights reserved
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program prints out your name, using default function parameters

const prompt = require('prompt-sync')()

function FullName(firstName, lastName, middleName = "") {
    // return the full formal name
    let fullName = firstName

    if (middleName.length != 0) {
        fullName = fullName + " " + middleName[0] + "."
    }
    fullName = fullName + " " + lastName

    return fullName
}

// this function function calculates the full name
let middleName = ""

// input
let firstName = prompt('Enter your first name: ')
let question = prompt('Do you have a middle name? (y/n): ')

if (question.toUpperCase() == "Y" || question.toUpperCase() == "YES") {
    middleName = prompt('Enter your middle name: ')
}
let lastName = prompt('Enter your last name: ')

// call functions
let fullName = ""

if (middleName != "") {
    fullName = FullName(firstName, lastName, middleName)
} else {
    fullName = FullName(firstName, lastName)
}
console.log(`\nYour formal name is ${fullName}.`)

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module prints out your name, using default function parameters
"""


def full_name(first_name: str, last_name: str, middle_name: str | None = None) -> str:
    """The full_name() function calculates the full formal name, returns str."""
    # return the full formal name

    full_name = first_name
    if middle_name is not None:
        full_name = full_name + " " + middle_name[0] + "."
    full_name = full_name + " " + last_name

    return full_name


def main() -> None:
    """The main() function gets a users name and prints out their formal name, returns None."""

    middle_name = None

    # input & process
    first_name = input("Enter your first name: ")
    question = input("Do you have a middle name? (y/n): ")
    if question.upper() == "Y" or question.upper() == "YES":
        middle_name = input("Enter your middle name: ")
    last_name = input("Enter your last name: ")

    if middle_name is not None:
        name = full_name(first_name, last_name, middle_name)
    else:
        name = full_name(first_name, last_name)

    # output
    print(f"\nYour formal name is {name}.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output