Here’s how to program in Python – Part 4


script, laptop, programming, code

In the previous lesson we used in Python the functions input and print for input and output. In this lesson, we’ll take this further and discuss many ways to adjust the output. Because we often want to show the elements from a list or dictionary in a special way, we also go deeper into how you move through the elements of a list or dictionary.

In the previous lesson, you used the input function to request a number from the user and the print function to display output on the screen. Those exports have remained fairly basic until now. That is why we first look at all kinds of possibilities to adjust the output.

Adjust the output of print

In the previous lesson, we used this command to display a number from a dictionary on the screen:

print (numbers[getal])

But what if you want to show multiple objects on the same line? This can easily be done by passing multiple objects to the print function, separated by a comma. For example, change the last line in the last program of the previous lesson by:

>>> print (number, “equals”, numbers[getal])
1 equals one

All objects that you pass to print are shown separated by a space.

After the objects that you pass to the function print, you can add arguments that change the output of print, namely sep and end. With sep (short for separator) you change the space between objects with another separator, and with end you replace the end of the output (default ‘ n’ which indicates a newline or a newline) with something else. For instance:

>>> print (number, numbers[getal], sep = ‘:’, end = ‘ n n’)
1 one
>>>

On to the argument end assigning two newlines, there is an empty line after the output.

Placeholders

If you want to include multiple objects in one output with print and / or change more complex things about the output, the function comes format useful. In its simplest form, you apply that function to a string in which you enter with {} space. The argument you pass to the function takes its place {}:

>>> ‘You have chosen {}.’. Format (1)
“You chose 1.”

That also works with multiple placeholders:

>>> ‘You have {} chosen between the numbers {} and {}.’. Format (2, 1, 10)
“You chose 2 between the numbers 1 and 10.”

You can also give the placeholders a serial number so that they appear in a different order in the output than the arguments you pass to format:

>>> ‘{1} <= {0} <= {2}'. Format (2, 1, 10)
‘1 <= 2 <= 10'

But often it is clearer if you name the arguments and use those names in the placeholders as well:

>>> ‘{min} <= {number} <= {max}'. format (min = 1, max = 10, number = 2)
‘1 <= 2 <= 10'

Scroll through a list with for

Often you do not want to show one line of output with print, but several, for example for all elements in a list or dictionary. So we need a way to go off all those elements. That is possible with a forloop, as in the following program:

names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]
for name in names:
print (name)

Python goes down each element from the list of names and displays this element with print. If you want to show both the index and the content of each element, use the handy function enumerate:

names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]

for index, name in enumerate (names):
print (‘{}: {}’. format (index, name))

Walk through a dictionary with for

We can with one forloop also run through all elements of a dictionary. Depending on what you are interested in, this can be done in three ways. In the following program we successively show how you go through only the keys, through only the values ​​and through the keys with their corresponding values:

scores = {‘lies’: 6231, ‘bas’: 2, ‘kees’: 18, ‘mireille’: 482, ‘aniek’: 35, ‘bert’: 184}

print (‘Players’)
for player in scores:
print (player)

print ()

print (‘Scores’)
for score in scores.values ​​():
print (score)

print ()

print (‘Players with score’)
for player, score in scores.items ():
print (‘{}: {}’. format (player, score))

You can also request the keys of a dictionary with the function keys, but that’s not necessary here. For instance:

scores.keys ()

Tuples

In the forloop through which we loop through both the index and the value of all elements of a list and the forloop with which we go through both the key and the value of all elements of a dictionary, you see that we have two elements at the same time after the for put: index, name respectively player, score. Two elements with a comma between them form a special data type in Python: a tuple (tuple). You can also add variables of type tuple you do not normally need that often.

List comprehension

Forloops are useful, but a bit cumbersome for more complex operations. Suppose we want to calculate the length of the longest name from a list. Right away forloop we can do that as follows:

names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]

max_length = 0

for name in names:
length = len (name)
if length> max_length:
max_length = length

print (max_length)

This works and is pretty clear, but it could be better. Python has a handy concept for these types of operations: list comprehension. With that we can replace the entire previous calculation with one line:

names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]

print (max ([len(naam) for naam in namen]))

This rule says: for each name in the list of names you calculate the length of the name, and of that you calculate the maximum. The piece [len(naam) for naam in namen] is a concise way of making a list of the lengths of all elements in the list names.

Align and fill text

Then we now go back to the function format. With that we can align text, left, right and center, and fill empty space with arbitrary characters. An example:

>>> ‘{: = ^ 15}’. Format (‘Title’)
‘===== Title =====’

And with something like:

print (‘{name: <6}: {score: 0> 6}’. format (name = ‘kees’, score = 3))

we get as output:

kees: 000003

With ^ we center text, with < we align text to the left and with > we align text to the right. After the alignment mark is the total number of characters that the text may contain. Before the alignment mark can optionally be a character with which we fill empty space. And if we take the arguments of format give a name, that name comes before the colon.

Summary

In this lesson, we’ve seen many ways to adjust the output of print, such as aligning text and filling empty space. We have also seen how to step through the elements of a list or dictionary so that you can display them one by one. Furthermore, we are also on list comprehension is a powerful way to perform loopless calculations on all elements in a list or dictionary. In the next lesson we will talk about input and output again, but with files. We also look at how to catch error messages in your program.

Task 1

Take the following dictionary with scores:

scores = {‘lies’: 6231, ‘bas’: 2, ‘kees’: 18, ‘mireille’: 482, ‘aniek’: 35, ‘bert’: 184}

Use list comprehension to create a list of tuples, each of which consists of the name with a capital letter and the score divided by 100.

Elaboration

>>> scores = {‘lies’: 6231, ‘bas’: 2, ‘kees’: 18, ‘mireille’: 482, ‘aniek’: 35, ‘bert’: 184}

>>> [(speler.capitalize(), score/100) for (speler, score) in scores.items()]
[(‘Lies’, 62.31), (‘Bas’, 0.02), (‘Kees’, 0.18), (‘Mireille’, 4.82), (‘Aniek’, 0.35), (‘Bert’, 1.84)]

With scores.items () we get back a list of tuples of the keys and values ​​of the dictionary. With list comprehension in each of these tuples we adjust the key and value as requested.

Exercise 2

Take the following dictionary with scores:

scores = {‘lies’: 6231, ‘bas’: 2, ‘kees’: 18, ‘mireille’: 482, ‘aniek’: 35, ‘bert’: 184}

With all the knowledge from this lesson you can show these persons and their scores in a table, with the names as the left column and the corresponding scores as the right column. Names should be left aligned and scores should be right with leading zeros. Your code should be able to work with names and scores of any length.

Elaboration

scores = {‘lies’: 6231, ‘bas’: 2, ‘kees’: 18, ‘mireille’: 482, ‘aniek’: 35, ‘bert’: 184}

max_name = max ([len(naam) for naam in scores])

max_num = max ([len(str(score)) for score in scores.values()])

for player, score in scores.items ():

print (‘{player: <{player_width}} {score: 0> {score_width}}’. format (player = player, player_width = max_name + 3, score = score, score_width = max_number))

This is a very compact program in which all knowledge so far and from this lesson comes together. We first calculate the maximum length of a name list comprehension to apply to the keys of the dictionary with scores. Then we do the same for the maximum length we need to display the scores.

Then we run through all players and corresponding scores. We indicate the function format as arguments the player, the maximum length of the player name (adding 3 to separate the columns), the score and the maximum length of the score. In the placeholder for the player we give with < indicates that the player’s name is left-aligned, and with {player_width} then we indicate how many characters long the alignment should be. Then we do the same for the score, but align to the right and supplement the numbers with zeros in front. Note that everything in our code that begins with print comes to one long line.

Cheat sheet

for: a loop that is executed for all elements in a list or dictionary.

list comprehension: a concise way to create a list.

newline: the character n that indicates a new line.

tuple: a series of objects with a comma in between.

.

Recent Articles

Related Stories