Day 2:Conditions ,Decision Making in Python
In C,C++,Java etc there are main three Decision Making blocks. If, Switch and Conditional Operators (?). In Python there is If . After Python 2.5 We can use two versions of If.
- Single Line If (Like Turnery/Conditional Operator)
- If Block
Following Example shows the use of both
x=2
y=3
#If Block
if x> y:
z=x
else:
z=y
print(z)
#Single Line If
x= x if x>y else y #Like Conditional Operator/Turnary Operator
print(x)
#Other Relational Operators <, <=, >, >= ,== , !=
if x==y:
print("Same")
else:
print("Not Same")
if x!=y:
print("Different")
else:
print("Equal Values")
Output for the above program will be.
3
3
Same
Equal Values
>>>
In Python there is no Switch..Case Statement is supported. But It can be achieved by if else block.
Following if the Example for if.elif and Nested if
x=int(input("Enter X"))
y=int(input("Enter Y"))
z=int(input("Enter Z"))
if x>y:
if x>z:
print("X is Great")
else:
print("Z is Great")
else:
if y>z:
print("Y is Great")
else:
print("Z is Great")
#Another Way
if x>y and x>z:
print("X is Greater")
elif(y>z):
print("Y is Greater")
else:
print("Z is Greater")