Lec 01 - Control Statement (3)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Control

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 _________

gpa = eval(input("GPA? "))


if gpa >= 3.5:
print("Deans list")
else:
print("Work harder")

print("One or the other, but always this")


Cont...
celsius = eval(input("Celsius temperature? "))
if celsius >= 40:
print("Heat stroke danger")
if celsius < -20:
print("Frost bite danger")
if celsius >= -20 and celsius < 40:
print("You decide")
Cont...
The if/else Statement
 The if statement has an optional else block that is
executed only if the Boolean condition is false.
Indentation in the if-else Statement
 When you write an if-else statement, follow these
guidelines for indentation:
 Make sure the if clause and the else clause are aligned.
 The if clause and the else clause are each followed by a
block of statements. Make sure the statements in the blocks
are consistently indented.
The if-elif-else Statement
 Python provides a special version of the decision structure
known as the if-elif-else statement, which makes this type of
logic simpler to write.
 Here is the general format of the if-elif-else statement:
if condition_1:
statement
statement
etc.
elif condition_2:
statement
statement
etc.
Cont...
Compound Boolean Expressions
 We can combine simple Boolean expressions, each
involving one relational operator, into more complex
Boolean expressions using the logical operators and, or, and
not.
 A combination of two or more Boolean expressions using
logical operators is called a compound Boolean expression.
age = 21
gender = "Male"
if gender == "Male" and age < 25:
print ("You will need to take out a loan to buy car insurance!")
else:
print ("Maybe car insurance won't be too expensive for you...")
The pass Statement

 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.')

 The == operator compares name1 and name2 to


determine whether they are equal.
Cont...
Iteration
 Iteration repeats the execution of a sequence of code.
 Iteration is useful for solving many programming
problems. Iteration and conditional execution form the
basis for algorithm construction.
Condition-Controlled and Count-Controlled Loops

 A condition-controlled loop uses a true/false condition to


control the number of times that it repeats.
 A count-controlled loop repeats a specific number of
times.
 In Python, you use the while statement to write a
condition-controlled loop, and you use the for statement
to write a count-controlled loop.
The while Loop: A Condition-Controlled Loop

 A condition-controlled loop causes a statement or set of


statements to repeat as long as a condition is true.
 In Python, you use the while statement to write a
condition-controlled loop.
 The while loop gets its name from the way it works: while
a condition is true, do some task.
 The loop has two parts:
 (1) a condition that is tested for a true or false value, and
 (2) a statement or set of statements that is repeated as long
as the condition is true.
Cont...
 Here is the general format of the while loop in Python:
while condition:
statement
statement
etc.
Cont...
Cont...
Cont...
Cont...
Infinite Loops
 If a loop does not have a way of stopping, it is called an
infinite loop.
 An infinite loop continues to repeat until the program is
interrupted.
 Infinite loops usually occur when the programmer forgets
to write code inside the loop that makes the test
condition false.
Cont...
The for Loop: A Count-Controlled Loop

 A count-controlled loop iterates a specific number of times. In


Python, you use the for statement to write a count-controlled
loop.
 The while loop is ideal for indefinite loops.
 We have used a while loop to implement a definite loop, as in

 The print statement in this code executes exactly 10 times


every time this code runs.
Cont...
 Python provides a more convenient way to express a definite
loop. The for statement iterates over a sequence of values.
 One way to express a sequence is via a tuple, as shown here:
for n in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10:
print(n)
 Python provides a convenient way to express a sequence of
integers that follow a regular pattern.
 The following code uses a range expression to print the
integers 1 through 10:
for n in range(1, 11):
print(n)
Cont...
 The general form of the range expression is
range( begin,end,step )
where
 begin is the first value in the range; if omitted, the default
value is 0
 end is one past the last value in the range; the end value
is always required and may not be omitted
 step is the amount to increment or decrement; if the step
parameter is omitted, it defaults to 1 (counts up by ones)
 begin, end, and step must all be integer expressions;
Cont...
 The range expression is very flexible. Consider the
following loop that counts down from 21 to 3 by threes:
for n in range(21, 0, -3):
print(n, end=' ')
 It prints
21 18 15 12 9 6 3
Cont...
 The expression range(1000) produces the sequence
0;1;2;:::;999.
 The following code computes and prints the sum of all the
positive integers less than 100:
sum = 0 # Initialize sum
for i in range(1, 100):
sum += i
print(sum)
Cont...
Cont...

End

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy