Decision making in programming languages determines the direction of program execution. Decision statements are available in Python:
if statement — the simplest decision making statement. It is used to determine whether a certain statement or statement block will be executed, i.e. if a certain condition is true, then the statement block is executed differently.
if condition : # Statements to execute if # condition is true
Here the condition after evaluation will be either true or false. if operator accepts boolean values — if true then it will execute the statement block below it, otherwise — not. We can also use a condition with a parenthesis & # 39; (& # 39; & # 39;) & # 39 ;.
As we know, Python uses indentation to identify a block ... Thus, the block in the if statement will be identified, as shown in the following example:
if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block.
| < / tr> |
I am Not in if
As a condition, present in the if statement is false. Thus, the block under the if statement is not executed.
Statement only if tells us that if the condition is true, it will execute the block of statements, and if the condition is false, then it won't. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with the if statement to execute a block of code when a condition is false.
if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false
Block diagram: —
i is greater than 15 i'm in else Block i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement, false after calling the statement that is not found in the block (no spaces).
Nested if statement & # 8212 ; it is an if statement that is the target of another if statement. A nested if statement means an if statement inside another if statement. Yes, Python allows us to nest if statements in if statements. those. we can put an if statement inside another if statement.
if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here
< code class = "undefined spaces">
i is smaller than 15 i is smaller than 12 too
Here the user can choose between several options. If statements are executed from top to bottom. As soon as one of the conditions governing the if condition is met, the statement associated with that if condition is executed and the rest of the circuit is bypassed. If none of the conditions are met, then the last else statement is executed.
Syntax : —
if (condition): statement elif (condition ): statement. ... else: statement
Block diagram: —
i is 20