We have just learned about loops and input validation.
The last thing we need to know before being able to complete this project is how to generate random numbers.
In Python, you need to import the random module to use its random number functions. This is because Python likes to keep things simple and fast. So instead of loading everything at once, you only import what you need. This way, the program uses less memory and runs quicker.
Above we do the following:
Import the random module so that we can utilise its functionality
Print out the result of randint(a, b) which returns a random integer between a and b, both inclusive.
Notice that to use randint() we must prefix it with random because to help Python know which module the function is from.
Some times you might want to create a random decimal value. Here we can just use the random function which returns a float between 0 and 1.
Sometimes you might need this decimal number to be in a larger range than 0 to 1. You can either multiply the above or use the uniform function.
Complete the following requirements:
Import the random module.
Generate and print out a random integer between 30 and 50.
Generate two random floats between 0 and 1, add them together and print out the result.
Generate and print out a random float between 1 and 100 and round it to 2 decimal places.
Press Ctrl + F5 to run the program or open a terminal and type python lab4.py
You should now know how to genrate random integers and decimals in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 4 complete"
Press Commit to main
Press Push origin