Let's assume we have an array of various English words. Our goal is to extract a random word from this list and print it. Sounds simple, right? Let's get started.
Example:
Here's the code.
import random words = ['abacus', 'abandon', 'brain', 'brake', 'branch', 'crazy', 'cream', 'create', 'doctor', 'document', 'documentary'] random_word = random.choice(words) print(random_word) # Output: a random word like "document" or "crazy".
I am using VS Code (or Visual Studio Code) to test the above code. You can use any other editor.
Here's how it works.
First, I am importing the random module. Its a built-in module that you can use to generate random numbers. For example, to generate a random floating number I can use the "random" module with the "random()" method like this.
import random print(random.random()) # Output: some random number between 0.0 to 1.0
The "random" module has a collection of other methods. The one that I have used in the first example above, is the choice() method.
random_word = random.choice(words)
Syntax of choice() method
random.choice(sequence)
The "choice()" method returns a single random element (in our case a word) from a given list (an array). The method takes a parameter in form a sequence of elements (string or numbers). It takes a parameter called "sequence". The sequence can a list (like an array), a string or a sentence.
Here's another example using the "choice()" method. It returns a random character from a string.
import random str = "arun banik" print(random.choice(str)) # Output: A random character (like a or n).