-2

Im very new to Python and decided I would try some basics.

Why does this always evaluate to true? Typing in "False" as UserInput should evaluate False?

true_or_false=input("Is it true or false?")
if true_or_false:
    print("It's true")
if not true_or_false:
    print("Well,it is not true")

Using newest Python Version (3.smth)

jns
  • 99
  • 1
  • 1
  • 8

3 Answers3

1

The if condition evaluates the "truthiness" of the object passed to it:

if object:
    ...

Is the same as:

if bool(object):
    ...

You'll see any string of length greater than 0 has a truthiness value of True:

In [82]: bool('True')
Out[82]: True

In [83]: bool('False')
Out[83]: True

In essence, you'll need to change your if to:

if string == 'True':
    ...
elif string == 'False':

When using strings in comparisons, use the == operator unless you know what you're doing.

In addition, it is useful to know about the truthiness of some other python builtins:

In [84]: bool(None)
Out[84]: False

In [85]: bool({})
Out[85]: False

In [86]: bool([])
Out[86]: False

In [87]: bool(['a'])
Out[87]: True
cs95
  • 379,657
  • 97
  • 704
  • 746
1

true_or_false=input("Is it true or false?")

will give the variable true_or_false a string value.

if true_or_false

will test if that's an empty string or not.

The solution is to compare the string to a string value:

if true_or_false == 'True'

If you want to guard against errors with upper- and lowercase letters you can do like this:

if true_or_false.lower() == 'true'
klutt
  • 30,332
  • 17
  • 55
  • 95
0

Strings in python always evaluate to True unless they are empty. You need to check if the string equals to "True"

bakatrouble
  • 1,746
  • 13
  • 19