Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Magic 8 ball code not working?

import random

fortunes = [
  "No"
  "Yes"
  "Maybe"
  "Soon"
  "Probably not"
  "Perhaps"
  "Of Course"
  "Yeah!"
]

def game():
  choice_fortune = random.choice(fortunes)
while 1 > 0:
    user_input = input('Welcome to Magic 8 ball! ' "Ask a Question or type 'Quit' to quit. ")
    if user_input == 'Quit':
      break
    else:
      print(choice_fortune)

it shows this error: Traceback (most recent call last):
File "python.py", line 21, in <module>
print(choice_fortune)
NameError: name 'choice_fortune' is not defined

1 Answer

Hey Ruslan!

The problem here is with indentation. By not indenting the while block, it's beeing used outside of the function, while the choice_fortune variable is inside the function. So choice_fortune is a local variable, hence, can't be called outside the function. Try to fix your indentation and your code will work, it will not return the expected output though, because while 1 > 0 always evaluates to true, so it will print every item in the list. Here is how your code should look like:

import random

fortunes = [
  "No"
  "Yes"
  "Maybe"
  "Soon"
  "Probably not"
  "Perhaps"
  "Of Course"
  "Yeah!"
]

def game():
    choice_fortune = random.choice(fortunes)
    while 1 > 0:
        user_input = input('Welcome to Magic 8 ball! ' "Ask a Question or type 'Quit' to quit. ")
        if user_input == 'Quit':
          break
        else:
          print(choice_fortune)

game()

And here is how I would solve this:

import random

fortunes = [
  "No"
  "Yes"
  "Maybe"
  "Soon"
  "Probably not"
  "Perhaps"
  "Of Course"
  "Yeah!"
]

def game():
    choice_fortune = random.choice(fortunes)
    user_input = input('Welcome to Magic 8 ball! ' "Ask a Question or type 'Quit' to quit. ")
    if user_input == 'Quit':
        break
    else:
        print(choice_fortune)

game()