to check whether x is True or False:
Copybool("")
> False
bool("x")
> True
for details on the semantics of is and == see this question
to check whether x is True or False:
Copybool("")
> False
bool("x")
> True
for details on the semantics of is and == see this question
Am I supposed to conclude that x is neither True nor False?
That's right. x is neither True nor False, it is "". The differences start with the type:
Copy>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool
Python is a highly object oriented language. Hence, strings are objects. The nice thing with python is that they can have a boolean representation for if x: print("yes"), e. g.. For strings this representation is len(x)!=0.
Videos
What's the most pythonic way of checking if variable is None or empty string ""?
empty string returns True upon checking if its contained in a non empty string
Why does my empty dictionary not evaluate to false?
.Empty string comprehension?
I'm trying to constantly check against any of those values but I don't want to keep repeating myself in code.
if variable is None or variable == "": do stuff
What are my options? Can I create somehow a class and check against that class?
if variable is MyNewClass: do stuff
How would I write such a class?
Thanks!
This code is meant to count all the words that have the expression "di" but with the text "imagina." the final answer is 1.
texto = 'imagina.'
cl = 0
flag_di = False
answer = 0
previous = ''
for car in texto:
if car != ' ' and car != '.':
cl += 1
if car in 'iI' and previous in 'dD':
flag_di = True
previous = car
else:
if car == ' ' or car == '.':
if flag_di:
answer += 1
cl = 0
flag_di = False
previous = ''
print(answer)dict_a = {}
print(dict_a)
print(dict_a == False)
print(bool(dict_a) == False)Why do we need the bool function to check whether a sequence is empty not not? I keep thinking if a list or dictionary is empty it automatically evaluates to none. So why do we need to explicitly check the boolean of an object?