Help with boolean operator on Magic 8-Ball

https://www.codecademy.com/courses/learn-python-3/projects/python-magic-8-ball

I am having trouble understanding the logic of my if statement.

import random

rn = random.randint(1,9)
name = ""
question = ""
answer = ""



if rn == 1:
  answer += "Yes - definitely."
elif rn == 2:
  answer +="It is decidedly so."
elif rn == 3:
  answer += "Without a doubt."
elif rn == 4:
  answer +="Reply hazy, try again."
elif rn == 5:
  answer += "Ask again later."
elif rn == 6:
  answer +="Better not tell you now."
elif rn == 7:
  answer += "My sources say no."
elif rn == 8:
  answer += "Outlook not so good."
elif rn == 9:
  answer += "Very doubtful."
else:
  answer += "Error"

if name and question == "":
    print("Please type in name and question.")
else:
   print(name + " asks: " + question)

print("Magic 8-Ball's answer:  " + answer)

Because the name and question variable are empty strings, the second if statement is true so I am expecting the if statement to run. However I get this as the output

asks:
Magic 8-Ball's answer: rn

When the name variable is a filled string, the output is this

Please type in name and question.
Magic 8-Ball's answer: rn

When the question variable is a filled string, the output is

asks: question
Magic 8-Ball's answer: rn

Can someone help me understand and point me in the right direction please?

This is not testing the values the way you think. It is testing whether name is a non-empty string.

1 Like

I am sorry, I still don’t understand. I removed
and question
from the statement so
if name == "":
is by itself and it runs as expected. Why would it test for a non-empty string when the
and question
condition is present?

name is an expression that if a non-empty string or non-zero will be truthy. It is not evaluated against the empty string like question is.

if name == "" and question == ""

Now both are evaluated against the empty string.

:man_facepalming:t3:
Thank you, I understand now.

1 Like