Python3 – Random Module

RockPaperScissor Game in Python

Randomization module in python

In the previous lesson, we have learned conditional statements and Logical operators on python.  I hope, you learned everything. Today we are going to learn about Randomization and listing in python. So head over this lesson.

In this lesson, we are going to learn about random modules. Before we start the lesson we have to talk about games. Everyone knows games. Every game we play against the computer. Such as Tetris, Chess, and many more. In the Tetris game, Computer sends the shapes randomly in a predictable way. We wonder that How the computer play against us. Today’s lesson will be the answer to this question. The game developers use this random module.

This Python random module using “Mersenne Twister” as a default PRNG. PRNG means a pseudo-random number generator. Not only Python but also MATLAB, Microsoft Excel, Ruby, PHP, and many still using this algorithm as a default pseudo-random number generator.

Here we don’t want to learn about MT PRNG just we need a python random module. So how can we implement to generate the random number? Before generating a random number we have to import the random module in our code.

In the random module, there are so many methods available to return the random integer, random float, random choice, etc. Here we take random integers within our given range of numbers. And later we use a choice generator in a random module. To do generate a random integer number we use the “randint()” method. To create the random number we have access to this method through the above module. and we have to just set the range in this method.

Just check this module using print function to how it is work.

import random
random_integer = random.randint(5,20)
print("A Random Number between 5 to 20 :", random_integer)

This is the way explain how we use it. Check the result yourself.

We just make coin flipping game to get who win the toss for your better understanding in random module.

# Import random module into our program 
import random

# Getting input from user
coin = int(input("1 – Head\n2 – Tail\nEnter the Side Number : ")

# Generate random integer using randint method
rand_number = random.randint(1,2)

# Conditional Statements
if rand_number == coin:
	print("You have won the toss.")
else:
	print("You loss.")

I hope this is enough to understand about randomization. Want more about random module ,Head over to python documentaion.

List in Python

let’s move to the list in python. In most of our previous lesson, we stored a single data in an individual variable. But we allocated a single variable to store the value of the months in our Age Calculator program. So what do you think about the differences between the above cases?

Let’s take a real-life example, there is two ticket counter in a cinema theatre. In the first counter, there is a clean queue. Second counter there are a bunch of people without queue. That is the difference between the list and the variable in our coding.

In the list we can use set of data that should be in a same data types. We can’t store different type of data. This list element saved within open & close square bracket and list items should separated by comma. And Element in the list access by integer number that start from zero. So if we want to access the data in the list, place the position number of data within open and closed square brackets followed name of variable.

For Example:

month = [January, February, March, April, May, June, July, August, September, October, November, December]
print (month[0])
output:
January

What is happen if print the position number 12.

month = [January, February, March, April, May, June, July, August, September, October, November, December]
print (month[0])

The output will be the below error.

 index error: list index out of range

So be care from making this error. If more elements available in the list , You can use len function, can count the number of elements in the list.

print(len(month))

In addition, there are some important methods available in the list to make our work simpler.

# We can add one elements in last of list element.
month.append(element ) 

# We can extend the list by adding this new elements in the last of list.
month.extend(element1, element2, element3, ……..)

# We can insert an element to given position.
month.insert(position, element) 

# We can remove the mentioned element from list. Make sure that element found in the list. Otherwise it make “value # error.”
month.remove(element) 

# We can remove all elements from list.
month.clear() 

# It will return that element appear in the list.
month.count(element) 

Let’s upgrade our above coin flipping game using this list method.

# Import random module
import random

# Getting user input
user = input("Enter the Head or Tail : ")

# Convert user input to lower case letter
user = user.lower()

# Store head and tail value using list
coin = ["head", "tail"]

# Generat random number
rand_number = random.randint(0,1)

# Condtional statements to print the value
if user == coin[rand_number]:
	print("You have won the toss.")
else:
	print("You loss.")

In above program we use lower method to convert all letter into lower case. If not the user enter lower case letter, it doesn’t match with our list value.Because python is a case sensitivable language. Here sometime if we have a lots of data in the list, we can reduce bunch of error by using choice method in randomization. So code will be like here.

# Import random module
import random

# Getting user input
user = input("Enter the Head or Tail : ")

# Convert user input to lower case letter
user = user.lower()

# Store head and tail value using list
coin = ["head", "tail"]

# Generate random choice
rand_choice = random.choice(coin)

# Condtional statements to print the value
if user == rand_choice:
	print("You have won the toss.")
else:
	print("You loss.")

So everything we learned to do our today python game. So let’s start our RockPaperScissor game.

First of all, we import the random module to access random methods. And ask the user to input the value and save it the variable. Here is the challenge, if not the user enters the value in the lower case it doesn’t match our choice. So let’s convert them into lower case.

# Import the random module to our game
import random

# Getting user input 
user = input("What do you want to select from Paper | Rock | Scissor ? ")

# Convert all user input into lower case
user = user.lower()

# Create a list that contain the values. And let the computer make choice.
Choices = ["rock","paper","scissor"]
Comp = random.choice(choices)

# Let check the choice using if/elif/else conditions
if user == comp:
    print("It's a tie!")
elif user == "rock": 
    if comp == "scissors": 
       print("You win!") 
    else:
       print("Computer wins!") 
elif user == "paper":
    if comp == "rock": 
       print("You win!") 
    else: 
       print("Computer wins!") 
elif user == "scissors": 
    if comp == "paper": 
       print("You win!") 
    else: 
       print("Computer wins!") 
else: 
   print("Error Found....")

So let’s meet on another lecture.

Leave a Comment