Python booleans

In python, we represent boolean data with keywords True and False

we can evaluate any expression in python and get the boolean data. Let's solve some problems using boolean data.

Code examples

print(10 > 9)
# True
print(10 == 9)
# False
print(10 < 9)
# False

Above code will give boolean value based on the operation.

Evaluate Values and Variables

  • bool is a built-in function allows us to evaluate other data type values into boolean data type.
bool("Hello")
  • bool will return False for the below values
bool(None)
bool(False)
bool(0)
bool("")
bool(())
bool([])
bool({})
  • bool will return True for the below values
bool("awesome")
bool(123)
bool(["apple", "cherry", "banana"])

Check if given number is even or odd

If number divisible by 2 then it's a even number. Below program will find if the number is even or not.

num = 20
is_even = num % 2 == 0

if is_even:
    print("even")
else:
    print("odd")

Age classifier

Write program to take age and tell whether its infant or child or adult

age = int(input("Please enter your age:"))
if age <= 0:
    print('Invalid input')
elif age >= 1 and age <= 5:
    print('Infant')
elif age >= 6 and age <= 10:
    print('Child')
else:
    print('Adult')