Lecture # 9 - Conditionals and Boolean Data Type
Boolean Data Type (bool):
In Python, the boolean data type represents two possible values: True
and False
. Booleans are used in expressions and conditional statements to evaluate conditions and make decisions. The boolean data type is essential for controlling the flow of a program and implementing logic.
Checking Data Type:
x = 5
y = 10
a = (x == y) # 5 == 10 -> False
b = (x < y) # 5 < 10 -> True
print(type(a))
print(type(b))
Output:
Conditionals:
Conditionals are the expressions that evaluate to either true or false.
if Statement:
In Python, the if
statement is used for conditional execution. It allows you to execute a block of code if a certain condition is true.
Syntax:
if condition:
#Code block to be execued if the condition is true
Example:
date = 23
if date >= 23:
print("You'll have to pay your fee with late fee charges.")
Output:
if-else Statement:
if-else
statement in Python allows you to execute one block of code if a condition is true and another block of code if the condition is false.
Syntax:
if condition:
# Code block to be executed if condition is True
else:
# Code block to be executed if condition is False
Example:
name = "Abdullah"
if name == "Ali":
print("This is Ali's Computer.")
else:
print("You're not owner of this Computer.")
Output:
if-elif-else Statement:
The if-elif-else
statement in Python allows you to execute different blocks of code based on multiple conditions. It's useful when you have multiple conditions to check.
Syntax:
if condition1:
# Code block to be executed if condition1 is True
elif condition2:
# Code block to be executed if condition1 is False and condition2 is True
elif condition3:
# Code block to be executed if condition1 and condition2 are False and condition3 is True
...
else:
# Code block to be executed if all conditions are False
Example:
age = 17
if age >= 18:
print("You are eligible vote.")
elif age == 17:
print("You will be eligible to vote after 1 year.")
else:
print("You are not eligible to vote.")
Output:
Subscribe to my newsletter
Read articles from Abdullah Bin Altaf directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by