KEMBAR78
Lecture 2 | PDF | Control Flow | Computer Science
0% found this document useful (0 votes)
18 views31 pages

Lecture 2

The document explains the concepts of conditionals and iterations in Python programming, detailing various conditional statements such as if, if-else, elif, and nested conditionals. It also covers loops, particularly the for loop and while loop, including their syntax and usage for repetitive tasks. Additionally, it discusses shortcuts for conditions, the absence of switch-case statements in Python, and provides examples and quizzes to reinforce understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

Lecture 2

The document explains the concepts of conditionals and iterations in Python programming, detailing various conditional statements such as if, if-else, elif, and nested conditionals. It also covers loops, particularly the for loop and while loop, including their syntax and usage for repetitive tasks. Additionally, it discusses shortcuts for conditions, the absence of switch-case statements in Python, and provides examples and quizzes to reinforce understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Conditionals

and
Iterations
Conditional Execution
• To write useful programs we need the ability to check conditions and
change the behaviour of the program accordingly.
• Different conditional statements in python are:
• if
• if ---else (Alternative Execution)
• if--- elif---- else (Chained Conditionals)
• Nested Conditionals (one into another)
What is conditional statements?

Condition True
e.g.

X=
Y=
False if block
if X>Y:
print(“Hello”)
print(“I don’t know”)
Next statement
What is conditional statements?
e.g.
False True
Condition
X=
Y=

if X>Y:
print(“Hello in if”) else block if block
else:
print(“Hello in else”)
print(“out of conditional statement”)
Next statement
What is conditional statements?
e.g.
Condition 1 True if block
X= False
Y=
Condition 2 True elif block

if X>Y: False
print(“X is greater than Y”) True
Condition 3 elif block
elif X<Y:
print(“Y is greater than X”) False
else: else block
print(“X is equal to Y”)
print(“out of conditional statement”)
Next statement
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven't written yet). In that case, you can use
the pass statement, which does nothing.

if x>0: if x>0:
print(“This statement is not in if”) pass
print(“This statement is not in if”)
IndentationError: expected an indented block
Alternative Execution
• A second form of the if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets
executed.
• Eg:
if x%2 == 0:
print( x, "is even“)
else:
print( x, "is odd“)
• The alternatives are called branches.
Quiz
x=5
if x>=0:
print(“Hello”)
print(“out of if”)

output would be

A. Hello
out of if
B. Hello
C. out of if
D. Error
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.
if x < y:
print( x, "is less than", y)
elif x > y:
print (x, "is greater than", y)
else:
print (x, "and", y, "are equal“)
NOTE: There is no limit of the number of elif statements.
Nested conditionals
• One conditional can also be nested within another.
if x == y:
print (x, "and", y, "are equal“)
else:
if x < y:
print (x, "is less than", y)
else:
print (x, "is greater than", y)
if 0 < x and x < 10:
print ("x is a positive single digit.“)

• Python provides an alternative syntax that is similar to mathematical


notation:
if 0 < x < 10:
print ("x is a positive single digit.“)
Shortcuts for Conditions
• Numeric value 0 is treated as False
• Empty sequence "", [] is treated as False
• Everything else is True
if m%n:
(m,n) = (n,m%n)
else:
gcd = n
Avoid Nested If
• For example, We can rewrite the following code using a single
conditional:
if 0 < x:
if x < 10:
print ("x is a positive single digit.“)
Better way:
if 0 < x and x < 10:
print ("x is a positive single digit.“)
Also possible (Ternary operator)
x,y=12,44
st="x is greater than y" if (x>y) else "x is less than or equal to y"
print(st)

Note: can not use elif in one line


Point to be noted
Python does not have any switch case statement
If []:
print(“inside if”)
Quiz print(“out of if”)

output would be

A. inside if
out of if
B. inside if
C. out of if
D. Error
ITERATION
Doing the Same Thing Many Times

• It’s possible to do something repeatedly by just writing it all out


• Print ‘hello’ 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Statements Hello
>>> print('Hello!')
Hello
Iteration and Loops
• A loop repeats a sequence of statements
• A definite loop repeats a sequence of statements a predictable number
of times
0,1,2,3,4

>>> for x in range(5): print('Hello!')


...
Count n Hello
times Hello
Hello
Hello
Hello
Statements
The for Loop
• Python’s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
• Use this syntax when you have only one statement to repeat
for <variable> in range(<number of
times>):
<statement-1>
>>> for x in range(3):
<statement-2>
... print('Hello!')

... print('goodbye')
<statement-n>
...
•Use indentation to format two or Hello!
goodbye
more statements below the loop Hello!
goodbye
header Hello!
goodbye
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1
loop variable

>>> for x in range(5): print(x)


...
0
1 Function to
2 create list
3
4
>>> list(range(5)) # Show as a
list
[0, 1, 2, 3, 4]
Counting from 1 through n
• The expression range(low, high) generates a sequence of ints from low
through high - 1

>>> for x in range(1, 6): print(x)


...
1
2
3
4
5
Counting from n through 1
• The expression range(high, low, step) generates a sequence of ints
from high through low+1.

>>> for x in range(6, 1, -1):


print(x)
...
6
5
4
3
2
Skipping Steps in a Sequence
• The expression range(low, high, step) generates a sequence of ints
starting with low and counting by step until high - 1 is reached or
exceeded

>>> for x in range(1, 6, 2): print(x)


...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
for loop with else
for x in range(1,10,2):
print(x)
else:
print(“out of for loop”)
for loop with break
sum=0
for x in range(10):
n=int(input("Enter even number"))
if n%2!=0:
break
sum=sum+n
print("Sum =",sum)
for loop with continue
sum=0
for x in range(10):
n=int(input("Enter even number"))
if n%2!=0:
continue
sum=sum+n
print("Sum =",sum)
Using a Loop in a Real Problem
• An investor deposits $10,000 with the Get-Rich-Quick agency and
receives a statement predicting the earnings on an annual percentage
rate (APR) of 6% for a period of 5 years. Write a program that prints the
beginning principal and the interest earned for each year of the period.
The program also prints the total amount earned and the final principal.
• Pseudocode:
principal = 10000
rate = .06
term = 5
totalinterest = 0
for each year in term
print principal
interest = principal * rate
print interest
principal = principal + interest
totalinterest = totalinterest + interest
print totalinterest
print principal
for x in range(1,5,-1):
Quiz print(x)
else:
print("i am in else")

output would be

A. 0 B. 1 C. i am in else D. Error
1 2
2 3
3 4
4
While Loop
I. A for loop is used when a program
knows it needs to repeat a block of
code for a certain number of times.
II. A while loop is used when a program
needs to loop until a particular
condition occurs.
While Loop
sum,i=0,0
while i<5:
sum=sum+i
i+=1 #or i=i+1
print("Sum= ",sum)

You might also like