Introduction to Python and IPython using Jupyter

Iterations¶

Sometimes we want to iterate over elements of a list, set, string or such in order to perfor operations with each element. This is done using a for statement, which looks like this

for element in list_name:
    perform_first_ operation_with_element
    perform_another_ operation_with_element_or_result_of_previous_operation
Note: There is special horizontal spacing below the line that starts with for and all lines below it are aligned in the for statement.

How to write a for statement:¶

  1. Start with the word for
  1. In the same line define a name for the variable you will use in the iterations. In the example we used element, but we coudl have named it i, j, t, n, or any other name. As before it is useful to choose a name that will let you know what it is.
  1. Write the word in followed by the name of the list, set, etc. from which you will take elements to perfrom the operations.
  1. Put a colon : at the end of that line.
  1. In a new line, which should have a tab or 2 or 4 spaces, write the code for first operation you want to perform using the element.
  1. Continue adding lines that start with the same horizontal spacing as in 5., i.e. a tab or 2 or 4 spaces.
  1. To finish the for statement, just start a line without the same horizontal spacing

Example¶

Let's iterate over the set of capitals and print a message saying "XXX is a capital of a country." where we will replace XXX with the name of the capital.

In [1]:
set_of_capitals = {'Washington, D.C.', 'Bogotá', 'Berlin'}

# Next line starts for statement
for capital in set_of_capitals:
    print(capital, " is a capital of a country.")
# For statment ends
Bogotá  is a capital of a country.
Washington, D.C.  is a capital of a country.
Berlin  is a capital of a country.

Example - Iteration over dictionaries¶

Let's iterate over our top_bands dictionary and print a message that says X is a member of Y.

In [2]:
top_bands = {'The Beatles':{'John':["vocals", "guitars", "keyboards", 'harmonica', "bass", 
                                    "(1960–1969; died 1980)"],
                            'Paul':["vocals", 'bass', 'guitars', 'keyboards', 'drums', "(1960–1970)"],
                            'George':["guitars", 'vocals', 'sitar', 'keyboards', 'bass', 
                                      "(1960–1970; died 2001)"],
                            'Ringo':["drums", 'percussion', 'vocals', "(1962–1970)"]
                           },
             'The Rolling Stones':{'Mick':["lead and backing vocals", 'harmonica', 'rhythm guitar', 
                                           'percussion', 'keyboards', 'bass guitar', "(1962–present)"],
                                   'Keith':['rhythm and lead guitars', 'bass guitar', 'keyboards', 
                                            'percussion', 'backing and lead vocals', '(1962–present)'],
                                   'Ronnie':['lead and rhythm guitars', 'bass guitar', 'backing vocals', 
                                             '(1975–present)']
                                  }
            }
In [3]:
for key in top_bands:
    for key2 in top_bands[key]:
        print(key2, "is a member of", key)
John is a member of The Beatles
Paul is a member of The Beatles
George is a member of The Beatles
Ringo is a member of The Beatles
Mick is a member of The Rolling Stones
Keith is a member of The Rolling Stones
Ronnie is a member of The Rolling Stones

Conditionals¶

Sometimes we want to execute code or perform a computation if a certain condition holds. This is done with an if, elif, else statement, which looks like this

if condition1:
    do_something
elif condition2:
    do_something_different
else:
    do_something_else
Note: There is special horizontal spacing separating each condition that is tested.

How to write an if-elif-else statement:¶

  1. Start with the word if
  1. On the same line put the condition you want to be checked condition1
  1. End the line with a colon :
  1. On the next line add horizontal spacing (tab, 2 or 4 spaces)
  1. On the same line write the code that will perform the computation you want to do if condition1 is true
  1. Continue adding all the code you want to perform if condition1 is true on new lines with the same horizontal spacing
  1. If you have other conditions you want to test, start a new line without horizontal spacing and the words elif
  1. Continue after elif with the same steps as in 2-6
  1. If you want to perform computation for any case not covered by all the previous conditions, start a new line without horizontal spacing with the word else and follow steps 2-6 again.
  1. To finish the if statement, just start a line without the same horizontal spacing

Example¶

Let's use our knowledge of conditionals to iterate over our list of cities, but only print the message "XXX is a capital of a country." where we will replace XXX with the name of the city if it is a capital. Otherwise, we will print the message "XXX is not a capital of a country."

In [4]:
set_of_cities = {'Washington, D.C.', 'Bogotá', 'Berlin', 'Dallas'}
for city in set_of_cities:
    if city in set_of_capitals:
        print(city, "is a capital of a country")
    else:
        print(city, "is not a capital of a country")
Bogotá is a capital of a country
Washington, D.C. is a capital of a country
Berlin is a capital of a country
Dallas is not a capital of a country

Conditional Iterations¶

Sometimes we want to perform some computations, especially iterations, only while some condition is true. This is especially useful for repetitive and humerical computations. To do this we use a while statement, which looks like this

while condition_is_true:
    perform_computations
Note: There is special horizontal spacing below the line that starts with while and all lines below it are aligned in the while statement.
Careful: If the condition is always true, the computer will continue iterating until the end of time. So you always want to put a condition to force it to stop after certain number of computations

How to write a while statement:¶

  1. Start with the word while
  1. On the same line put the condition you want to hold while performing computations condition_is_true
  1. End the line with a colon :
  1. On the next line add horizontal spacing (tab, 2 or 4 spaces)
  1. On the same line write the code that will perform the computation you want to do while condition_is_true holds
  1. To finish the while statement, just start a line without the same horizontal spacing

Example¶

Let's find the smallest integer $n$ such that $n^2>100$.

To do this, let's add 1 to a variable named n, which starts at 0. And let's do this until $n^2>100$.

In [5]:
n = 0
while n**2<=100:
    n = n + 1
print(n)
11

The smallest integer such that $n^2>100$ is {{n}}

Exercises
¶

Exercise 1: Use your dictionary artist_best_song to print messages that say "X song is the best song of Y".
Exercise 2: Use your dictionaries artist_best_song and favorite_song_artist to check whether an artist's best song is also one of your favorite songs. If so, print messages that say "X is my favorite song of artist Y, and it is also his/her best song", where the message will correctly specify her or his depending on the gender of the artist. If it is not, it should print a message saying so also. (Hint: You may want to add more information to the dictionary, so it records the gender, or create a gender_artist that keep for each artist her/his gender)
Exercise 3: Use the dictionary top_bands to print messages that say for each member the band he belongs to, then another message that says the instruments they play, then a message that says the years they beloged to the band, and finally a message that says whether they are alive or not.
Exercise 4: Find the largest integer $n$ such that $n^2<200$ and $n$ is even.

Notebook written by Ömer Özak for his students in Economics at Southern Methodist University. Feel free to use, distribute, or contribute.