1

I am on day 4 of learning python so I apologize in advance if I am missing something very obvious.

The entire program is posted below. word = input() no matter what I type into the input prompt my tree function will not be called. However if I change: if word == 'Chris' or 'j': to if word == 'Chris': it seems to work.

def tree(pine):
    return 'Hello' + pine


def app():
    word = input()
    if word == 'Chris' or 'j':
        print('Welcome ' + word + ' it is nice today! ', end='')
        print('It is so sunny')
    else:
        print(tree('lplp'))



app()
blackjesus
  • 11
  • 1
  • 4
    Like this: ```if word == 'Chris' or word == 'j':``` – Red May 31 '20 at 23:27
  • You may want to format your string too: print(f'Welcome {word} it is nice today!') – Red May 31 '20 at 23:29
  • `if word in {'Chris', 'j'}:` – gilch May 31 '20 at 23:30
  • Also, I'm not 100% sure on this, but the reason your code is always true is because when you perform `if variable_name:` statements, you're asking Python if said variable is not None nor False. In this case the string 'j' is always not-None non-False, so your statement will always evaluate to True, and thus the `else` statement will never run – Juan C May 31 '20 at 23:31
  • @JuanC not exactly, every data type has its own python `bool` quirk. in the case of strings, any non empty string is evaluated as `True` – notacorn May 31 '20 at 23:36
  • Nice! I'm clearer now – Juan C May 31 '20 at 23:36

1 Answers1

2

The problem lies with

    if word == 'Chris' or 'j':

If we break down this statement, you're evaluating two conditions:

  1. word == 'Chris'
  2. 'j'

So Python is a funny language because pretty much any kind of object can be evaluated as a boolean. This means when you check if 'j', that actually comes out as True instead of some sort of error because Python does a lot of stuff behind the scenes.

To fix the issue you just want to make sure you're checking that word == "j".

Just to get you started, for example, here are some common python boolean evals:

>>> bool("")
False
>>> bool("j")
True
>>> bool(0)
False
>>> bool(69)
True
>>> bool([])
False
>>> bool(["hello", "world"])
True
>>> class Foo:

    def __init__(self):
        self.x = "y"


>>> bool(Foo())
True
>>> bool(None)
False
notacorn
  • 3,526
  • 4
  • 30
  • 60