0% found this document useful (0 votes)
57 views1 page

Python Random Module Functions Explained

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views1 page

Python Random Module Functions Explained

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

One interesting function from the random module is randint().

This
function takes two integer arguments and returns a randomly selected inte-
ger between (and including) those numbers.
Here’s how to generate a random number between 1 and 6:

>>> from random import randint


>>> randint(1, 6)
3

Another useful function is choice(). This function takes in a list or tuple


and returns a randomly chosen element:

>>> from random import choice


>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> first_up = choice(players)
>>> first_up
'florence'

The random module shouldn’t be used when building security-related


applications, but it works well for many fun and interesting projects.

NOTE You can also download modules from external sources. You’ll see a number of these
examples in Part II, where we’ll need external modules to complete each project.

TRY IT YOURSELF

9-13. Dice: Make a class Die with one attribute called sides, which has a
default value of 6. Write a method called roll_die() that prints a random num-
ber between 1 and the number of sides the die has. Make a 6-sided die and
roll it 10 times.
Make a 10-sided die and a 20-sided die. Roll each die 10 times.
9-14. Lottery: Make a list or tuple containing a series of 10 numbers and 5 letters.
Randomly select 4 numbers or letters from the list and print a message saying that
any ticket matching these 4 numbers or letters wins a prize.
9-15. Lottery Analysis: You can use a loop to see how hard it might be to win
the kind of lottery you just modeled. Make a list or tuple called my_ticket. Write
a loop that keeps pulling numbers until your ticket wins. Print a message report-
ing how many times the loop had to run to give you a winning ticket.
9-16. Python Module of the Week: One excellent resource for exploring the
Python standard library is a site called Python Module of the Week. Go to
[Link] and look at the table of contents. Find a module that looks
interesting to you and read about it, perhaps starting with the random module.

180 Chapter 9

You might also like