# How to get a random number in Python

## Introduction

In this blog post, we'll learn how to generate random numbers in Python. Generating random numbers is a common task in programming. From creating passwords to simulating experiments or games, random numbers play an essential role in various applications.

We'll begin by understanding what random numbers are and then explore different ways to generate them in Python. We'll also look at some practical examples to demonstrate the use of random numbers in real-life scenarios.

As a beginner-friendly guide, we'll make sure to avoid jargons or explain them if necessary. Let's get started!

## What are random numbers?

Random numbers are numbers that are chosen by chance. In other words, there's no pattern or predictable sequence in a series of random numbers. They can be any number within a specific range, and every number has an equal chance of being picked.

Think of it like rolling a dice; each time you roll, you have an equal chance of getting any number between 1 and 6. This is an example of a random event, and the outcome of a dice roll can be thought of as a random number.

However, it's important to note that computers cannot generate truly random numbers. Instead, they generate pseudo-random numbers, which are numbers that appear random but are generated using deterministic processes. For our purposes, these numbers are still random enough.

## Generating random numbers in Python

Python has a built-in module called `random` that provides various functions to generate random numbers. Before using any of the functions, we need to import the module:

``````import random
``````

Now that we have the `random` module imported, let's explore some of its functions to generate random numbers.

### random.randint()

The `randint()` function generates a random integer within a specified range. It takes two arguments: the lower and upper bounds of the range. Both bounds are inclusive, meaning they can be chosen as the random number.

Here's an example of how to generate a random number between 1 and 6, simulating a dice roll:

``````import random

dice_roll = random.randint(1, 6)
print("You rolled a", dice_roll)
``````

This code will output a random number between 1 and 6 each time you run it.

### random.random()

The `random()` function generates a random float between 0 (inclusive) and 1 (exclusive). This can be useful when you need a random fraction or percentage.

Here's an example of how to generate a random float between 0 and 1:

``````import random

random_float = random.random()
print("Random float:", random_float)
``````

This code will output a random float like `0.34849584923` each time you run it.

### random.uniform()

The `uniform()` function generates a random float within a specified range. It takes two arguments: the lower and upper bounds of the range. The lower bound is inclusive, while the upper bound is exclusive.

Here's an example of how to generate a random float between 1 and 10:

``````import random

random_float = random.uniform(1, 10)
print("Random float between 1 and 10:", random_float)
``````

This code will output a random float like `4.8934857384` each time you run it.

### random.choice()

The `choice()` function picks a random element from a sequence, such as a list or a tuple. This can be useful when you need to select a random item from a collection.

Here's an example of how to pick a random item from a list of fruits:

``````import random

fruits = ["apple", "banana", "cherry", "orange", "grape"]
random_fruit = random.choice(fruits)
print("Randomly selected fruit:", random_fruit)
``````

This code will output a random fruit like `cherry` each time you run it.

### random.sample()

The `sample()` function selects a random sample of elements from a sequence. It takes two arguments: the sequence and the sample size. The function returns a new list containing the randomly selected elements.

Here's an example of how to pick a random sample of 3 items from a list of numbers:

``````import random

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_sample = random.sample(numbers, 3)
print("Random sample of 3 numbers:", random_sample)
``````

This code will output a random sample like `[4, 7, 2]` each time you run it.

## Practical examples of using random numbers

Now that we know how to generate random numbers in Python let's explore some practical examples to demonstrate their use in real-life scenarios.

### Example 1: Simulating a coin flip

A coin flip is a random event with two possible outcomes: heads or tails. We can simulate this using the `choice()` function by choosing a random element from a list containing the two possible outcomes.

``````import random

def coin_flip():
return random.choice(outcomes)

print("The coin landed on", coin_flip())
``````

This code will output either `The coin landed on heads` or `The coin landed on tails` each time you run it.

### Example 2: Generating a random password

We can use the `randint()` function to create a random password with a specific length and a mix of uppercase letters, lowercase letters, and digits.

``````import random
import string

characters = string.ascii_letters + string.digits

for _ in range(length):
random_character = random.choice(characters)

``````

This code will output a random password like `a8Fj4kD9b2` each time you run it.

### Example 3: Shuffling a deck of cards

We can use the `sample()` function to shuffle a deck of cards by selecting a random sample with the same size as the original deck.

``````import random

def create_deck():
suits = ["hearts", "diamonds", "clubs", "spades"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

deck = []
for suit in suits:
for rank in ranks:
card = rank + " of " + suit
deck.append(card)

return deck

def shuffle_deck(deck):
return random.sample(deck, len(deck))

deck = create_deck()
shuffled_deck = shuffle_deck(deck)

print("Original deck:", deck)
print("Shuffled deck:", shuffled_deck)
``````

This code will output the original deck and the shuffled deck, showing that the order of the cards has been randomized.

## Conclusion

In this blog post, we learned about random numbers and how to generate them in Python using the built-in `random` module. We explored various functions like `randint()`, `random()`, `uniform()`, `choice()`, and `sample()` to generate random integers, floats, and selections from sequences.

We also looked at practical examples of using random numbers, such as simulating a coin flip, generating a random password, and shuffling a deck of cards.

Remember that the `random` module generates pseudo-random numbers, which are not truly random but are random enough for most applications. If you need cryptographically secure random numbers, consider using the `secrets` module in Python.

Now that you know how to generate random numbers in Python, you can apply this knowledge to various applications and bring more unpredictability to your programs. Happy coding!

## Learn to code in our 100% online programs

Altcademy coding bootcamp offers beginner-friendly, online programs designed by industry experts to help you become a coder. 85%+ of Altcademy alumni are hired within 6 months after graduation. See how we teach, or click on one of the following programs to find out more.