Discover Python and Patterns (6): Random

Published January 03, 2020
Advertisement

In the previous post, the magic number is always the same. I propose now to introduce random numbers to change the magic number every time we launch the game. I also present imports and more on integers.

This post is part of the Discover Python and Patterns series

Library import

In the previous programs, I used print() and input() functions. They are part of the Python language, so nothing is required to use them. For other functions, like the ones for random number generation, we have to tell Python we want to use them.

For instance, to use random number functions, we need to import the random package at the beginning of our program:

import random

Note that if you type this in Spyder, you see a warning telling that you don’t use the random package. It is as expected, and it disappears once you use any function of this package.

The random package is part of the Python standard library, so it is always available when we ask for it. For other libraries, we have to install them in the current Python environment. The default Anaconda setup we installed in the first post already includes a lot of useful libraries. For more specific ones, like PyGame, I’ll show you later how to proceed.

Generate a random integer

We can generate a random integer in the following way:

magicNumber = random.randint(1,10)

We use the randint() function inside the random package. To tell that this function is in the random package, we have to type the name of the package before it, followed by a dot.

This line generates a random integer between 1 and 10 and puts it in magicNumber. If you replace the initialization in the program in the previous post with this one, the game now runs with a different magic number every time.

Import a specific function

If you don’t want to type the package name before the function, you can use the following syntax:

from random import randint
magicNumber = randint(1,10)

The first line indicates that we want to use the randint() function from the random package. Then, if the randint() function is found in the following lines (of the same file), Python assumes that it is the one of the random package. You can replace the import random with from random import randint at the beginning of the program if randint() is the only function you need.

Import all symbols

Continue reading on https://www.patternsgameprog.com/discover-python-and-patterns-6-random/

0 likes 1 comments

Comments

NekrosArts

I discover a repetetive pattern and it has nothing to do with programming XD

January 03, 2020 09:43 AM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement
Advertisement