M4) Does It Run?

Consider the Python code snippets in Listing 1. Each snippet attempts to generate a random floating-point number between a lower bound (inclusive) and an upper bound (exclusive).

Listing 1: Code snippets to generate a random number between a lower bound (inclusive) and an upper bound (exclusive) in Python. Which of them will run? (Question 1).
(a)
from random import random


def random_number_between(lower_bound, upper_bound)
    difference = upper_bound - lower_bound
    return difference * random() + lower_bound


def test():
    print(random_number_between(1, 10))


test()
(b)
from random import random


def random_number_between(lower_bound, upper_bound):
    return (upper_bound - lower_bound) * random() + lower_bound


def test():
    print(random_number_between(lower_bound, upper_bound))


test()
(c)
from random import random


def random_number_between(lower_bound, upper_bound):
    return (upper_bound - lower_bound) * random() + lower_bound


def test():
    print(random_number_between(1, 10))


test()
(d)
from random import random


def random_number_between(lower_bound, upper_bound):
    difference = upper_bound - lower_bound
    return difference * random() + lower_bound


def test():
    lower_bound = 1
    upper_bound = 10
    result = random_number_between(lower_bound, upper_bound)
    print(result)


test()

Which of the code snippets in Listing 1 will run without errors when executed?

Tip

Pay attention to the colon after each def header, the return statement, and whether every name used in test has been defined.

TipFunctions Used in the Python Code Snippets
  • random: function from Python’s random module that returns a floating-point number in the interval \([0, 1)\).
  • print: built-in function that displays a value.
  • def: keyword used to define a function.
  • return: statement that sends a value back to the function caller.