Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 2, Topic 11
In Progress

Python: Random Numbers

Yasin Cakal 21 Oct 2021
Lesson Progress
0% Complete

In Python, we can generate a random number from a range by using the random module’s .randint() function. However, first we must import this module in order to make use of its functions. Following that, we’ll create a variable to hold the value that was generated randomly. Let’s take a look at an example:

# This imports the random mudule
import random

# Generates a random int that can be:
# 1, 2, 3, 4 or 5
number = random.randint(1,5)
print(number)

Output: (Can be anything 1 through 5)

3

Let’s take a closer look at the line of code that includes random.randint(1,5). randint() is a function that is part of the module random. Just like print() is also a function, but print() is a core function, therefore it does not need to be imported. randint() stands for random integer, and takes 2 integers inside the parenthesis. The two integers are the starting and ending point for the range of values that can be randomly generated. Remember, the randomly generated integers include the starting and ending values. Lastly, the probability for each integer in the range of values is equal. In our example, random.randint(1,5) can generate 1, 2, 3, 4 or 5 each with a 20% probability.

%d bloggers like this: