If you have to compare data's and then display the result conditionals are used.
if, elif, else
Ex for if
v1,v2=3,4
if v1<v2:
print("v2 is greater")
Ex for else
v1,v2=7,4
if v1<v2:
print("v2 is greater")
else:
print("v1 is greater")
Ex for elif
v1,v2=7,7
if v1<v2:
print("v2 is greater")
elif v1>v2:
print("v1 is greater")
else:
print("v1 is equal to v2")
Conditional expression:
Compare in one line and display
Ex:
v1, v2=5,3
ans="v1 is greater" if v1>v2 else "v2 is greater"
print(ans)
Switch Alternative
selc=dict(
one="Fan",
two="TV",
three="Frdige",
four="Microwave"
)
v='two'
print(selc[v])
O/P:
TV
If in above example v is assigned with other values than mentioned in dictionary then results in error. Below example shows how to hide the error and display the result
selc=dict(
one="Fan",
two="TV",
three="Frdige",
four="Microwave"
)
v='six'
print(selc.get(v,"Wrong selection"))
O/P
Wrong selection
if, elif, else
Ex for if
v1,v2=3,4
if v1<v2:
print("v2 is greater")
Ex for else
v1,v2=7,4
if v1<v2:
print("v2 is greater")
else:
print("v1 is greater")
Ex for elif
v1,v2=7,7
if v1<v2:
print("v2 is greater")
elif v1>v2:
print("v1 is greater")
else:
print("v1 is equal to v2")
Conditional expression:
Compare in one line and display
Ex:
v1, v2=5,3
ans="v1 is greater" if v1>v2 else "v2 is greater"
print(ans)
Switch Alternative
selc=dict(
one="Fan",
two="TV",
three="Frdige",
four="Microwave"
)
v='two'
print(selc[v])
O/P:
TV
If in above example v is assigned with other values than mentioned in dictionary then results in error. Below example shows how to hide the error and display the result
selc=dict(
one="Fan",
two="TV",
three="Frdige",
four="Microwave"
)
v='six'
print(selc.get(v,"Wrong selection"))
O/P
Wrong selection