To compare two values with an if
statement in Python, you can use comparison operators such as ==
(equal to), !=
(not equal to), <
(less than), >
(greater than), <=
(less than or equal to), or >=
(greater than or equal to). Here’s an example:
a = 5
b = 10
if a == b:
print("a and b are equal")
elif a < b:
print("a is less than b")
else:
print("a is greater than b")
In this example, we compare the values of a
and b
using the if
statement and the comparison operators.
- The condition
a == b
checks ifa
is equal tob
. If it evaluates toTrue
, the corresponding code block is executed, printing “a and b are equal”. - The
elif
statement introduces an additional condition to check ifa
is less thanb
using the<
operator. If it evaluates toTrue
, the corresponding code block is executed, printing “a is less than b”. - If none of the previous conditions are satisfied, the
else
block is executed, and it prints “a is greater than b”.
You can modify the comparison operators and conditions based on your specific requirements. Note that indentation is crucial in Python to indicate the scope of code blocks associated with if
, elif
, and else
statements.
+ There are no comments
Add yours