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.
In [1]:
i = 5
In [2]:
# Regular if else
if i % 2 == 0:
print("even")
else:
print("odd")
odd
In [3]:
# (cond) ? on_true : on_false
In [4]:
# on_true (cond) else on_false
In [5]:
# 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
In [7]:
i = int(input("Enter an integer: "))
In [8]:
if i == 0:
print(f"i is 0")
elif i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
45 is odd
- Object of type
None
is special object which represent nothing. At times we need to check againstNone
.
In [9]:
n = None
print('Not None') if n else print(n)
None
In [10]:
i = int(input("Enter an integer: "))
In [11]:
if i:
print('Not None')
else: print(n)
Not None
In [13]:
i = int(input("Enter an integer: "))
In [14]:
if not i % 2 == 0: print(f'{i} is odd')
47 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
In [15]:
age = int(input('Enter age in months: '))
In [16]:
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')
Adult
Task 2¶
Check if the number is even or divisible by 3.
In [17]:
n = int(input('Enter integer: '))
In [18]:
if n % 2 == 0 or n % 3 == 0:
print(f'Number {n} is even or divisible by 3')
Number 18 is even or divisible by 3
Task 3¶
Check if the number is even and divisible by 3
In [19]:
n = int(input('Enter integer: '))
In [20]:
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 86 is even but not divisible by 3