Python boolean

PythonprovideboolType, can have two values:TruewithFalse(capital)

done = False
done = True

Boolean for conditional control structures (e.g.ifstatement:

done = True

if done: # run some code here else: # run some other code

When evaluating the valueTrueorFalseIf the value is notboolDepending on the type to be checked, we have some rules:

  • Numbers are alwaysTrueUnless number0
  • The string isFalseOnly when empty
  • List, tuple, set, dictionary areFalseOnly when empty

You can check whether the value is a boolean in the following ways:

done = True
type(done) == bool #True

Or useisinstance(), Pass 2 parameters: variables andboolclass:

done = True
isinstance(done, bool) #True

globalany()The function is also very useful when using boolean values, because it returnsTrueIf any value of the iterable (e.g. list) passed as a parameter isTrue:

book_1_read = True
book_2_read = False

read_any_book = any([book_1_read, book_2_read])

globalall()Same function, but returnsTrueIf all the values passed to it areTrue:

ingredients_purchased = True
meal_cooked = False

ready_to_serve = all([ingredients_purchased, meal_cooked])

More python tutorials: