Reputation: 5
In the book "Python for the absolute beginner" by Michael Dawson, in the chapter on Lists and Dictionaries I have learned a great deal and am trying to make a new program as practice using the old Magic 8-Ball as my inspiration. Below is the code I have come up with so far.
It works up to a point...the random generated number gets generated but the elif doesn't seem to work. I know there are better ways and simpler ways, but I am doing this to reinforce my understanding of dictionaries.
I have put several print statements in to see if I was getting a number selected and the else statement is if all goes bad. As the code stands now all I get is the number printed and the else produces "Does not compute. Exit works fine. I have also confirmed the dictionary is fine using the commented out print "ball" statement.
So my issue is why does the elif statement seem to not process the random number generated. Whom ever answers has my heartfelt thanks and appreciation.
# Import the modules
import sys
import random
# define magic 8-ball dictionary
ball = {"1" : "It is certain.",
"2" : "Outlook is good.",
"3" : "You may rely on it.",
"4" : "Ask again later.",
"5" : "Concentrate and ask again.",
"6" : "Reply is hazy, try again later.",
"7" : "My reply is no.",
"8" : "My sources say no"}
# for items in ball.items():
# print(items)
ans = True
while ans:
question = input("Ask the Magic 8 Ball a question: (press enter to quit) ")
answer = random.randint(1,8)
print(answer)
if question == "":
sys.exit()
elif answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
Upvotes: 0
Views: 688
Reputation: 60024
random.randint()
returns an integer. Your dictionary's keys are all strings. Thus, when you do answer in ball
, it will always be False
, because "1" != 1
What you can do is either make all the keys integers (remove the quotation marks), or make answer
a string by doing:
answer = str(random.randint(1,8))
Note that you shouldn't be using an elif
here. If your input is nothing, both your if
and elif
will be True, and most of the time you don't want this. Instead, change your elif/else
to just an if/else
:
if question == "":
sys.exit()
if answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
One final thing. answer
will always be in ball
, because you dynamically created the dictionary. Here, you can use dict.get()
. Eg:
if not question: # You can do this instead
sys.exit()
print(ball.get(answer))
Upvotes: 3
Reputation: 239693
You are looking up on the dictionary with a number whereas the keys are strings in the dict. So, you have to convert the number to string with str
.
Change
answer = random.randint(1,8)
to
answer = str(random.randint(1,8))
Upvotes: 1
Reputation: 794
The string "1"
is not the int 1
. So answer
is actually not in ball
.
Try converting it like answer = str(random.randint(1,8))
Upvotes: 1