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

Control Structures Complete

Uploaded by

Rahul Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Control Structures Complete

Uploaded by

Rahul Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Control Structures

Musarrat Ahmed
Outline
● if, else, elif
● Conditional expression
● pass statement
● Loops
● break and continue
● else clause
if Statement
● In its simplest form, it looks like this:
- <expr> is an expression evaluated in Boolean context.
- <statement> is a valid Python statement, which must be
indented.
● If <expr> is true (evaluates to a value that is “truthy”), then <statement> is
executed else it is skipped over.
● Note that the colon (:) following <expr> is required.
● No parentheses should enclose <expr>.
4
Grouping Statements
● Python is one of a relatively small set of off-side rule languages, in which blocks
are defined by indentation.
● In a Python program, contiguous statements that are indented to the same level
are considered to be part of the same block.
● There is no token that denotes the end of the block.
● Rather, it is indicated by a line that is indented less than the lines of the block
itself.
● In the Python documentation, a group of statements
defined by indentation is often referred to as a suite.

else and elif Clauses
- If <expr> is true, the first suite is executed, and the second is
skipped - If <expr> is false, the first suite is skipped and the second is
executed.
● If there’re several alternatives, elif clause is used.
● The else clause is optional. If it is present, there can be only one, and it must be
specified last.
8
One-line if Statements
● It is permissible to write an entire if statement on one line.
● There can even be more than one <statement> on the same line, separated by
semicolons.
If <expr> is true, execute all of <statement_1> ... <statement_n> .
Otherwise, don’t execute any of them.

● Multiple statements may be specified on the


same line as an elif or else clause as well.
● PEP 8 specifically recommends against these
one-line if statements.
Conditional Expression
● Also referred to as a conditional operator or ternary operator.

● <conditional_expr> is evaluated first. If it is true, the


expression evaluates to <expr1>. If it is false,
the expression evaluates to <expr2>.
● Can be used as part of a longer expression.
● It has lower precedence than virtually all the other operators, so parentheses are
needed to group it by itself.
● It uses short-circuit evaluation.
pass Statement
● Because Python uses indentation instead of delimiters, it is not possible to specify
an empty block.
● If you introduce an if statement with if <expr>: , something has to come after
it, either on the same line or indented on the following line.

● pass statement solves this problem.


● It is used as a placeholder to keep the interpreter happy in any situation
where a statement is syntactically required, but you don’t really want
to do anything.
Loops in Python
for Loop
● Python’s for loop looks like this:
● <iterable> : collection of objects—for example, a list or tuple.
● <statement(s)> : denoted by indentation, executed once for each item in
<iterable>.
● <var> : loop variable that takes on the value of the next element in
<iterable> each time through the loop.
Iterables and Iterators
● Iterable means an object that can be used in iteration.
● If an object is iterable, it can be passed to the built-in function iter(), which
returns something called an iterator.
● Each of the objects in the following example is an iterable and returns some type
of iterator when passed to iter():
● An iterator is essentially a value producer that yields successive values from its
associated iterable object.
● The built-in function next() is used to obtain the next value from iterator.
● In the example, a is an iterable list and itr is the associated iterator, obtained
with iter(). Each next(itr) call obtains the next value from itr.
● If all the values from an iterator have been returned already, a subsequent
next() call raises a StopIteration exception.

● You can only obtain values from an iterator in one direction. You can’t go
backward. There is no prev() function.

● But you can define two independent iterators on the same iterable object.

17
Working of for loop
● To carry out the iteration in for loop, Python does the following:
➔ Calls iter() to obtain an iterator for a
➔ Calls next() repeatedly to obtain each item
from the iterator in turn
➔ Terminates the loop when next() raises
the StopIteration exception
range()Function
● Python’s built-in range() function returns an iterable that yields a sequence of
integers.
● range(start, stop[, step])
while Loop
● The format of a rudimentary while loop is:
One-line while Loop
● A while loop can be specified on one line.
● Multiple statements in the block can be separated by semicolons.

● You can’t combine two compound statements into one line.


break and continue
● break statement immediately terminates a loop entirely. Program execution
proceeds to the first statement following the loop body.
● continue statement immediately terminates the current loop iteration. Execution
jumps to the top of the loop, and the controlling expression is re-evaluated to
determine whether the loop will execute again or terminate.
else Clause
● Python allows an optional else clause at the end of a while/for loop.
● The statement specified in the else clause will be executed when the while
loop terminates.
● Statements placed in an else clause will be executed only if the loop terminates
“by exhaustion”.
25
Quiz Time
1. What is the output of this
code snippet? a) ('baz', 3)
('bar', 2)
('foo', 1)
Done.
b) foo
bar
baz
c) No output
d) Done.

Ans: (d)
2. What is the output of this code
snippet? a) d)

b)

c) No output

Ans: (a)
3. Which one of the following if
statements will not execute a)
successfully?

b)

c)

d)

Ans: (c)
4. Suppose you have the following
variables defined: Write a Python conditional
expression to assign the
smaller of a and b to the
variable m.
5. Which of the following are valid
if/else statements in Python, a)
assuming x and y are defined
appropriately?
b)

c)

d)

Ans: (a),(d)
6. What is value of this
expression? a) 'axyb'

b) 'ab'

c) 'axb'

d) 'ax'

Ans: (d)
7. What is the output of the
following code snippet? a) 123

b) 1 2 3

c) 1
2
3

d) Error

Ans: (d)
8. What is the output of the
following code snippet? a) 0 1 2 0

b) 0 1 2

c) 0
1
2

d) Error

Ans: (c)
Thank you!

You might also like