if....else Statement

IF...ELIF...ELSE Statements :

An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at the most only one else statement following if.

Syntax :

if expression:
     statement(s)
else:
     statement(s)



Let us take another example :

#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
     discount=amount*0.05
     print ("Discount",discount)
else:
     discount=amount*0.10
     print ("Discount",discount)
print ("Net payable:",amount-discount)

In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it produces the following result-

Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
Net payable: 1080.0


Single Statement Suites

If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.
Here is an example of a one-line if clause-

#!/usr/bin/python3

var = 100

if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")
Value of expression is 100
Good bye!
When the above code is executed, it produces the following result-

Value of expression is 100
Good bye!

if statement<<<Back                           Home                            Next>>>elif Statement