Conditional Statements in Python

Decision making empowers us to change the control-flow of the program. There are two major ways to accomplish this task. One is the "if" construct and the other is "switch".

The "if" block in a program is executed if the condition is true otherwise it is not executed. Switch is used to implement a scenario in which there are many conditions, and the corresponding block executes in case a particular condition is true.

Example: Ask the user to enter the marks of a student in a subject. If the marks entered are greater than 35, then print "pass". If they are lower print "fail".

marks = input("Enter Marks: ")

if int(marks) > 35:
    print("Pass")
else:
    print("Fail")

Logical Operators

In many cases, the execution of a block depends on the value of more than one statement. In such cases the operators “and” (“&”) and “or” (“|”) are used. The "and" is used when both conditions are true. The "or" is used if any of the conditions are true.

Ternary Operator

The code can be reduced by using the ternary statements provided by Python. For example, the conditional operator can be used to check which of the two numbers entered by the user is greater.

great = a if (a>b) else b