CT04a
Format output to meet requirements
Format output suitable for the end user
CT04a
In a previous lesson you learned how to iterate over a list data structure.
This allows you to look at, print or otherwise interact with each item in the list individually, one after another.
This program would print each item in the list one at a time.
order = ["C","C","H","T","T","C","H","H","T","C","H"]
for sandwich in order:
print(sandwich)
CT04a
Open 'Activity1_Student.py' in Thonny.
Run the code
Explain what happens when you run the code.
# -- Global variables --
numCheese = 0
numHam = 0
numTuna = 0
order = ["C","C","H","T","T",
"C","H","H","T","C","H"]
# -- Main Program --
for sandwich in order:
if sandwich == "C":
numCheese = numCheese + 1
elif sandwich == "H":
numHam = numHam + 1
else:
numTuna = numTuna + 1
print("Cheese = ", numCheese)
print("Ham = ", numHam)
print("Tuna = ", numTuna)
CT04a
The code snippet you’ve just seen is part of a larger program.
This program is designed to count up the orders for sandwich fillings and output the totals so that the right number can be prepared.
The program could be extended to allow new orders to be added.
# -- Global variables --
numCheese = 0
numHam = 0
numTuna = 0
order = ["C","C","H","T","T",
"C","H","H","T","C","H"]
# -- Main Program --
for sandwich in order:
if sandwich == "C":
numCheese = numCheese + 1
elif sandwich == "H":
numHam = numHam + 1
else:
numTuna = numTuna + 1
print("Cheese = ", numCheese)
print("Ham = ", numHam)
print("Tuna = ", numTuna)
CT04a
For this small exercise, this is usable. However, if this program was much larger and worked with more data, this output would not be very user-friendly.
When working with data in a text-based computer program, you should consider how to output the results so that they are easy to read and understand.
This is the output of the previous program.
Cheese = 4
Ham = 4
Tuna = 3
CT04a
The most common way of presenting lots of information for a person to read is in a table.
Tables have rows and columns.
In industry, the standard width of an output is 80 columns wide. This is equivalent to a width of 80 characters.
Programmers can therefore organise the data output from their programs into tables with a maximum width of 80 characters.
CT04a
In Python you can use the <string>.format() function to modify the look of a string when it is output.
The format function allows programmers to substitute variables into strings and add positional formatting. It makes output more readable and user friendly.
Recall that the print() function displays one line of text to the screen (and also starts a new line).
Combined, these two functions can produce rows of output text that are formatted in the layout needed.
CT04a
Format works by putting placeholders into a string, defined by { }, and calling the <string>.format() function.
You can do this with other data types and with multiple placeholders, like so:
print("Alice has {} cupcakes.".format(5))
Outputs:
Alice has 5 cupcakes.
print("Bob has {} {}.".format(2, "kittens."))
Outputs:
Bob has 2 kittens.
CT04a
You can also specify which element you want to include in the place holder using an index value.
You can also add variable names to the items in the format function so that these are used in the placeholder, like so:
print("Carl the {1} has a pet {0}!".format("llama", "python"))
Predict what the code will output:
Carl the python has a pet llama!
print("Elaine submitted {0} {a}.".format(10, a = "assignments"))
Outputs:
Elaine submitted 10 assignments
CT04a
You can also specify the data type of a value, like so:
print("Danny ate £{0:.2f} worth of chocolate!".format(15))
Predict what the code will output:
Danny ate £15.00 worth of chocolate!
{0:.2f}
Part of the keyword – means apply format to the item on the left
Selects first item in format
Convert to float
Limit to two decimal places
CT04a
layout = "The score is {}"
print (layout.format (score))
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "My name is {} and my score is {}"
print (layout.format (myname, score))
layout = "All data: {2}, {1}, {0}"
print (layout.format (thePrice, myname, score))
layout = "Another: { {1:.3f} {0:.0f} {q}}"
print (layout.format (thePrice, score, q="decimals"))
layout = "My name is {}. \nScore is {}. \nPrice is £{:.2f})"
print (layout.format (myName, score, thePrice))
layout = "My name is {}. \nScore is {} and my score is {})"
print (layout.format (score, myName))
CT04a
layout = "The score is {}"
print (layout.format (score))
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
The score is 10876
CT04a
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "My name is {} and my score is {}"
print (layout.format (myname, score))
My name is Frankie and my score is 10876
CT04a
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "All data: {2}, {1}, {0}"
print (layout.format (thePrice, myname, score))
All data: 10876, Frankie, 23.567
CT04a
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "Another: { {1:.3f} {0:.0f} {q}}"
print (layout.format (thePrice, score, q="decimals"))
Another: 10876.000 24 decimals
CT04a
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "My name is {}. \nScore is {}. \nPrice is £{:.2f})"
print (layout.format (myName, score, thePrice))
My name is Frankie.
Score is 10876.
Price is £23.57
CT04a
Complete the table to predict the output based on the use of the <string>.format() function. Use these variables for each of the statements
thePrice = 23.567
myName = "Frankie"
score = 10876
layout = ""
layout = "My name is {}. \nScore is {} and my score is {})"
print (layout.format (score, myName))
My name is 10876 and my score is Frankie
CT04a
Format can also be used to set field widths.
This adds additional empty characters and is known as padding.
This will enable you to create tables of data in the output.
This code creates a column 6 characters wide, using blank spaces to pad the width.
You should plan your output on paper first so that you know how wide to make your columns.
Square paper helps with this exercise.
In Python this looks like
"{:6}"
CT04a
The format function includes some additional tools to help improve the look of your columns.
You can include symbols that indicates the alignment of the content of a column.
^ means centre justify
"{:^8.2f}"
"{:<6}"
< means left justify
> means right justify
"{:>10}"
CT04a
You can combine padding and alignment to create columns.
What will this code layout produce?
Year: 1973 Reading:10.247 Name: Rover
year = 1973
reading = 10.2468
name = "Rover"
layout = "Year:{:^6} Reading:{:<10.3f} Name:{:>10}"
print (layout.format (year, reading, name))
CT04a
You can also use symbols to produce borders for your tables by simply multiplying a string to print many times.
print ("="*30)
The code might look like this:
What do you think it will output?
==============================
CT04a
Much of the programming that is done involves improving or maintaining existing code.
In this lesson you have been given some basic code to make fit for purpose.
Making your program and its output user-friendly is always a good idea. It will be expected of you in all the programming you do.
You have improved the way in which the program displays the output by using a table. This makes it much clearer.
Cheese = 4
Ham = 4
Tuna = 3
Ham | Cheese | Tuna
===================
4 | 4 | 3
CT04a