Like any other programming language python also support if-else for the conditional statement.
== :- Equals
a == b
!= :- Not Equals
a != b
< :- Less than
a < b
<= :- Less than or equal to
a <= b
> :- Greater than
a > b
>= :- Greater than or equal to
a >= b
These conditions can be used in several ways, most commonly in "if statements".
Syntax:
if (condition) :
#exexute this block
Or without braces
if condition :
#exexute this block
For example
a=5
if a==5:
print("A value is 5")
Output:
A value is 5
- when we want to check one condition and if that condition met we need to execute if block code otherwise run else block
Syntax:
if condition :
#exexute this block
else:
#execute this else block
For example
a=5
if (a==5):
print("A value is 5")
else:
print("A value is not 5")
Output :
A value is 5
Or you can simple write
a=5
if a==5:
print(" A value is 5")
else:
print("A value is not 5")
Output:
A value is 5
- There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.
Syntax:
if condition:
#code
if condition:
#code here for inner if
else:
#else code
else:
#outer else code add here
When you want to execute multiple conditions you can use elif
Santax:
if condition:
#add code here
elif second condition:
#add another code block
elif third_condition:
#add another code block
else:
#add final else block
Here first condition check if it doesn't true then it check second condition if all elif conditions are fail at that time it will execute else block
Use logical operator and(&), or(|) to checking multiple conditions
syntax
if condition and condition2 and condition3:
#code block
Example:
a=5
b=6
c=3
large=0
if a>b and a>c :
large=a
elif b>a and b>c :
large=b
else:
large=c
print(large)
Output:
6