Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. Conditional statements are handled by IF statements in Python.
#
#Example file for working with conditional statement
#
def main():
x,y =2,8
if(x < y):
st= "x is less than y"
print(st)
if __name__ == "__main__":
main()
In this above, if the condition is not met, then st becomes undefined and the run time will give error.
Below is for elif
#
#Example file for working with conditional statement
#
def main():
x,y =8,8
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)
if __name__ == "__main__":
main()
A short form like ternary operator is like below
def main():
x,y = 10,8
st = "x is less than y" if (x < y) else "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
Python doesn't have switch statement. Python uses dictionary mapping to implement switch statement in Python
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
References
https://www.guru99.com/if-loop-python-conditional-structures.html
#
#Example file for working with conditional statement
#
def main():
x,y =2,8
if(x < y):
st= "x is less than y"
print(st)
if __name__ == "__main__":
main()
In this above, if the condition is not met, then st becomes undefined and the run time will give error.
Below is for elif
#
#Example file for working with conditional statement
#
def main():
x,y =8,8
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)
if __name__ == "__main__":
main()
A short form like ternary operator is like below
def main():
x,y = 10,8
st = "x is less than y" if (x < y) else "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
Python doesn't have switch statement. Python uses dictionary mapping to implement switch statement in Python
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
References
https://www.guru99.com/if-loop-python-conditional-structures.html
No comments:
Post a Comment