If-else statement
An if statement can be followed by an optional else statement. An else statement contains the block of code that executes if the conditional expression in the if statement is False. An else statement is optional statement and there could be at most one else statement following if.
Syntax :
if(conditional expression):
statement(s) # execute if condition is true
else :
statement(s) # executes if condition is false
Working and Execution :
a. The condition will be evaluated to a conditional expression (true or false)
b. If the condition is true then the statements or program present inside the if block will be executed.
c. If the condition is false then the statements or program present inside else block will be executed
Flow chart :
Example :
number=5
if(number<10):
print("number is less than 10")
else:
print("number is greater than 10")
print("this statement will always be executed")
Output :
number is less than 10
this statement will always be executed
Short hand If-else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line.
Example :
a=2
b=3
print("a") if a>b else print ("b")
Output :
b
No comments:
Post a Comment