You are on page 1of 24

Conditionals and Iteration

in Python

•1
Frequently syntax errors
Notice a single space at the start of the line

Notice there is no indentation in print

Notice IF instead of if

Notice If instead of if

Notice three commas instead of two

\ can be used to join line (words) a word (e.g., It’s fine

•2
Conditional execution (from previous lecture)
condition

Indentation is important
Use a single Tab or four
spaces for each indentation
level

•3
•4
•5
Nested Conditionals

IF
(outer IF condition)

Nested IF
(inner IF condition)

If the outer IF condition is true, the inner (nested)


IF part will be ignored
Note the INDENTATION

•6
•7
•8
•9
Roots of Quadratic Equations

Break the problem into pieces


1. Input (a,b,c)
2. Output (x)
1. two
2. Complex
3. One

•10
Roots of Quadratic Equations (Python Code)

•11
x2-4x+4=0

x2-2x+4=0

•12
If with or and and

•13
Iteration

 Start with a test


 If evaluates to True, then execute loop
body once, and go back to reevaluate the
test.
 Repeat until test evaluates to False, after
which code following iteration statement
is executed.

•14
Iteration (while)

n=input("Enter a number") >>>


while n>0: Enter a number5
print n 5
4
n=n-1 3
print 'GOOD bye' 2
1
GOOD bye

You can almost read the while statement as if it were English. It


means, while n is greater than 0, continue displaying the value of n
and then reducing the value of n by 1. When you get to 0, display
the word “Good Bye”

•15
This code squares the value of x by repetitive addition

•16
The for Loop

The for…in statement is an other statement which iterates


over a sequence of objects , i.e., go through each item in a sequence.

for variable_name in range([start ], stop,[step ]):


in is used for membership tests

for x in range(0,10,1)
for x in range(0,10) Similar to DO loop in Fortran
for x in range(10) •17
The for Loop

•18
The for Loop
>>> for x in range(0,10,1): 0
print x 1
2
>>> for x in range(0,10): 3
print x 4
5
>>> for x in range(10): 6
print x 7
8
9

The break statement


is used to break out of
a loop statement

•19
The for Loop

The continue statement is used to tell python to skip the rest


of the statements in the current loop block and to continue to
the next iteration of the loop
•20
This part
is skipped

•21
The for Loop Python Code for even/odd
numbers from 0 to 10

•22
10

𝑥 = 1 + 2 + 3 + 4 + 5 + 6 … 10
𝑥=1
10

𝑥 2 = 1 + 22 + 32 + 42 + 52 + 62 …
𝑥=1

•23
Good Programming
Turn off your other activities in your mind when
you Turn on a computer for programming
Hypnotize a computer

•24

You might also like