A control structure is a logical design that controls the order in which a set of statements execute.
A sequence structure
is a set of statements that execute in the order that they appear.
For example, the following code is a sequence structure because the statements execute from top to bottom.
name = input('What is
your name? ')
age = int(input('What
is your age? '))
print('Here is the data
you entered:')
print('Name:', name)
print('Age:', age)
Although the sequence
structure is heavily used in programming, it cannot handle every type of task.
Control structure: one
that can execute a set of statements only under certain circumstances. This can
be accomplished with a decision structure. Decision structures are also
known as selection structures.
In a decision
structure’s simplest form, a specific action is performed only if a certain
condition exists. If the condition does not exist, the action is not performed.
1. If
Statement:
The if statement
contains a logical expression using which data is compared and a decision is
made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean
expression evaluates to TRUE, then the block of statement(s) inside the if statement
is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.
Example:
a = 3
if a > 2:
print(a,
"is greater")
print("done")
2. Alternative if
(If-Else):
An else statement can
be combined with an if statement. An else statement contains the block of code
(false block) 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 most only one else Statement
following if.
Syntax of if - else :
if test expression:
Body of if
else:
Body of else
Example:
a=int(input('enter the
number'))
if a>5:
print("a
is greater")
else:
print("a
is smaller than the input given")
3. Chained Conditional:
(If-elif-else):
The elif statement
allows us 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 most one
statement, there can be an arbitrary number of elif statements following an if.
Syntax of if – elif -
else :
If test expression:
Body
of if
elif test expression:
Body
of elif
else:
Body
of else
Example:
a=int(input('enter the
number'))
b=int(input('enter the
number'))
c=int(input('enter the
number'))
if a>b:
print("a
is greater")
elif b>c:
print("b
is greater")
else:
print("c is greater")