-2

I am currently creating this magic 8ball program that should tell whether the question the user input starts with ("Should, is, am ,what, can, why..etc"). It then randomly chooses through a list and prints a str suitable to the question.

However.. It doesn't use the if statements I've written and only prints "I dont quite know..".

I've tried remaking the program differently - no success I've tried using different methods to get the first word of a str - no success.

Here is my code:


import random, time, os

what = ("Your answer is mine!", "I don't quite know..", "Who knows...")

should = ("Yes, yes you should..", "Don't, please don't", "Okay...")

isvar = ("I believe so.", "No, not at all.....")

amvar = ("Yes, definetly", "No, not at all.....")

whyvar = ("Your answer is mine...", "I dont quite know..")

can = ("Yes, indeed", "No.... Idiot!", "Im not sure..")

question = input("The answer resides within your question, which is..?\n:")

first, *middle, last = question.split()

rwhat = random.choice(what)
rshoud = random.choice(should)
ris = random.choice(isvar)
ram = random.choice(amvar)
rwhy = random.choice(whyvar)
rcan = random.choice(can)

first = str(first)

if (first) == "what" or "What":
    print (rwhat)
    time.sleep(1)
    os.system('pause')

elif (first) == "should" or "Should":
    print (rshoud)
    time.sleep(1)
    os.system('pause')

elif (first) == "is" or "Is":
    print (ris)
    time.sleep(1)
    os.system('pause')

elif (first) == "am" or "Am":
    print (ram)
    time.sleep(1)
    os.system('pause')

elif (first) == "why" or "Why":
    print (rwhy)
    time.sleep(1)
    os.system('pause')

elif (first) == "can" or "Can":
    print (rcan)
    time.sleep(1)
    os.system('pause')

it should run correctly.

  • 2
    `first == "what" or "What"` doesn't do what you think it should. See [Operator Precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence). – meowgoesthedog May 17 '19 at 10:13
  • Instead of doing checks for all possible capitalisations, why not just use `String.lower()` method? – icwebndev May 17 '19 at 10:24

1 Answers1

1

It's because of how you structure your if statements.

if (first) == "what" or "What":

is evaluated as

if (first == "what") or ("What"):

And since "What" is a truthy value, the condition always evaluates to True becuase of the or statement. Consider using in with an iterable:

if first in ("what", "What"):

This will get you the desired results.

Edit:: Or as noted in the comments, if you're just checking for both capitalization methods, why not just use:

if first.lower() == "what":
miike3459
  • 1,431
  • 2
  • 16
  • 32