Conditionals¶
Let us go through conditionals in Python. We typically use “if else” for conditionals. Let us perform a few tasks to understand how conditionals are developed.
Create a variable i with 5. Write a conditional to print whether i is even or odd.
i = 5
# Regular if else
if i % 2 == 0:
print("even")
else:
print("odd")
odd
# (cond) ? on_true : on_false
# on_true (cond) else on_false
# Ternary Operator (one liner)
print("even") if i % 2 == 0 else print("odd")
odd
Improvise it to check if i is 0 and print zero
i = int(input("Enter an integer: "))
Enter an integer: 10
if i == 0:
print(f"i is 0")
elif i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
10 is even
Object of type
None
is special object which represent nothing. At times we need to check againstNone
.
n = None
print('Not None') if n else print(n)
None
i = int(input("Enter an integer: "))
Enter an integer: 10
if i:
print('Not None')
else: print(n)
None
i = int(input("Enter an integer: "))
Enter an integer: 9
if not i % 2 == 0: print(f'{i} is odd')
9 is odd
We can also perform boolean operations such as boolean or and boolean and.
Task 1¶
Determine the category of the baby.
Print New Born or Infant till 6 months.
Print Toddler from 7 months to 18 months.
Print Grown up from 19 months to 144 months.
Print Youth from 145 months to 216 months
age = int(input('Enter age in months: '))
Enter age in months: 5
if age <= 6:
print('New Born or Infant')
elif age > 6 and age <= 18:
print('Toddler')
elif age > 18 and age <= 144:
print('Grown up')
elif age > 144 and age <= 216:
print('Youth')
else:
print('Adult')
New Born or Infant
Task 2¶
Check if the number is even or divisible by 3.
n = int(input('Enter integer: '))
Enter integer: 6
if n % 2 == 0 or n % 3 == 0:
print(f'Number {n} is even or divisible by 3')
Number 6 is even or divisible by 3
Task 3¶
Check if the number is even and divisible by 3
n = int(input('Enter integer: '))
Enter integer: 6
if n % 2 == 0 and n % 3 == 0:
print(f'Number {n} is even and divisible by 3')
elif n % 3 == 0:
print(f'Number {n} is divisible by 3 but not even')
elif n % 2 == 0:
print(f'Number {n} is even but not divisible by 3')
Number 6 is even and divisible by 3