0

I have been reading about how to figure out if a string is empty or has value within Python and discovered Not If i done some reading and found out that Not will return true if a condition does not equal what the programmer expects it to this is used in a if statement like this if not how does this work with strings?

#!/usr/bin/python
Data = ""
if not Data:
    print 'Hello'
else:
    print 'Goodbye'

I expect the output to be Hello and wish to know how this works

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
Samatha
  • 5
  • 3
  • 2
    Objects in python have a notion of truthy-ness or falsey-ness. You can always check this by casting a given object to a `bool`: `bool([])`, `bool("")`, `bool(None)`, `bool(-1)`, etc. – JacobIRR Jul 23 '19 at 21:36
  • 2
    Possible duplicate of [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – G. Anderson Jul 23 '19 at 21:36
  • In Python, the empty string, `''` , is considered *"falsey"*. All other strings are *"truthy"*. This is why `"Hello"` is printed – Tomerikoo Jul 23 '19 at 21:37

1 Answers1

1

not object is essentially a shorthand for bool(object) == False. It's generally used to negate the truth value of object.

However, the truth value of object depends on object's type:

  • If object is a boolean, then True evaluates to True and False evaluates to False.
  • If object is an number (integer or floating-point), then 0 evaluates to False and any other value evaluates to True
  • If object is a string, then the empty string "" evaluates to False and any other value evaluates to True (this is your case at the moment)
  • If object is a collection (e.g. list or dict), then an empty collection ([] or {}) evaluates to False, and any other value evaluates to True.
  • If object is None, it evaluates to False. Barring the above cases, if object is not None, it will usually evaluate to True.

These are generally grouped into two categories of truthy and falsey values - a truthy value is anything that evaluates to True, whereas a falsey value is anything that evaluates to False.

Python programmers use if not object: as a shorthand to cover multiple of these at once. In general, if you're not sure, you should check more specifically. In your case:

data = ""
if data == "":
    print("Hello")
else:
    print("Goodbye")

or if you wanted to make sure that, say, data didn't end with the character p, you could do this:

data = "orange"
if not data.endswith(p):
    print("data does not end with p")
else:
    print("data ends with p")
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53