For working professionals
For fresh graduates
More
Python Tutorials - Elevate You…
1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Python List remove() Method
92. How to Add Elements in a List in Python
93. How to Reverse a List in Python?
94. Difference Between List and Tuple in Python
95. List Slicing in Python
96. Sort in Python
97. Merge Sort in Python
98. Selection Sort in Python
99. Sort Array in Python
100. Sort Dictionary by Value in Python
101. Datetime Python
102. Random Number in Python
Now Reading
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
106. Anagram Program in Python
107. Append in Python
108. Applications of Python
109. Armstrong Number in Python
110. Assert in Python
111. Binary Search in Python
112. Binary to Decimal in Python
113. Bool in Python
114. Calculator Program in Python
115. chr in Python
116. Control Flow Statements in Python
117. Convert String to Datetime Python
118. Count in python
119. Counter in Python
120. Data Visualization in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
124. Fibonacci Series in Python
125. Format in Python
126. GCD of Two Numbers in Python
127. How to Become a Python Developer
128. How to Run Python Program
129. In Which Year Was the Python Language Developed?
130. Indentation in Python
131. Index in Python
132. Interface in Python
133. Is Python Case Sensitive?
134. Isalpha in Python
135. Isinstance() in Python
136. Iterator in Python
137. Join in Python
138. Leap Year Program in Python
139. Lexicographical Order in Python
140. Literals in Python
141. Matplotlib
142. Matrix Multiplication in Python
143. Memory Management in Python
144. Modulus in Python
145. Mutable and Immutable in Python
146. Namespace and Scope in Python
147. OpenCV Python
148. Operator Overloading in Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
152. Pattern Program in Python
153. Perfect Number in Python
154. Permutation and Combination in Python
155. Prime Number Program in Python
156. Python Arrays
157. Python Automation Projects Ideas
158. Python Frameworks
159. Python Graphical User Interface GUI
160. Python IDE
161. Python input and output
162. Python Installation on Windows
163. Python Object-Oriented Programming
164. Python PIP
165. Python Seaborn
166. Python Slicing
167. type() function in Python
168. Queue in Python
169. Replace in Python
170. Reverse a Number in Python
171. Reverse a string in Python
172. Reverse String in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
178. Speech Recognition in Python
179. Split in Python
180. Square Root in Python
181. String Comparison in Python
182. String Formatting in Python
183. String Slicing in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
187. Sum of Digits of a Number in Python
188. Sum of n Natural Numbers in Python
189. Sum of Prime Numbers in Python
190. Switch Case in Python
191. Python Program to Transpose a Matrix
192. Type Casting in Python
193. What are Lists in Python?
194. Ways to Define a Block of Code
195. What is Pygame
196. Why Python is Interpreted Language?
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.