If Statements
Selection structure is used when a decision has to be made, based on some
condition, before selecting
an instruction to execute. The condition tested in the selection structure must be a Boolean
expression (evaluating to true or false). The Boolean expression can contain variables,
constants,
arithmetic operators, comparison operators, and logical operators.
Types of selection structure:
- Single-alternative selection structure: A set of instructions is executed only if the
condition
evaluates to true
- Dual-alternative selection structure: Executes different sets of instructions based on
whether
the condition evaluates to true or false
Syntax:
- if condition:
- one or more statements (true path)
- [else:
- one or more statements (false path)]
- The else portion in brackets is optional, executed only if the condition is false.
It
is only used for dual-alternative selection structures
- Indentation is important
-
- if value == 5:
- x += value
-
if answer == 3:
- print(“congratulations”)
- score +=1
-
- if savings >= 15000:
- print(“buy a car”)
- else:
- print(“travel by bus”)
-
- if x > 2:
- print(“yes”)
- x = 5
- else:
- print(“no”)
-
- if grade >= 50:
- print( “congratulations you passed”)
- print(“you will receive a prize”)
- else:
- print(“sorry you failed”)
- print(“you will go on probations”)
The if-else Chain
if-else chain is a nested if statement occurring in the else clause
of
the outer if-else. If any
condition is true, the corresponding statement is executed and the chain terminates. Final
else
is
only executed if no conditions were true. It serves as a catch-all case. if-else chain
provides one
selection from many possible alternatives.
Syntax:
- if condition:
- statement(s)
- elif condition:
- statement(s)
- else:
- statement(s)
-
- a = 200
- b = 33
- if b > a:
- print("b is greater than a")
- eif a == b:
- print("a and b are equal")
- else:
- print("a is greater than b")