Understanding the Random Module in Python

Understanding the Random Module in Python

Python’s Random Module: A Comprehensive Guide

  1. Generate a Random Integer (randint)
a = random.randrange(1, 7)
print(a)
# Output will be any number from 1 to 6
a = random.random()
print(a)
# Output: a float between 0 and 1
a = random.uniform(1, 3)
print(a)
# Output: a float between 1 and 3
l = [2, 5, 9, -5, 89, 12, 56]
a = random.choice(l)
print(a)
# Output: any number from list `l`
l = [2, 5, 9, -5, 89, 12, 56]
random.shuffle(l)
print(l)
# Output: a rearranged version of `l`

Real-World Example: Rock-Paper-Scissors Game

USERCOMPUTERRESULT
InputInputOutput
00Draw
01Computer win
02User win
10User win
11Draw
12Computer win
20Computer win
21User win
22Draw
administrator

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *