
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Random numbers in Python
Explanation
Python has few functions for generating random numbers. They can be used in a lot of games, lotteries etc. where random numbers are required to get generate.
There are some functions which generates the random numbers −
choice()
This function can be used to generate one random number from a collection of numbers.
Example
print ("A random number from list : ",end="") print (random.choice([1, 4, 6, 100, 31]))
Output
A random number from list : 100
randrange(beg, end, step)
This function is used to generate number randomly but within a specific range in its arguments. This function takes 3 arguments, beginning number, last number and step.
Example
print ("A random number from range : ",end="") print (random.randrange(2, 10, 3))
Output
A random number from range : 8
random()
This function generates a float random number less than 1 and also greater than or equal to 0.
Example
print ("A random number between 0 to 1 : ", end="") print (random.random())
Output
A random number between 0 to 1 :0.42487645546
shuffle()
This function shuffle the list and randomly arrange them.
Example
list = [1, 3, 5, 10, 4] print (" list before shuffling : ", end="") for j in range(0, len(list)): print (list[j], end=" ") print("\r") random.shuffle(list) print ("list after shuffling : ", end="") for j in range(0, len(list)): print (list[j], end=" ") print("\r")
Output
list before shuffling : 1 3 5 10 4 list after shuffling : 3 10 1 4 5
uniform(a, b)
This function generates a floating point number randomly between the numbers mentioned in arguments. It takes two arguments, lower limit and upper limit.
Example
print (" random floating point number between 6 and 11 is : ",end="") print (random.uniform(6,11))
Output
The random floating point number between 6 and 11 is : 7.18036982355346
- Related Articles
- Generate pseudo-random numbers in Python
- How does Python generate random numbers?
- Python module to Generate secure random numbers
- How to generate non-repeating random numbers in Python?
- Random vs Secure Random numbers in Java
- Random Numbers in Java
- Random Numbers in C#
- How to use Python Numpy to generate Random Numbers?
- Generate Secure Random Numbers for Managing Secrets using Python
- Generating random numbers in C#
- Generating random numbers in Java
- Generate random numbers in Arduino
- Generate random numbers using C++11 random library
- Generate Random Integer Numbers in Java
- Excel random data: generate random numbers, texts, dates, times in Excel
