0% found this document useful (0 votes)
8 views

Lec 6. Control Structures

Uploaded by

sudeepiitb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lec 6. Control Structures

Uploaded by

sudeepiitb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Fall 2019

Computational Thinking with @cse_bennett @csebennett

Programming
Control
Structures
• Control flow is the order that instructions are executed in a program.
• A control statement is a statement that determines the control flow of
a set of instructions.
• Types of Control:
• Sequential control: Instructions are executed in the order that
they are written
• Selection control: Selectively executes the instructions.
Control E.g. Decision Control
• Iterative control: Repeatedly executes the instructions. E.g. Loops.
Structures
Selection Control or Decisions
(It is a control statement providing selective execution of instructions)

Decisions • if statements
in a • if else statements
Python • elif statements
program • nested if conditions
If Statement Syntax:
It is a selection control statement based on the if test expression:
value of a given Boolean expression statement(s)
Expression’s value can be True or False.
We may want to do something only when a certain condition is true.

if statement in python takes an expression with it.

If the expression results to True


• then the block of statements under it is executed.

If it results to False
• then the block is skipped and control transfers to the statements
after the block.

Remember to indent the statements in a block equally


If Statement: Example
Example: What will be the output ?
1. 4.

2.
5.

3.
Example: What will be the output ?
1. 4.

Output: Smaller
Output: 3 is a positive number.
2. This is always printed.
5.
Output: Finish
3.
Output: This is also always printed.

Output: yay
if...else Statement
a.k.a. Two way decisions

What happens when the


condition is untrue or false?

We can mention that it in the


block after the else statement.

An ‘else’ statement comes


right after the block after ‘if’.
Syntax:
if test expression:
Body of if
else:
Body of else

Example
• One unique aspect of Python is that the amount of
indentation of each program line is significant.

Header, Suite
and Indentation
Nested if statements (multi-way selection)

You can put an if


statement in the
block under another
if statement.

This is to implement
further checks.
Nested if statements: Example
Example: What will be the output?
Example: What will be the output?
if...elif...else Statement

Replacement to More than one


the else-if condition to
statements check

If condition 1 isn’t If it isn’t true,


True, condition 2 condition 3 is
is checked. checked.
if...elif...else Statement: Example Use
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Example:
What will be
the output?
Example:
What will be
the output?
Single Statement Condition
Write a single statement under if
Exercise

Find out the Max of three numbers


Maximum between 3 numbers
Maximum between 3 numbers
Maximum between 3 numbers
MCQs
1. All if statements must contain either an 3. Which of the following statements is true?
else or elif header. a) Statements within a suite can be indented a
a) TRUE different amount.
b) FALSE b) Statements within a suite can be indented a
different amount as long as all headers in
the statement that it occurs in are indented
2. Which of the following statements are the same amount.
true regarding headers in Python? c) All headers must be indented the same
a) Headers begin with a keyword and amount as all other headers in the same
end with a colon. statement, and all statements in a given
b) Headers always occur in pairs. suite must be indented the same amount.
c) All headers of the same compound 4. The elif header allows for,
statement must be indented the a) Multi-way selection that cannot be
same amount. accomplished otherwise
b) Multi-way selection as a single if statement
c) The use of a “catch-all” case in multi-way
selection
MCQs: Answers
1. All if statements must contain either an 3. Which of the following statements is true?
else or elif header. a) Statements within a suite can be indented a
a) TRUE different amount.
b) FALSE b) Statements within a suite can be indented a
different amount as long as all headers in
the statement that it occurs in are indented
2. Which of the following statements are the same amount.
true regarding headers in Python? c) All headers must be indented the same
a) Headers begin with a keyword and amount as all other headers in the same
end with a colon. statement, and all statements in a given
b) Headers always occur in pairs. suite must be indented the same amount.
c) All headers of the same compound 4. The elif header allows for,
statement must be indented the a) Multi-way selection that cannot be
same amount. accomplished otherwise
b) Multi-way selection as a single if statement
c) The use of a “catch-all” case in multi-way
selection
Iterative Control (Loop)
• An iterative control statement is a control
statement that allows for the repeated
execution of a set of statements.

• Due to their repeated execution, iterative


control structures are commonly referred to
as “loops.

• Loop Statements:
• While
• For
• Nested loop
While Statement (indefinite loop)
• A while statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition).
Example 1
• Find all even numbers from 0 to n. where, n is given by user.
Example 2
• Print all even numbers between n to m. m should be greater than n.
Example 3
Write a program to take numbers from the user until he enter 0 as
input. then print sum of all entered number.
Example 4
• Write an efficient program to determine sum of N natural numbers
where N is given by user.
For Loop Loop to read
(definite loop) sequence

• A for loop is used for iterating over a


sequence (that is either a list, a tuple,
a dictionary, a set, or a string). Can
execute a set of statements, once for
each item in a list, tuple, set etc.

Syntax:
for iterating_var in sequence:
statements(s)
• Example:
Sequences
• Sequence of character - 'QWERTYUIOPASDFGHJKL’
• Sequence of words - ['abc','def','efg','ijk’]
• Sequence of numbers - [1,2,3,4,5,6,7,8,9]
• Sequence of mix data – [‘Suvi’, 4, “LKG”, “Bennett University”, 98.5

Sequence of numbers can also be generated as:


• range(start, end, difference)
• range(3) = (0,1,2)
• range(1,5) = (1,2,3,4)
• range(3,9,2) = (3, 5, 7)
• range(9,2,-1) = (9,8,7,6,5,4,3)
• range(9,2,1) = []
For Loop: What will be the output?
1. 4.

2. 5.

3.
For Loop: Answers to Previous Questions
1 2 3 4 5
Exercise: Write a program to find whether a given
number is prime or not

• Solution:
•Let one grain of wheat be placed on the first square
of a chessboard, two grains on the second square,
four grains on the third square, eight grains on the
fourth square, and so on until all square are filled in
chessboard. what will be the total weight in ton of
grains on whole 8×8 chessboard? If 15432 grains in
one kg and 907.18 kg in one ton then.

Problem
Exercise 2
• Loop inside a loop a is called nested loop.

• Example:

Nested Loop
Nested Loop: What will be the output?
1.

2. 4.

5.
3.
Find all prime numbers between given two numbers
Find first 100 prime numbers start from 2.
Find number is Strong or not

If the sum of the factorial of the digits in a number is equal to the original number, the
number is a strong number.
Accept the limit and print the strong numbers from 1 to
the given limit.
• An infinite loop is an iterative control structure
that never terminates (or eventually terminates
with a system error).
• Infinite loops are generally the result of
programming errors.
• For example: if the condition of a while loop can
never be false, an infinite loop will result when
executed.
Infinite loop
Loop Control Statements
• Break Statement: Terminates the loop statement and transfers execution to the
statement immediately following the loop.
• Continue Statement: Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.

• Pass Statement:The pass statement in Python is used when a statement is required


syntactically but you do not want any command or code to execute.
Example: Output:
Use of pass in if: for letter in 'Python’: Current Letter : P
a = 33 if letter == 'h’: Current Letter : y
b = 200 pass Current Letter : t
if b > a: print('This is pass block’) This is pass block
pass print('Current Letter :', letter) Current Letter : h
Current Letter : o
print(“Loop Ended!“)
Current Letter : n
Loop Ended
Break and Continue: Examples
• Break Statement:
Ex.1: fruits = ["apple", "banana", "cherry"] Ex.2: fruits = ["apple", "banana", "cherry"]
for x in fruits: for x in fruits:
print(x) Output: if x == "banana":
if x == "banana": apple break
break banana print(x)

• Continue Statement:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana": Output:
continue apple
print(x) cherry
MCQs
1. A while loop continues to iterate until its 5. The terms definite loop and indefinite loop
condition becomes false. are used to indicate whether,
a) TRUE a) A given loop executes at least once
b) FALSE
b) The number of times that a loop is
2. A while loop executes zero or more times. executed can be determined before the
a) TRUE loop is executed.
b) FALSE c) Both of the above
3. All iteration can be achieved by a while loop.
a) TRUE 6. A Boolean flag is,
b) FALSE a) A variable
4. An infinite loop is an iterative control b) Has the value True or False
structures that, c) Is used as a condition for control
a) Loops forever and must be forced to statements
terminate
d) All of the above
b) Loops until the program terminates with a
system error
c) Both of the above
MCQs: Answers
1. A while loop continues to iterate until its 5. The terms definite loop and indefinite loop
condition becomes false. are used to indicate whether,
a) TRUE a) A given loop executes at least once
b) FALSE
b) The number of times that a loop is
2. A while loop executes zero or more times. executed can be determined before
a) TRUE the loop is executed.
b) FALSE c) Both of the above
3. All iteration can be achieved by a while loop.
a) TRUE 6. A Boolean flag is,
b) FALSE a) A variable
4. An infinite loop is an iterative control b) Has the value True or False
structures that, c) Is used as a condition for control
a) Loops forever and must be forced to statements
terminate
d) All of the above
b) Loops until the program terminates with a
system error
c) Both of the above

You might also like