November 2nd, 2005, 06:24 PM
How to print random strings
Im at the end of chapter 3 of "Python Programming For The Absolute Beginner, Michael Dawson " and he asks to make a fortune program that displays a fortune each time its ran, and to have 5 unique fortunes.
Whats confusing is that, he never discussed how to do this. The only thing he talked about was using random.randrange() and I tried that with text but it seems like its only for integers as it complains when I put text in the argument.
So how would I go about have 5 strings, and running a program that will randomly pick one of those to print?
I think he may have forgot to cover something?
November 2nd, 2005, 06:38 PM
Make a list that contains 5 strings.
Import the random library.
Use the random module's choice function.
To use it, check out the following:
This will print out a random element of the fortunes list.
from random import *
fortunes = ['text', 'text2', 'text3', 'text4', 'text5']
November 2nd, 2005, 06:49 PM
yea what the heck, the author didnt cover the list or the "choice" part. How dooes he expect us to do that challenge with only teaching random.randrange() ? Thanks, im going to email this dude.
November 2nd, 2005, 08:53 PM
I didn't get to read the tutorial myself. It's feasible that you may have perhaps missed something? Also, the method I showed you is just one way to do this, in my opinion it is the easiest and most effective way. However there are other ways.
November 2nd, 2005, 09:07 PM
This will work with random.randrange().
fortunes = ('first', 'second', 'third', 'fourth', 'fifth')
number = random.randrange(0, 5)
November 2nd, 2005, 10:37 PM
from os import system
# Not reinventing the wheel == priceless <img src="http://images.devshed.com/fds/smilies/smile.gif" border="0" alt="" title="Smilie" class="inlineimg" />
system( "/usr/bin/env fortune" )
Comments on this post
November 6th, 2005, 11:32 AM
If tuples and lists have not been covered yet, then use something like this:
number = random.randrange(1, 6)
if number == 1:
if number == 2:
if number == 3:
if number == 4:
if number == 5: