Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random fortune
#2
Just to give an idea: maybe use dictionary?

>>> fortunes = {'red': {1: 'be happy', 2: "don't worry"}, 
...            'blue': {3: 'monday', 4: 'tuesday'}}                                                                       
>>> color = 'red'                                                                                                       
>>> num = 2                                                                                                             
>>> fortunes[color][num]                    # works like charm                                                                                            
"don't worry"
>>> fortunes['purple'][1]                   # but throws an error if there is no such a key                                                                                           
/.../
KeyError: 'purple'
One can use try...except to handle non-existing keys (alternatively perform input validation):

try: 
    fortune = fortunes[color][num] 
    # do something with fortune 
except KeyError: 
    # handle situation of incorrect input                                                                           
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Random fortune - by jackthechampion - Feb-10-2020, 05:25 AM
RE: Random fortune - by perfringo - Feb-10-2020, 07:52 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020