Does it run?

Consider the Python listings 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 listings 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 listings in Listing 1 will run without errors when executed?

  • random(), imported with from random import random, takes no arguments and returns a floating-point value from 0 inclusive to 1 exclusive. A possible result is 0.37; repeated calls can differ. For a reproducible API example, import random; rng = random.Random(17); rng.random() returns 0.5219839097124932.
  • print(value) displays the value followed by a new line and returns None. print("Blue") displays Blue. With multiple arguments, the default separator is one space; print(2, 5) displays 2 5.