In: Computer Science
There are various selection structures that can be used in programming. What are the different relational operators used in selection structures in the Python programming language? Also, explain what short-circuiting is with respect to compound conditional expressions in Python. Provide examples to support your response in addition to constructive feedback on the structures and circumstances posted by your peers. Provide at least one reference to support your findings.
a) Relational operators used in selection structures are:
Example: if age < 18: print("Cannot vote")
Example: if age > 60: print("Senior citizen")
Example: if age <= 60: print("Not senior citizen")
Example: if age >= 18: print("Can vote")
if i % 2 == 0: print("Even")
if i mod 2 != 0: print("Odd")
By short circuiting we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right. In python, short circuiting is supported by various boolean operators and functions.
Short Circuiting in conditional operators
Conditional operators also follow short circuiting as when expression result is obtained, further execution is not required.
Example
# python code to demonstrate short circuiting
# using conditional operators
# helper function
def check(i):
print ("geeks")
return i
# using conditional expressions
# since 10 is not greater than 11
# further execution is not taken place
# to check for truth value.
print( 10 > 11 > check(3) )
print ("\r")
# using conditional expressions
# since 11 is greater than 10
# further execution is taken place
# to check for truth value.
# return true as 11 > 3
print( 10 < 11 > check(3) )
print ("\r")
# using conditional expressions
# since 11 is greater than 10
# further execution is taken place
# to check for truth value.
# return false as 11 < 12
print( 10 < 11 > check(12) )
Output:
False geeks True geeks False