In this challenge we will focus on using the random library to generate random numbers in Python.
The randint() function is used to generate a random integer (whole number) within a given range.
number = randint(1,100)
The above code would generate a random number between 1 and 100.
The aim of this challenge is to write our own function called randomOddNumber() to generate a random odd number within a given range and a another function called randomEvenNumber() to generate a random even number. Both functions will take two parameters, the lower and higher values of the range.
Random Odd Number Functions
We will investigate three different algorithms to implement the randomOddNumber() function:
Here is the approach we will use:
To generate an odd number, let’s say between 0 and 100, we will first generate a random number between 0 and 49, then multiply this number by 2 (this will hence become an even number between 0 and 98) and finally we will add 1 to make it an odd number (between 1 and 99).
With this approach we are generating a random number between 1 and 100. We will repeat this process as long as the number generated is even (not odd). A number is even if the remainder of dividing this number by two is zero.
We will generate a random number, check if this number is odd or even by checking whether the remainder of dividing this number by two is zero (for an even number) or 1 (for an odd number). If the number is even, we will add 1 to this number to change it to an odd number.
Random Even Number Functions
Your task consists of adapting the above three functions to create three additional functions, this time to generate random even numbers using all three methods/programming constructs: sequencing, selection and iteration.
Extension Task: Random Prime Number Function
For this more complex extension task, you will need to write a function called randomPrimeNumber() to generate a random prime number within a given range. This function will take two parameters: the lower and higher values of the range.