Truthy & Falsy #
After we have understood boolean values and how to use if statements, let's try to copy the code below and run it to see the output:
num = 10
if num:
print(num)
We will see that the print(a) function is executed even though the value of a is not True. However, if we try to run the code below, we will see that the code under the condition is not executed:
num = 0
if num:
print("Hello World")
In Python, every value that is not a boolean value has this property. The values that are evaluated as True are called truthy, and the values that are evaluated as False are called falsy. In Python, almost every value is evaluated as True except for the following values:
NoneFalse
or numeric values equal to 0, such as:
- 0
- 0.0
or data structures with no values, such as:
[]- list with no data{}- dictionary with no data()- tuple with no dataset()- set with no data"",''- empty strings
We can check the truthiness or falsiness of a value by calling the bool function with the value you want to check:
print(bool(1)) # True
print(bool("")) # False
print(bool(None)) # False
print(bool([])) # False
print(bool(0)) # False
We can use this property to write if statements to control the flow of the program as we need. For example, we can write an if statement to do something based on whether the variable name is an empty string or not:
name = ""
if name:
print(f"Hello {name}")
else:
print("There is no name")
Exercise #
Write code for the function is_empty_string() to check if a string is empty.
Tests #
is_empty_string("")should returnTrueis_empty_string("Not Empty")should returnFalse
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules