hi im new to python and programming, and I have just learned loop and nesting statements.
I dont understand how to create functions and all that.

could anyone come with some good suggestions to make my crappy script better?

here is my script:

print 'choose option'
print 'a) fortune telling'
print 'b) quit'
while True:
    option=raw_input('enter option: ')
    if option == 'a':break
    if option == 'quit':quit()
while True:
    fortune=raw_input('enter a number from 1-3')
    if fortune == '1':
        print 'you will have a great life,\nbut you might get in trouble with the law'
    elif fortune == '2':
        print 'you will marry a wife that wants to kill you,\nand she was a guy'
    elif fortune == '3':
        print 'you will live a peacefull life with no trouble'
    elif fortune == 'b':quit()
        print 'thats cant be right!'
5 Years
Discussion Span
Last Post by griswolf

You probably want a script that looks more like this:

# do any initialization
while True:
  # prompt for user choice
  # clean up the choice: at least one non-white character, lower cased, 
  # if 'q': break
  # if something legal, look up the appropriate fortune (but see 'get' below)
  # otherwise, remind what is legal and continue

functions are very easy. You should work through the tutorial

I would get the fortunes from a dictionary like this:

fortune_dict = {
  '1': 'You will have an interesting life!',
  '2': 'You will have a VERY interesting life!'
  '3': 'You will have a boring life.'

Then I'd use get(user_choice, "You are very bad at following instructions") to extract the fortune from the dictionary.


so instead of writing print and all that, I would get the "fortunes" from a dictionary?


Since I'm a long time *n*x guy, I know of a tool called "fortune" that works a little different from what you're writing: When you call it, you get back a random fortune rather than the one you ask. For instance load this page, then reload it... (the font is kinda small)

So if I were writing your code, I'd probably encapsulate 'get a fortune' in a function, and then call the function... and I'd probably store the fortunes in a file, and use a random number to decide which fortune to produce. That is probably a little too advanced for you, so in your case, I'd just wrap a function around the dictionary I showed you: Pass in the index/key that the user chose and return the appropriate fortune. Your main loop would then look like this

while True:
  # get user input, clean it and break if 'q'
  fortune = get_fortune(user_input)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.