Luiss
Libera Università Internazionale
degli Studi Sociali Guido Carli
Digital Transformation
and Emerging
Technologies
Coding Lab 5
Topics
• For
• While
Recall from previous
Iterative loops class
The iteration (or “loop”) is a control structure that allows you to repeatedly execute a
sequence of instructions until certain conditions are determined:
• for: iterates a certain number of times based on the elements of a sequence
• while: iterates as long as a certain condition is true
3
Recall from previous
For class
The for construct allows you to iterate
over a sequence, according to the
end of yes
following syntax: sequence
reached?
for var in sequence: next No
item
istructions
instructions
The instructions, indented by 4 spaces, are
executed for all elements of the sequence.
4
Recall from previous
While class
The while construct allows you to iterate as
long as the condition is True, according to
the following syntax : False
condition
while condition: True
instructions
instructions
A loop becomes an infinite loop if the
condition never becomes False (in some
cases an infinite loop can be useful, e.g.
server always active).
5
Exercise 1
Define the function median that has as parameter an odd number n and that takes
as input the same number n of integers returning the median.
• Theory recall: The median of a finite list of numbers is the "middle" number,
when those numbers are listed in order from smallest to greatest
• For example:
• if n=5 and as input I have 23, 45, 81, 10, 5 then it returns 23
Solution
Exercise 2
• Define the function string_reverse that has as parameter a string
and returns it in reverse order.
• For example, if as input string I have "hello" then it returns
"olleh"
Solution
Exercise 3
• Define the function count_num_characters that has as
parameter a number n and that takes as input the same number n
of strings returning the sum of the characters.
• For example, if n=3 and as input I have “hello”, “home”, “Luiss”
then it returns 14.
Solution
Exercise 4
• Define the function count_4 that taken a list as parameter return
the number of words that have exactly four characters. If the list
is empty return 0.
Solution