The single line of code below must be inserted ONCE at the beginning of your program.
The randint function from the random library allows for the creation of random integers (as Python doesn't have this functionality built in).
#EVERY SINGLE PROJECT YOU COMPLETE WILL START WITH THE LINE BELOW
#WE TYPE THIS ONCE ONLY AT THE BEGINNING OF ANY PYTHON PROGRAM FROM NOW ON
#THIS ALLOWS FOR THE CREATION OF RANDOM INTEGERS (WHOLE NUMBERS)
#NOTE THE FUNCTION WE ARE IMPORTING IS SPELT RANDINT (it stands for 'random integer')
from random import randint
The line of code below generates a random integer between 1 and 100 and assigns it to a variable called num1.
num1 = randint(1,100)
The line of code below generates a random integer between 1 and 300 and prints it to the screen.
print("A random number" + str(randint(1,300))
randint could be used for a coin toss which results in heads or tails.
from random import randint
headsOrTails = randint(1,2)
if headsOrTails == 1:
print("Your result is heads.")
elif headsOrTails == 2:
print("Your result is tails.")
randint could be used for a a roll of a dice which results in a number between 1 and 6.
from random import randint
diceRoll = randint(1,6)
print("You can now move " + str(diceRoll) + " spaces on the game board.")
The line of code below generates a random integer between two variables. This could be useful for a maths game.
#this example could be VERY, VERY useful when completing your project this trimester!
from random import randint
minumum = 10
maximum = 20
num1 = randint(minimum, maximum)
answer = num1 * num1
userAnswer = int(input("What is " + str(num1) + " squared?"))
The random function from the random library allows for the creation of random decimal (floating point) numbers between 0 and 1.
from random import random
print(random()) # Produces a random float/decimal: 0.0 <= x < 1.0
Output example: 0.37444887175646646
The randrange function from the random library allows for the creation of random integers to a maximum.
from random import randrange
print(randrange(10)) # Integer from 0 to 9 inclusive
Output example: 7
randrange can also be used to generate numbers that are even (using 2) or divisible by a certain number (eg 3, 7 etc).
print(randrange(0, 101, 2)) # Even integer from 0 to 100 inclusive
print(randrange(0, 101, 7)) # Integer divisible by 7 up to 100 inclusive
The line of code below generates a random integer between 1 and 300 and prints it to the screen.
from random import choice
print(choice(['win', 'lose', 'draw'])) # Single random element from a sequence
Output example: lose
Random Number Generation Video