The if-else statement provides an else block of code which is executed if the condition is turned false.
if < test expression>:
< statement>
else:
< statement>
NOTE-The body of if will be executed only when the test condition is True. The body of else is executed only if the if condition is false. Indentation is used to separate the if and else blocks of code.
In a code, if the if-else statements are present, then first, the test expression included in the ‘if’ statement is checked. If the given expression results True, then the block of codes given below the ‘if’ statement will be executed. And the codes after the if-else statements are then executed. However, suppose the test expression results in False. In that case, the block of code mentioned below the else statement is executed, and then the statements mentioned after the if-else statements are executed.
If there is only one line of code statement to be executed each after the if statement and the else statement, then you can put it all in a single line. Here is the syntax for it:
print(if result) if (test expression) else print (else result)
Knowledge2life 2
|