4. Conditional Statements & Decision Making
4. Conditional Statements & Decision Making
You need to determine which action to take and which statements to execute if
the outcome is TRUE or FALSE otherwise.
Statement Description
Syntax
if expression:
statement(s)
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
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. if
expression:
statement(s)
else:
statement(s)
#!/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)
The elif statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for
which there can be at the most one statement, there can be an arbitrary
number of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
var = 100
if ( var == 100 ) :
print ("Value of expression is 100")
print ("Good bye!")
n=5
"Greater than 2" if n > 2 else "Smaller than or equal to 2"
# Out: 'Greater than 2'
Truth Values
The following values are considered false, in that they evaluate to False when
applied to a boolean operator.
None
False
0, or any numerical value equivalent to zero, for example 0L, 0.0, 0j
Empty sequences: '', "", (), []
Empty mappings: {}
User-defined types where the __bool__ or __len__ methods return 0 or
False