0% found this document useful (0 votes)
14 views20 pages

2 - Branching and Iteration

The document covers key programming concepts including string manipulation, branching, conditionals, and loops in Python. It explains the syntax for strings, input/output functions, comparison and logic operators, and control flow using if statements and loops. Additionally, it provides examples and in-class questions to reinforce understanding of these topics.

Uploaded by

ghouti.haoulia
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)
14 views20 pages

2 - Branching and Iteration

The document covers key programming concepts including string manipulation, branching, conditionals, and loops in Python. It explains the syntax for strings, input/output functions, comparison and logic operators, and control flow using if statements and loops. Additionally, it provides examples and in-class questions to reinforce understanding of these topics.

Uploaded by

ghouti.haoulia
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/ 20

12/12/2024

BRANCHING,
ITERATION

a1
a2

LAST TIME
 syntax and semantics
 scalar objects
 simple operations
 expressions, variables and values

1
Diapositive 2

a1 amina; 05/10/2024

a2 amina; 05/10/2024
12/12/2024

TODAY
 string object type
 branching and conditionals
 indentation
 iteration and loops

STRINGS
 letters, special characters, spaces, digits
 enclose in quotation marks or single quotes
 hi = "hello there"
 concatenate strings
 name = "ana"

 greet = hi + name

 greeting = hi + " " + name


 do some operations on a string as defined in Python docs
 silly = hi + " " + name * 3

2
12/12/2024

Example
 ###################
 ## EXAMPLE: strings
 ###################
 #hi = "hello there"
 #name = "ana"
 #greet = hi + name
 #print(greet)
 #greeting = hi + " " + name
 #print(greeting)
 #silly = hi + (" " + name)*3
 #print(silly)

INPUT/OUTPUT: print
 used to output stuff to console
 keyword is print

x = 1
print(x)
x_str = str(x)

print("my fav num is", x, ".", "x =", x)


print("my fav num is " + x_str + ". " + "x = " + x_str)

3
12/12/2024

Example
 ####################
 ## EXAMPLE: output
 ####################
 #x = 1
 #print(x)
 #x_str = str(x)
 #print("my fav number is", x, ".", "x=", x)
 #print("my fav number is", x_str + "." + "x=" + x_str)
 #print("my fav number is" + x_str + "." + "x=" + x_str)

INPUT/OUTPUT: input("")
 prints whatever is in the quotes
 user types in something and hits enter
 binds that value to a variable
text = input("Type anything... ")
print(5*text)

 input gives you a string so must cast if working


with numbers
num = int(input("Type a number... "))
print(5*num)

4
12/12/2024

COMPARISON OPERATORS ON
int, float, string
 i and j are variable names
 comparisons below evaluate to a Boolean
i > j
i >= j
i < j
i <= j
i == j  equality test, True if i is the same as j
i != j  inequality test, True if i not the same as j

LOGIC OPERATORS ON
bools
 a and b are variable names (with Boolean values)
not a  True if a is False
False if a is True
a and b  True if both are True
a or b  True if either or both are True
A B A and B A or B
True True True True
True False False True
False True False True
False False False False

5
12/12/2024

COMPARISON EXAMPLE
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)

derive = True
drink = False
both = drink and derive
print(both)

If right clear, If right blocked, If right and If right , front,


go right go forward front blocked, left blocked,
go left go back

6
12/12/2024

If right clear, If right blocked, If right and If right , front,


go right go forward front blocked, left blocked,
go left go back

7
12/12/2024

CONTROL FLOW - BRANCHING

if <condition>: if <condition>:
<expression> <expression>
<expression> <expression>
... ...
elif <condition>:
if <condition>: <expression>
<expression> <expression>
<expression> ...
... else:
else: <expression>
<expression> <expression>
<expression> ...
...

 <condition> has a value True or False


 evaluate expressions in that block if <condition> is True

INDENTATION
 matters in Python
 how you denote blocks of code
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:

print("x and
print("x and yy are
are equal"
equal")
if y !=
if y != 0 0:
:
print("therefore, xx // yy is",
print("therefore, is", x/y
x/y)
elif x < y:
print("x is smaller")
print("x is smaller"

print("y is smaller"
else:
print("y is smaller")

print("thanks!")

8
12/12/2024

= vs == INDENTATION
 matters in Python
 how you denote blocks of code
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")

9
12/12/2024

Legend of Zelda –
Lost Woods
keep going right,
takes you back to this
same screen, stuck in
a loop
Image Courtesy Nintendo, All Rights Reserved. This content is excluded from our
Creative Commons license. For more information, see http://ocw.mit.edu/help/faq-fair-
use/.
if <exit right>:
<set background to woods_background>
<set background to woods_background
if <exit right>
if <exit right>: :
<set background to woods_background>
<set background to woods_background
if <exit right>
if <exit right>:
<set background to woods_background>
set background to woods_background
and so on and on and on..
and so on and on and on...
else
else:
<set background to exit_background>
set background to exit_background
else
else:
<set background to exit_background>
<set background to exit_background
else:
<set background to exit_background>
_background
exit

10
12/12/2024

Legend of Zelda –
Lost Woods
keep going right,
takes you back to this
same screen, stuck in
a loop

while <exit right>:


<set background to woods_background >
<set background to exit_background>

11
12/12/2024

CONTROL FLOW:
while LOOPS
while <condition>:
<expression>
<expression>
...
 <condition> evaluates to a Boolean
if <condition> is True, do all the steps inside the
while code block
 check <condition> again
 repeat until <condition> is False

while LOOP EXAMPLE


You are in the Lost Forest.
************
************

************
************
Go left or right?

PROGRAM:

n = input("You're in the Lost Forest. Go left or right? ")


while n == "right":
n = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")

12
12/12/2024

CONTROL FLOW:
while and for LOOPS
 iterate through numbers in a sequence

# more complicated with while loop


n = 0
while n < 5:
print(n)
n = n+1

# shortcut with for loop


for n in range(5):
print(n)

CONTROL FLOW: for LOOPS


for <variable> in range(<some_num>):
<expression>
<expression>
...

 each time through the loop, <variable> takes a value


 first time, <variable> starts at the smallest value
 next time, <variable> gets the prev value + 1
 etc.

13
12/12/2024

range(start,stop,step)
 default values are start = 0 and step = 1 and optional
 loop until value is stop - 1

mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)

mysum = 0
for i in range(5, 11, 2):
mysum += i
print(mysum)

14
12/12/2024

break STATEMENT
 immediately exits whatever loop it is in
 skips remaining expressions in code block
 exits only innermost loop!

while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>

15
12/12/2024

break STATEMENT
mysum = 0
for i in range(5, 11, 2):
mysum +=
= i
if mysum == 5:
5
break
mysum += 1
print(mysum)

 what happens in this program?

16
12/12/2024

In-Class Questions
Lecture 2

Strings

What is the value of variable `u` from the code below?

once = "umbr"
repeat = "ella"
u = once + (repeat+" ")*4

o umbrella ella ella ella


o umbrellaellaellaella
o umbrella
o umbrella4

In-Class Questions
Comparisons

What does the code below print?

pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and derive
print(both)

o False then False


o False then True
o True then False
o True then True

17
12/12/2024

In-Class Questions
Branching

What’s printed when x = 0 and y = 5?

x = float(input("Enter a number for x: "))


y = float(input("Enter a number for y: "))
if x == y:
if y != 0:
print("x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")

o x is smaller
o y is smaller
o x / y is 0.0

In-Class Questions
While Loops

In the code below from Lecture 2, what is printed when you type
“Right”?

n = input("You're in the Lost Forest. Go left or right? ")


while n == "right":
n = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")

o You’re in the Lost Forest. Go left or right?


o You got out of the Lost Forest!

18
12/12/2024

In-Class Questions
For Loops

What is printed when the below code is run?

mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)

o 5
o 6
o 21
o 24

19

You might also like