This unit will focus on generating and using random numbers.
It is important to include the import random at the top of your code to be able to generate and use random numbers
Create brand new code in main to make a program that follows these instructions:
- Gets user input of two numbers.
- Extra challenge – Build in a check for the input, if the second number is lower than or the same as the first number then print an error message. Else continue to the next steps.
- Generates a random number between the two numbers input.
- Prints the random number generated.
Generating Random Numbers
Numbers are randomly generated within a range of numbers. To generate them, use:
random.randint(min,max)
The min is the lowest the random number can be, and the max is the highest the random number can be.
Random numbers can also be stored in variables, like this:
num = random.randint(1,5)
This means that num can be a random number between 1 and 5
Help! My Code Does Not Work!
When you run into errors in your code, check if:
- import random missing from the top of the program
- import random used every time a random number is generated (it only needs to be done once)
- spelling of ‘randint’
- max and min random values in brackets after ‘randint’
- comma between the max and min random values in brackets after ‘randint’