Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
Basic Boolean Values. Here we create two variables that store boolean values. True and False are special keywords in Python (notice the capital letters). These represent the two possible boolean states - there are no other options!
is_sunny = True
is_raining = False
print(is_sunny) # Output: True
print(is_raining) # Output: False
Example 2
Boolean from Comparison. When we compare age >= 18, Python evaluates this comparison and returns True because 18 is indeed greater than or equal to 18. The result gets stored in the is_adult variable. This shows how comparisons automatically create boolean values.
age = 18
is_adult = age >= 18
print(is_adult) # Output: True
Example 3
Boolean in Action. This shows how boolean values work with conditional statements. Since has_ticket is True, the code inside the if block will execute and print the message. If has_ticket were False, nothing would happen.
has_ticket = True
if has_ticket:
print("You can enter the movie theater!")
Example 4
Checking Boolean Type. This demonstrates that True and False belong to a special data type called 'bool' (short for boolean). Just like numbers are 'int' and text is 'str', boolean values have their own type.
answer = True
print(type(answer)) # Output: <class 'bool'>