Lec 01 - Control Statement (3)
Lec 01 - Control Statement (3)
Lec 01 - Control Statement (3)
Statement
Contents
Introduction:
Boolean Expression
Control Statement
Conditional Statement
If statement
If – else statement
If – elif – else statmet
Looping/Iteration
While loop
For loop
INTRODUCTION
So far, we’ve viewed programs as sequences of
instructions that are followed one after the other.
While this is a fundamental programming concept, it is
not sufficient in itself to solve every problem. We need to
be able to alter the sequential flow of a program to suit a
particular situation.
A control structure is a logical design that controls the
order in which a set of statements execute.
Control structures allow us to alter this sequential
program flow.
Cont
In this chapter, we’ll learn about decision structures,
which are statements that allow a program to execute
different sequences of instructions for different cases,
allowing the program to “choose” an appropriate course
of action.
Boolean Expressions
Arithmetic expressions evaluate to numeric values; a
Boolean expression, sometimes called a predicate, may
have only one of two possible values: false or true.
The simplest Boolean expressions in Python are True and False. In a Python
interactive shell we see:
Cont..
The simplest kinds of Boolean expressions use relational
operators to compare two expressions.
The Simple if Statement
The if statement is used to check a condition: if the condition is
TRUE, we run a block of statements (the if-block), else (FALSE)
we process another block of statements (else-block) or continue if
no optional else clause.
Cont...
The semantics of the if
First, the condition in the heading is evaluated.
If the condition is true, the sequence of statements in the
body is executed, and then control passes to the next
statement in the program.
If the condition is false, the statements in the body are
skipped, and control passes to the next statement in the
program.
Cont...
What is the output with these 2 dialogs?
GPA? 3.78 _________
GPA? 2.59 _________
If the value of x is less than zero, this section of code should print
nothing. Unfortunately, the code fragment above is not legal Python.
The if/else statement contains an else block, but it does not contain
an if block.
Python has a special statement, pass, that means do nothing.
Nested Conditionals
The statements in the block of the if or the else may be
any Python statements, including other if/else
statements.
We can use these nested if statements to develop
arbitrarily complex program logic.
Comparing Strings
Python allows you to compare strings. This allows you to
create decision structures that test the value of a string.
name1 = 'Mary' name2 = 'Mark' if name1 == name2:
print('The names are the same.') else:
print('The names are NOT the same.')
End