For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
In Python, generating random numbers is a crucial task for many applications like simulations, gaming, and data analysis. A random number in Python is one that is generated without any predictable pattern, often used in games, cryptography, or statistical simulations.
The problem comes when you need to generate these numbers for a specific range or type of output. In this guide, we will explore how to generate random numbers in Python with examples, covering various techniques like using the random module and the use of seed values.
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
In Python, one of the simplest and most straightforward ways to generate a random number is by using the choice() function from the random module. This function allows you to select a random element from a sequence (such as a list or string) and can be a great tool when you want to simulate picking random items, including numbers, from a predefined set.
Here’s a basic example to generate a random number using choice():
# Import the choice function from the random module
import random
# Define a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use choice() to select a random number from the list
random_number = random.choice(numbers)
# Output the result
print(f"The random number selected from the list is: {random_number}")
Output:
The random number selected from the list is: 7
Explanation:
Importing the random module: First, we import the random module, which contains functions to generate random numbers in Python with example.
Defining the list: Next, we define a list of numbers. This list is where choice() will pick a random value from.
Using choice(): The choice() function is called with the list numbers as its argument. This function randomly picks one element from the list.
Printing the result: The result is printed out using a formatted string to show the random number selected from the list.
Why Use choice()?
The choice() function is particularly useful when you want to select a random item from a known set of values. It is an easy and efficient way to generate random values without having to manually specify a range or logic.
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
The randrange() function from the random module allows you to generate a random number from a specified range. This function provides more flexibility than choice() because you can define a starting point, an endpoint, and even a step size.
It's particularly useful when you need a random number from a specific range with optional intervals between numbers.
Here’s an example:
# Import the randrange function from the random module
import random
# Generate a random number between 1 and 10 (inclusive)
random_number = random.randrange(1, 11)
# Output the result
print(f"The random number generated between 1 and 10 is: {random_number}")
Output:
The random number generated between 1 and 10 is: 4
Explanation:
Importing the random module: We begin by importing the random module, which contains the randrange() function.
Using randrange(): The randrange() function is called with two arguments: the start (1) and the end (11). The second argument (11) is exclusive, meaning the generated number will be in the range 1 to 10.
Printing the result: Finally, we print the randomly generated number using a formatted string.
You can also specify the step size between numbers in the range. For example, if you want a random number between 1 and 10 but only choose odd numbers, you can use randrange() with a step of 2:
empty_set = set()
# Generate a random odd number between 1 and 10
random_odd_number = random.randrange(1, 11, 2)
# Output the result
print(f"The random odd number generated between 1 and 10 is: {random_odd_number}")
Output:
The random odd number generated between 1 and 10 is: 3
In this case, the randrange() function picks a random odd number between 1 and 10 because we specified a step size of 2.
Why Use randrange()?
The randrange() function is more flexible than choice() because it lets you specify the range and step size for the generated number. If you need a random number within a certain range but with specific intervals or without including the upper limit, randrange() is the way to go.
The seed() function in Python’s random module is used to initialize the random number generator. By setting a seed value, you ensure that the sequence of random numbers generated is reproducible.
This is particularly useful when you need to generate the same set of random numbers for testing or debugging purposes.
Here’s an example:
# Import the random module
import random
# Set the seed to a fixed value for reproducibility
random.seed(42)
# Generate a random number between 1 and 100
random_number = random.randint(1, 100)
# Output the result
print(f"The random number generated is: {random_number}")
Output:
The random number generated is: 81
Explanation:
Setting the Seed:
We set the seed for the random number generator with random.seed(42). The value 42 is just an arbitrary number. Setting the seed ensures that each time you run the program, the random number sequence will be the same.
Generating the Random Number:
The random.randint(1, 100) function generates a random integer between 1 and 100. Since we set the seed, this number will always be the same when the program runs.
Printing the Result:
We print the randomly generated number to the console.
Why Use seed() for Random Numbers?
The main advantage of using seed() is the ability to generate repeatable sequences of random numbers. This is helpful in scenarios like testing, debugging, or any case where you need consistent results from random functions.
Let’s look at another example using a different seed:
# Set a different seed
random.seed(99)
# Generate a random number between 1 and 100
random_number = random.randint(1, 100)
# Output the result
print(f"The random number generated with a different seed is: {random_number}")
Output:
The random number generated with a different seed is: 25
As you can see, changing the seed results in a different set of random numbers.
The shuffle() function in Python's random module is used to randomly reorder the elements in a list. This is useful when you want to create a random arrangement of items, such as shuffling a deck of cards or randomly ordering a list of elements.
Here’s an example:
# Import the random module
import random
# Define a list of items
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Shuffle the list randomly
random.shuffle(items)
# Output the shuffled list
print(f"The randomly shuffled list is: {items}")
Output:
The randomly shuffled list is: [7, 3, 9, 1, 4, 2, 8, 6, 10, 5]
Explanation:
Defining the List:
We define a list of integers from 1 to 10. You can use any type of list, such as strings or mixed data types.
Shuffling the List:
We use random.shuffle(items) to randomly rearrange the order of the elements in the list. Note that shuffle() works in-place, meaning it modifies the original list directly.
Printing the Result:
The shuffled list is printed to the console.
Why Use shuffle() for Random Ordering?
shuffle() is particularly useful when you need to randomly reorder elements in a list for various applications, such as:
In contrast to other random generation functions, shuffle() directly manipulates the order of elements in a list, making it ideal for scenarios where order matters.
You can also use shuffle() to randomize the order of other types of data, like strings or even more complex data structures.
Let’s look at another example, this time using a list of strings:
# Define a list of words
words = ["banana", "cherry", "apple", "papaya", "strawberry"]
# Shuffle the list randomly
random.shuffle(words)
# Output the shuffled list
print(f"The shuffled list of words is: {words}")
Output:
The shuffled list of words is: ['cherry', 'papaya', 'banana', 'apple', 'strawberry']
The shuffle() function is a simple yet powerful way to generate a random order for items in a list. It is especially useful when working with collections where order is important, such as games or randomized trials.
The uniform() function in Python’s random module is used to generate a random floating-point number between two specified values. This allows you to get a random float within a given range, which can be useful for simulations, games, and statistical operations.
Let’s look at an example:
# Import the random module
import random
# Define the range for generating random float
low = 1.5
high = 10.5
# Generate a random floating-point number between low and high
random_float = random.uniform(low, high)
# Output the random floating-point number
print(f"The random float between {low} and {high} is: {random_float}")
Output:
The random float between 1.5 and 10.5 is: 6.857569321345679
Explanation:
Define the Range:
We define two numbers, low and high, which represent the lower and upper bounds for the random floating-point number we want to generate.
Using uniform():
The random.uniform(low, high) function generates a random float between the two bounds (inclusive of the lower bound and exclusive of the upper bound).
Printing the Result:
We print the generated random float value to the console.
Why Use uniform() for Random Floats?
The uniform() function is great when you need a random float in a specific range. It is commonly used for:
Practical Example
Let’s say you are working with a game and need to randomly determine the speed of an object within a specific range.
You could use uniform() to generate random speed values:
# Randomly generate speed for an object
min_speed = 5.0 # Minimum speed in units per second
max_speed = 15.0 # Maximum speed in units per second
# Generate random speed
random_speed = random.uniform(min_speed, max_speed)
# Output the random speed
print(f"The random speed of the object is: {random_speed} units per second.")
Output:
The random speed of the object is: 12.834560948323712 units per second.
The uniform() function is especially useful when you need to simulate real-world data or deal with floating-point values that vary within a specified range.
The uniform() function in Python is used to generate random number in python by producing a floating-point number between two specified values. It’s useful for situations where you need a random float within a specific range, as shown in random number in python with example.
You can generate random number in python using the uniform() function. For example, random.uniform(1.5, 10.5) will give you a random float between 1.5 and 10.5. This is a practical method for generating random number in python with example within a specific range.
No, uniform() generates random floating-point numbers, not integers. To generate integers, you can use random.randint(). However, for random number in python with example, uniform() is a great choice when you need a floating-point result.
The uniform() function includes the lower bound, but random number in python with example results are not guaranteed to include the upper bound. The upper bound is exclusive in some contexts, but generate random number in python always returns a floating-point value between the given bounds.
Yes, uniform() is part of Python's random module, which is included in Python’s standard library. This makes it easy to generate random number in python without any external dependencies.
Yes, uniform() is specifically designed to generate random floating-point numbers, including decimal values. This helps in tasks that require random number in python with example where decimals are important.
Use random.uniform(low, high), where low is the starting value, and high is the ending value of the range. It allows you to generate random number in python and apply it to any floating-point range you desire.
Yes, uniform() can return negative values if the lower bound is negative. For example, random.uniform(-5, -1) will return a random negative float between -5 and -1, which is a valid random number in python with example.
uniform() generates floating-point numbers, while randint() generates integer values. To generate random number in python with decimals, use uniform(), and for integer values, use randint().
A real-world example of using uniform() is in simulation models where you need a random floating-point number, such as for simulating physical movements in a game, or random stock price changes, which require random number in python with example in a continuous range.
uniform() simplifies the process of generating random number in python by handling the complexity of generating floats within a specified range, ensuring efficient and accurate results.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.