Python Random moduleThe Python Random module is a built-in module for generating random integers in Python. These numbers occur randomly and does not follow any rules or instructuctions. We can therefore use this module to generate random numbers, display a random item for a list or string, and so on. The random() FunctionThe random.random() function gives a float number that ranges from 0.0 to 1.0. There are no parameters required for this function. This method returns the second random floating-point value within [0.0 and 1] is returned. Code Output: 0.3232640977876686 The randint() FunctionThe random.randint() function generates a random integer from the range of numbers supplied. Code Output: 215 The randrange() FunctionThe random.randrange() function selects an item randomly from the given range defined by the start, the stop, and the step parameters. By default, the start is set to 0. Likewise, the step is set to 1 by default. Code Output: 4 9 The choice() FunctionThe random.choice() function selects an item from a non-empty series at random. In the given below program, we have defined a string, list and a set. And using the above choice() method, random element is selected. Code Output: M 765 54 The shuffle() FunctionThe random.shuffle() function shuffles the given list randomly. Code Output: [23, 43, 86, 65, 34, 23] [65, 23, 86, 23, 34, 43] Rock-Paper-Scissor Program using Random ModuleCode Output: This is Javatpoint's Rock-Paper-Scissors! Please Enter your choice: choice 1: Rock choice 2: Paper choice 3: Scissors Select any options from 1 - 3 : 1 Option choosed by Machine is: Rock Wow It's a tie! Want to Play again? ( yes / no ) yes This is Javatpoint's Rock-Paper-Scissors! Please Enter your choice: choice 1: Rock choice 2: Paper choice 3: Scissors Select any options from 1 - 3 : 2 Option choosed by Machine is: Scissors Congratulations!! You won! Want to Play again? ( yes / no ) no Thanks for playing Rock-Paper-Scissors! Various Functions of Random ModuleFollowing is the list of functions available in the random module.
ConclusionTo conclude, We learned about various methods that Python's random module provides us with for dealing with Integers, floating-point numbers, and other sequences like Lists, tuples, etc. We also looked at how the seed affects the pseudo - random number pattern. Next TopicPython statistics module |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India