Loops
-
types of loops:
while, for
-
Other loop statements:
break, continue
-
The phonebook of Rick
For loops
Syntax
for element in iterable:
statement1
statement2
…
rest of code…
Print each element separately with a descriptive text:
current element: rick
current element: c
current element: 137
Slide 48
Iteration can also be done on a string
Give me R
Give me i
Give me c
Give me k
What did we get? Rick
Put zeros instead each even element
Slide 55
Infinite for loop
# Do not run this code
x=[1]
for a in x:
x.append(1)
print(x)
Avoid changing the list on which you iterate! (may cause all kind of problem, including infinite loops)
Example #3: concatenate all characters in a matrix into a single string
Try this with Python Tutor
Slide 56
while loops
Syntax
while expression: ## expression is either True or False
statement1
statement2
…
rest of code…
Print numbers from 1 to 7 with a descriptive text:
current number: 1
current number: 2
current number: 3
current number: 4
current number: 5
current number: 6
current number: 7
Infinite loop
# Do not run this code
i = 1
while i < 137:
print(i)
break and continue statements
break statement – breaking loops
First negative number is -6
done!
continue statement – Skipping loops
1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29
Loops - for or while?
In most cases it is more natural to use for
In some cases it is better to use while
Self learning
Exercise 2: Multiplication chart
print the multiplicaion chart.
hint: try this code first.
for letter in ["a", "b", "c"]:
print(letter, end="\t")
Solution
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Exercise 3: Unique list of numbers
Write a function that receives a list of number, and returns a list where each number from the original list appears exactly once.
[1,3,3,1,7,7,7,1,3] \(\rightarrow\) [1,3,7]
Exercise 4: The phone book of Rick
We want to develop an application for managing the Contacts of Ricks
It will contain a database
A list of contacts
Each contact is a list in the format [name, phone]
Functionality
Find contact(s) by full name or prefix
Add contact
Remove contact
Retrieve the number for a given person
name = 'rick' ## Change the value here
### Write your code here
if found:
print("Name:", name , "Phone:", phone)
else:
print("Cannot find", name , "in contact list.")
Solution
Cannot find rick in contact list.
Solution
The contact rick was deleted
Ignore character case (aka, case insensitive).
Name: rick c-138 Phone: 8888
Name: rick c-139 Phone: 9999
|