3.2 — if statement, for loop, Indexing & Slicing Strings

Flow of execution — functions

Try debugging in thonny for the following examples. (Also try Step out button, when the code inside a function is being executed.)

1# Function definition
2def display_greeting():
3 print("+------------+")
4 print("| Welcome! |")
5 print("+------------+")
6
7display_greeting()
8
9display_greeting()
1def f(x):
2 result = x * x - x - 1
3 return result
4 # OR: return x * x - x - 1
5
6y = f(5)
7print(y)
8
9y = f(10)
10print(y)

1def f():
2 return 2
3
4
5def g():
6 return 3
7
8
9def h():
10 return f() * g()
11
12
13print(h())

Variables and if statement

Variables can be created inside the branches of if statement.

Make sure that all branches have same variable names!

1income = 15000
2
3if income < 12000:
4 tax = 0.0
5else:
6 taxes = income * 15.5 / 100 # Change variable name to tax
7
8print("Your tax is", tax)
Output
NameError: name 'tax' is not defined

Mutually exclusive conditions — chained if-elif-else statement

1income = 20000
2
3if income < 12000:
4 tax = 0.0
5elif income < 30000:
6 tax = income * 15.0 / 100
7elif income < 100000:
8 tax = income * 20.0 / 100
9else:
10 tax = income * 25.0 / 100
11
12print("Your tax is", tax)
  • Mutually exclusive — only one of these blocks will get executed.
  • Order matters! If first of the conditions is True, later conditions are not checked.
  • We can have as many elif’s as you want.
  • The final else part is not required so you may omit it if not needed.

Example

Is there anything wrong in code below?

1temperature = 25
2
3if temperature > 0:
4 print("Cold")
5elif temperature > 20:
6 print("Warm")
7elif temperature > 30:
8 print("Hot")
9else:
10 print("Freezing")
Output
Cold

Order of conditions matters!

1temperature = 25
2
3if temperature > 30:
4 print("Hot")
5elif temperature > 20:
6 print("Warm")
7elif temperature > 0:
8 print("Cold")
9else:
10 print("Freezing")
1temperature = 25
2
3if temperature > 0 and temperature <= 20:
4 print("Cold")
5elif temperature > 20 and temperature <= 30:
6 print("Warm")
7elif temperature > 30:
8 print("Hot")
9else:
10 print("Freezing")

Try “Blood Pressure” problem on Ed Lessons.

if statements can be nested

Examples below are logically equivalent.

Nested if statements

1x = 10
2if x > 0:
3 print("Positive")
4else:
5 if x < 0:
6 print("Negative")
7 else:
8 print("Zero")

Chained if statement

1x = 10
2if x > 0:
3 print("Positive")
4elif x < 0:
5 print("Negative")
6else:
7 print("Zero")
You can use either one, but nested statements can easily become difficult to read.

Correct indentation is essential!

Sometimes, incorrect indentation may not give an error but it may lead to an unexpected program.

1income = 1000
2
3if income < 12000:
4 print("You don't have to pay tax.")
5 tax = 0.0
6else:
7 print("You have to pay tax.")
8tax = income * 15.0 / 100 # this line should be indented
9
10print("Your tax is", tax)

Iteration using for loop

for loop can be used to repeatedly execute a block of code.

1for i in range(5):
2 print("Hello")
Output
Hello
Hello
Hello
Hello
Hello
1for i in range(5):
2 print(i)
Output
0
1
2
3
4

What happens when the for loop is executed?

1for i in range(5):
2 print(i)
  • range(5) will produce a sequence of integers 0,1,2,3,40, 1, 2, 3, 4 in steps.
  • for loop allows us to iterate i.e. “go over” that sequence, a number at a time
    • In each step of the loop, variable i gets a value from the sequence
  • We can have any valid variable name, other than i if we want.

Try step-by-step execution of the examples above!

range() function takes up to 3 arguments

range(end): produces sequence 0, 1, 2, ..., end-1

range(start, end): produces sequence start, start+1, ..., end-1

range(start, end, step):

  • if step > 0, produces sequence start, start+step, ..., N where N < end
  • if step < 0, produces sequence start, start+step, ..., N where N > end

Examples of range()

1# 0, 1, 2, ..., 9
2for i in range(10):
3 print(i)
4
5# 1, 2, ..., 10
6for i in range(1, 11):
7 print(i)
8
9# 0, 2, 4, ..., 18
10for i in range(0, 20, 2):
11 print(i)
1# 10, 15, 20, 25, ..., 95
2for i in range(10, 100, 5):
3 print(i)
4
5# 10, 9, 8, ..., 1
6for i in range(10, 0, -1):
7 print(i)

Exercise

Compute sum of first N numbers.

1N = 50
2
3total = 0
4for num in range(1, N+1):
5 total = total + num
6
7print(total)

Try “Harmonic sum” problem on Ed Lessons.

Indexing & Slicing Strings

Recall that a string is a sequence of characters.

Each character, therefore, has a position or an index.

Index starts with zero. For example, for the string "Hello":

0
1
2
3
4
H
e
l
l
o

Indices must be integers and cannot be float.

Python also allows negative indices, which go from right to left:

0
1
2
3
4
H
e
l
l
o
-5
-4
-3
-2
-1

For any string s,

  • valid positive index values are from 0 to len(s)-1.
  • valid negative index values are from -len(s) to -1.

Square brackets [] are used to get the letter in a string at a given index.

1>>> message = "Hello"
2>>> message[0] # first letter
3'H'
4>>> message[1] # second letter
5'e'
6>>> message[4] # fifth letter, the last one in the string
7'o'

0
1
2
3
4
H
e
l
l
o
-5
-4
-3
-2
-1
1>>> message = "Hello"
2>>> message[5] # there is no letter at this index
3IndexError: string index out of range
4>>> message[-1]
5'o'
6>>> message[-5]
7'H'
8>>> message[-6] # there is no letter at this index
9IndexError: string index out of range
10>>> message[1.0]
11TypeError: string indices must be integers

Traversing a string

We can use for loop with range() function to go over a string letter-by-letter.

1message = "Hello"
2
3for i in range(len(message)):
4 print(i, message[i])
Output
0 H
1 e
2 l
3 l
4 o

Another example:

1letters = "bcmrst"
2
3for i in range(len(letters)):
4 print(letters[i] + "ake")

Try “Remove spaces from a string” problem on Ed Lessons.

Using slice to get substrings

Using slice notation we can get parts of a string: string[start:end:step].
start, end, step values must be integers and work similar to range() function.

0
1
2
3
4
5
6
7
8
p
i
n
e
a
p
p
l
e
-9
-8
-7
-6
-5
-4
-3
-2
-1
1>>> fruit = "pineapple"
2
3>>> fruit[4:7] # letters at indices 4, 5, 6
4'app'
5>>> fruit[2:7:2] # letters at indices 2, 4, 6
6'nap'

0
1
2
3
4
5
6
7
8
p
i
n
e
a
p
p
l
e
-9
-8
-7
-6
-5
-4
-3
-2
-1
1>>> fruit[:4] # same as fruit[0:4]
2'pine'
3>>> fruit[4:] # same as fruit[4:len(fruit)]
4'apple'
5
6>>> fruit[-5:] # from index -5 to the end of string
7'apple'
8>>> fruit[-5:-2] # letters at indices -5, -4, -3
9'app'

0
1
2
3
4
5
6
7
8
p
i
n
e
a
p
p
l
e
-9
-8
-7
-6
-5
-4
-3
-2
-1
1# Negative step size of -1 means go from
2# right to left, i.e. in reverse order
3>>> fruit[-4:-8:-1] # letters at -4, -5, -6, -7
4'paen'
5
6# Omitting start and end mean select whole string,
7# but step size -1 means right to left i.e. reverse order
8>>> fruit[::-1]
9'elppaenip'