There is a built-in module in Python that lets you perform random actions.
I’ll be showing you the two most common and important things you can do with this module, as well as some example code!
Contents
Importing the Module
First, to access the module, just type in this line at the start of your program-
import random
Generating a Random Number
The randint() function gives you a random number within the range.
num = random.randint(0,10)
In this code, the computer will generate a random whole number between 0 and 10. It’s inclusive, which means 0 and 10 also have a chance to get selected.
Example: Number Guessing Game
This is how you can code a Number Guessing Game! It’s pretty easy. We use the randint() function from above to do this, and a combination of a while loop and an if statement.
This program generates a random number between 1 to 10, and asks the user to guess a number within that range. It’ll keep asking until the user guesses correctly.
import random
correct = False
answer_comp = random.randint(1,10)
while correct == False:
answer_user = int(input("Guess a number between 1 to 10: "))
if answer_user == answer_comp:
correct = True
print("Correct. You guessed it!")
else:
print("Wrong. Try again")
At the start of our program, we import the random module. Then, on line 3, we set a flag to False. Line 5 generates a random number between 1 to 10. This is the number the user needs to guess.
There is a while loop on line 7 that keeps the code going, as long as the user’s guess is incorrect. Then, we proceed to ask the user for their guess.
Then, the rest of the code is an if statement that checks if the user guessed correctly.
Choosing a Random Value from a List
The choice() function chooses a random value from a set list.
fruits = ["apple","banana","orange"]
chosen_fruit = random.choice(fruits)
In this example, the computer will choose either apple, banana, or orange from the list.
Example: Coin Flip Game
This is how to code a Coin Flip Game! It requires the choice() function, as well as two if statements.
So, the computer first chooses heads or tails, then lets to user make their choice. At the end, it displays if it was heads or tails.
import random
coin = ["heads","tails"]
coin_face = random.choice(coin)
guess = input("Heads or tails?: ").lower()
if guess == coin_face:
print("You win!")
else:
print("You lose!")
if coin_face == "heads":
print("It was heads")
else:
print("It was tails")
As always, we import the random module first. Then, we make a list containing heads or tails. Line 5 selects either heads or tails, and line 6 asks the user.
Then, there are two if statements. The first checks if the user’s choice is the same as the computer, and displays a win or lose message. The second reveals if it was heads or tails.
Conclusion
That’s two of the main things in the random module! I hope this guide helped.
