Tutorial 3 - Python - / Loops, lists and dictionaries /

* Use of lists and loops « while »

Exercise 1

Considering the following list:

['Michel','Marc','Jessy','Anna', Max','Alexander','Louisa']

Write a script that displays each of these names with the corresponding number of characters.

Exercise 2

Let the following 2 lists:

t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

t2 = ['January','February','March','April','May','June','July','August','September','October','November','December']

Write a small program that creates a new « t3 » list. This must contain all the elements of the two lists alternating them, in such a way that each month name is followed by the corresponding number of days: ['January',31,'February',28,'March',31, etc...].

Then, display this list.

Note: mylist.append("my_text") --> add the string "my_text" as a new item in the "mylist" list

Exercise 3

Write a program that looks for the largest item in a given list. For example, if applied to the list [32, 5, 12, 8, 3, 75, 2, 15], this program should display :

"the largest item on this list has the value 75."

Exercise 4

Write a program that analyzes one by one all the items in a list of numbers (for example, from the previous exercise) to generate two new lists. One will contain only the even numbers from the initial list, and the other will contain the odd numbers. For example, if the initial list is from the previous exercise, the program will build an even list that will contain [32, 12, 8, 2], and an odd list that will contain [5, 3, 75, 15].

* Use of « for »

Exercise 1

Eight ducks are called respectively: Jack, Kack, Lack, Mack, Nack, Oack, Pack and Qack.

Write a script that displays all these names from the following two strings :

prefixes ='JKLMNOP' and suffix ='ack'

Using an instruction « for ... in... » Your script should only have 3-4 lines.

Exercise 2

Write a « capital() » function that returns "true" if the argument passed is a capital letter.

* Use of dictionaries

Exercise 1

Write a function that have a dictionnary as parameter and return a new dictionnary with keys and values inverted (assuming the input dictionary does not contain several identical values).

Take as an example the dictionary (key -> value):

Computer -> Ordinateur

Mouse -> Souris

Keyboard -> Clavier

Hard disk -> Disque dur

Screen -> Ecran