Python Conditional Statements
Decision making is one of the most important concepts of computer programming . It require that the developer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Python programming language provides following types of decision making statements.
- if statements
- if....else statements
- if..elif..else statements
- nested if statements
- not operator in if statement
- and operator in if statement
- in operator in if statement
Python if statements
In Python, if statement evaluates the test expression inside parenthesis. If test expression is evaluated to true (nonzero) , statements inside the body of if is executed. If test expression is evaluated to false (0) , statements inside the body of if is skipped.
In this program we have two variables x and y. x is assigned as the value 20 and y is 10. In next line, the if statement evaluate the expression (x>y) is true or false. In this case the x > y is true because x=20 and y=10, then the control goes to the body of if block and print the message "X is bigger". If the condition is false then the control goes outside the if block.
Python if..else statements
The else statement is to specify a block of code to be executed, if the condition in the if statement is false. Thus, the else clause ensures that a sequence of statements is executed.
In the above code, the if stat evaluate the expression is true or false. In this case the x > y is false, then the control goes to the body of else block , so the program will execute the code inside else block.
The elif is short for else if and is useful to avoid excessive indentation.
In the above case Python evaluates each expression one by one and if a true condition is found the statement(s) block under that expression will be executed. If no true condition is found the statement(s) block under else will be executed.
Nested if statements
In some situations you have to place an if statement inside another statement.
not operator in if statement
By using Not keyword we can change the meaning of the expressions, moreover we can invert an expression.
You can write same code using "!=" operator.
and operator in if statement
The equivalent of "& & " is "and" in Python.