Random

 Random



Uses of Random:

        Random is a library used in Python for making random choices. There is no installation for the random library since it is built-in to Python when you download it. Neat! Random can be used for all sorts of things, whether it's a game with dice, picking an item to run through an item shop in a video game, picking items from a list, picking a random number given as a parameter, etc. Random is very useful for many things and I bet we all thank it for being a thing.

Initialization and Examples:

        To use random, you will need to import it at the top of your file. All you need to do is type import random and you're all set and ready to use the library!


        Random is a pretty easy library to understand. It's for making all the random choices in your project. Like picking a random number that the user can then guess.

randint(a, b)

        The method randint() takes two parameters that are both integers. This method returns a random integer between the two parameters given, including the integers given. The first parameter given should be smaller than the second parameter, no floats. The image above will return either 5, 6, 7, 8, 9, or 10.

choice(sequence)

        The method choice() takes one parameter which is a sequence (list, set, tuple, etc.). This method returns a random item from the given sequence. The parameter has to be a sequence, either given as a variable or the value given as the parameter. The image above will return either apple, banana, orange, or mango.

choices(sequence, weight=[probability], k=num_of_items)

        The method choices() takes three parameters that are a sequence, the probability of each item appearing (keyword argument weight), and the number of items in the returned list. The choices() method returns a list with k items in it and the items in the given sequence multiple times based on the probability of each item appearing, as given in the weight argument. The image above will return something like this:

 ["apple", "apple", "apple", "apple", "banana", "apple", "apple", "apple", "apple", "apple", "apple", "apple", "apple", "apple", ]

    Use the knowledge you have learned today to complete many python projects whether for games or jobs or anything else. You can check out the other random methods here at https://www.w3schools.com/python/module_random.asp. Check out my other posts for more python tutorials. Leave a comment for any feedback!









Comments