Conditional Statements In Python
Conditional Statements
One of the most Crucial thing in programming is decision making It is required to give direction to the code.
These are some operators which are used with conditional Statements.
Equals (==)->
We use it to check if a variable is equal to another variable. For example, m == n.
Not Equals (!=)->
To check if a variable is not equal to another variable. For example, m != n.
Greater Than (>)->
To check if a variable is greater than another variable. For example, m > n.
Less Than (<) ->
To check if a variable is less than another variable. For example, m < n.
Greater Than or Equal to->
To assess if a variable is greater than or equal to another variable. For example, m >= n.
Less Than or Equal to->
To evaluate if a variable is less than or equal to another variable. For example, m <= n.
FOUR TYPES OF CONDITIONAL STATEMENTS
if Conditional Statement
The if conditional statement is the simplest conditional statement in python programming In if conditional statement the code will execute if the given condition is true otherwise it will move forward in the program.
x = 5
if x == 5:
print("True")
Output: True
If else conditional statement
"In an if-else conditional statement, the code within the if block is executed if the given condition is True. If the condition is False, the code within the else block is executed instead."
x = 5
if x == 4:
print("True")
else:
print("False")
Output: False
Nested if conditional statement
"Nested if statements allow you to create complex decision-making structures in Python. By placing one if statement within another, you can execute different code blocks based on multiple conditions. However, excessive nesting can make code less readable and harder to maintain.
x = 10
y = 20
if x > 5:
if y > 15:
print("Both x and y are greater")
else:
print("x is greater than 5,
but y is not greater than 15")
else:
print("x is not greater than 5")
Output: Both x and y are greater than
their respective values
if-elif-else Conditional Statement
"This conditional statement operates as follows: if the if condition evaluates to True, the code within its block is executed. Otherwise, if an else block is present, its code is executed instead."
a = 7
b = 9
c = 10
if a >= b and a >= c:
print("a is greatest")
elif b >= a and b >= c:
print("b is greatest")
else:
print("c is greatest")
Output: is greatest
Follow on LinkedIn
Comments
Post a Comment