Skip to content

Latest commit

 

History

History
278 lines (211 loc) · 6.45 KB

3.loops.adoc

File metadata and controls

278 lines (211 loc) · 6.45 KB

Loops and Iterator

Learning Material

We will now discuss an element more complex and obscure than the conditions, I have named: the loops!

Loops are an essential element in programming. They allow instructions to be repeated a number of times. They also help to avoid repetition. Let’s say you want to display the numbers from 1 to 10. Without the loops, we should write something like this:

print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10)

We could do copy and paste, but it’s not clean and a good developer never repeats himself. Be D.R.Y, think D.R.Y.

While

The while loop repeats the sequence of actions several times until the condition has the value False. The condition is given before the loop body and is checked before each execution of the loop body. As a general rule, the while loop is used when it is impossible to determine the exact number of iterations of the loop in advance.

The syntax of the while loop in the simplest case looks like this:

while expression:
    block of statements

Example if you want to display the numbers from 1 to 10.

i = 1
while i <= 10:
    print(i)
    i += 1

In python, the equivalent of the loop do…​while does not exist. The loop do…​while does not know in advance how many times it will iterate but it will run at least once. On the other hand, it is very easy to create the same behaviour.

while True:
    n = int(input("give a integer > 0 : "))
    print("You have provided", n)
    if n > 0:
        break
print("correct answer")

For

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Unlike the for keyword in other programming language, it works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

With the strings

for x in "banana":
  print(x)

Range

The range function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

for i in range(10):
    print(i)
## Output: 0 .. 9

for i in range(2 ** 3):
    print(i)
## Output: 0 .. 7

With a point starting specified :

for i in range(4,10):
    print(i)
## Output: 4 .. 9

With steps :

for i in range(0,10,2):
    print(i)
## Output: 0 2 4 6 8

Continue

The instruction continue allows you to move on to the next loop turn early. It continues on the next iteration of the loop.

for i in range(4):
    print("Start of iteration", i)
    print("Hello")
    if i < 2:
        continue
    print("End of iteration", i)
print("After the loop")

Break

The instruction break is used to interrupt the execution of a loop (while or for). It exits the loop and proceeds to the next instruction.

for i in range(10):
    print("Start of iteration", i)
    print("Hello")
    if i == 2:
        break
    print("End of iteration", i)
print("After the loop")

Else

Loop instructions have an "else" clause. It is executed when the loop ends with exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is interrupted by a break instruction. The folowing loop illustrates the difference between a while and range up to 10:

i = 1
while i < 10:
    print(i)
    i += 1
else:
    print('Finally finished!, i =', i)

## Output
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# Finally finished!, i = 10

for i in range(1, 10):
  print(i)
else:
  print("Finally finished!, i =", i)

## Output
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# Finally finished!, i = 9

Exercises

1. Display all employee in the employees list.

employees = ["Merouane", "Koen", "Jonas", "Hendrik", "Sophie", "Ferdi", "Ignace", "Axel", "Jeroen", "Adrien"]

2. Display only those whose first name begins with the letter J

3. Display integers from 0 to 23 not included, using a for loop

and the range() instruction.

4. Use the break instruction to interrupt a for loop to

display integers from 1 to 10 included, when the loop variable is 7

5. Use the continue instruction to modify a for loop to

display intergers from 1 to 10 included, when the loop variable is 7

6. Follow the instructions :

list_of_num = [23, 18, 64, 35, 92]

  • sort and display the list;

  • add item 43 to the list and display the list;

  • reverse and display the list;

  • display the index of element 35;

  • remove item 35 and display the list;

  • display the sub-list of the 2nd to 3rd element;

  • display the sub-list from the beginning to the 2nd element;

  • display the sub-list of the 3rd element at the end of the list;

  • display the last element using a negative indication.

Note that some list methods do not return anything.

7.a Write an algorithm that asks the user to enter a number. Then

make sure that your program displays all the numbers up to the number, for example, if the user enters the number 3, then your program will display something like this: 0,1,2,3

7.b Now make sure that your program displays all the numbers down to

0, for the same example, your program will display something like this: 3,2,1,0

8.The price is right ! Create a variable that will contain the

number to be found. Then create an algorithm that will ask the user to find this price. If the user enters a number that is too high, he will have the sentence: It’s less. If he enters a number that is too low, he will have the sentence: It’s more. If the user finds the right price he will have the sentence: Well done, you won.

9. Display all employees with the sentence NAME is an employee.

all_employees = [["David", "John", "Gabe", "Alix", "Anthony"], ["Julie", "Jess", "Mustafa", "Claudius", "Sonja"]]

10. Display all elements. If the element is part of the first table

display - Java is a compiled language - and if the element is part of the second language, display - PHP is an interpreted language …

languages = [["C", "Java", "COBOL" ], ["PHP", "Python", "Javascript"]]