CS13 : Dealing with output


https://docs.google.com/presentation/d/17-zxs0sKszc4a0b9UAEWFemzqujpUKmtTDON3_Z-0Zk/preview
OK, so we've dealt with input, we've processed until we fell asleep so it's time to deal with methods of outputting data back to the user. If we are careful, data can become information (as long as we format it correctly). There is also a section on output devices specifically for WJEC but it won't do any harm if your students want to do it as well.

We are learning ...
  • How to output data and information from a program to a computer display
  • About the principles of operation of different output devices
So that we can ...
  • Use simple and more complex formatting techniques to present information on the computer display.
    - Concatenation operator
    - print() statement parameters
    - string.format() string method
  • Describe the principles of operation of various output devices
  • Describe the applications of these output devices in real life scenarios.

# Get Ready.png

Consider the following three situations. Each one show the output from a simple script; but what do they do?



Write your ideas on your whiteboards. The ambiguity which results from badly formatted output can render a script fairly useless, although you might be able to work out what the scripts do.

Activity 1 Simple string concatenation   O   A   E   W 

There are two simple ways to concatenate (join) strings together depending on where you are doing it. There are two different situations you may find yourself in ...

Generating output before printing

In this case, the output string must be generated using the '+' concatenation operator to generate an expression which is evaluated before it is printed. Be aware, however, that you must typecast any non-strings to strings before concatenating in this way.

string+string+string...

Joining strings together in the print function

If you simply want to print a concatenated string, you pass the print function (Python 3) either a single expression with strings joined by '+' (plus) or a series of parameters to print separated by ',' (comma). In the latter case, the print function simply prints the parameters one at a time, each one followed by a space. The advantage of using the comma is that you don't need to typecast variables before printing, but you do have to put up with spaces between the values.

print(string+string+...)
print(string,integer,float,string,...)


Task 1.1 String concatenation
Where we learn about the different methods of joining strings


Try the following tasks. There is no need to evidence your work in Python but you must respond to the task under a suitable title in your notebooks / on paper.

https://repl.it/languages/python3

Get ready to code!

Open up your favourite Python programming environment

At the prompt
 

Type the following statements, pressing the  Enter  key after each one. DO NOT COPY and PASTE!

>>> greeting = "Hello"
>>> quantity = 12
>>> price = 10.99
>>> print(greeting,quantity,price)
>>> print(greeting+quantity+price) # Doesn't work
>>> print(greeting+str(quantity)+str(price))
>>> print(greeting+' '+str(quantity)+' '+str(price))

In your notebooks / on paper

Notice that to achieve the same output using the '+' concatenation operator, you need to do a lot more work. Which do you think is better? Write down your ideas.

At the prompt

You can add literal text between the parameters if you wish ...

>>> print(greeting,', you ordered',quantity,'widgets at £',price,'costing',quantity*price)

In your notebooks / on paper

This is OK I suppose, but do you see any problems? Write down your ideas.

In a script

Download and complete the tasks in the six Python scripts ...


Print out your completed scripts in colour (using Notepad++) and stick them in your notebooks / folders.


Activity 2 Advanced formatting   O   A   E   W 

To get more control over the appearance of output, we can use the .format() string method. This is much more powerful, but more difficult to master. In it's simplest form (!), a string formatted with the .format() method looks like this ...

print('string {arg1} string {arg2} string {arg3} ...'.format(arg1,arg2,arg3,...))

You might have to read it again!


Task 2.1 Advanced string formatting
Where we learn how to perform advanced string formatting in Python


You should carry out the tasks carefully in Python. There is no need to evidence your work in Python for your but you must respond to the activities under a suitable title in your notebooks.


Get ready to code

Open up your favourite Python programming environment

At the prompt

A simple example. Enter the following lines of code, pressing the  Enter  key after each one.

>>> forename = 'Graham'
>>> surname  = 'Smith'
>>> print('Full name : {0}, {1}'.format(surname,forename))

Python substitutes the parameters in the .format() function in the numbered curly braces in the string. Note that the numbers start at 0, not 1.

In your notebooks / on paper

Is this easier than using simple concatenation using the plus sign or the comma? Does it give you more control over the layout of the output? Write down your ideas.

At the prompt

Let's create the same (similar) output using the .format() method as we did with the ',' method above. Type the following lines of code, pressing the  Enter  key after each one.

>>> greeting = "Hello"
>>> quantity = 12
>>> price = 10.99
>>> print(
        '{0}, you ordered {1} widgets at £{2} each, totalling £{3}'
        .format(greeting,quantity,price,quantity*price)
        )

I've split the print statement up into multiple lines to a) make it fit in the width of the screen and b) make it a little easier to read. You can try this with your code if the lines are too long.

In your notebooks / on paper

Think back to the examples you tried earlier where you used the comma to concatenate items within the print statement. What explicit operation do you not have to carry out? Write down your ideas.

At the prompt

Nothing different so far ... but the real power comes in the formatting capabilities. Type the following lines of code at the prompt, pressing the  Enter  key after each one.

>>> pi = 3.1415927
>>> radius = 5.00
>>> print(
        'The area of a circle radius {0} units is {1} square units.'
        .format(radius,pi*radius**2)
        )

The print statement produces an answer for the area to 7 decimal places of accuracy but we can force Python to give it us to
2 decimal places using the following extra code (highlighted) ...

>>> print(
        'The area of a circle radius {0} units is {1:.2f} square units.'
        .format(radius,pi*radius**2)
        )

Notice that we follow the parameter index with a colon (:) then the precision to 2 decimal places (.2) and then that we want it in float format (f).

In your notebooks / on paper

How would you format the output to three decimal places? What would you change? Write down your ideas.

At the prompt

Try typing the following lines of code, pressing the  Enter  key after each one.

>>> score = 7
>>> total = 12
>>> print(
        'You scored {0}/{1} which is {2:.2%}'
        .format(score,total,score/total)
        )

This is a nice quick way to calculate a percentage and format it nicely directly in the output! Nice!

In your notebooks / on paper

Describe exactly what the '%' format operator does. Try the same line of code without the highlighted format codes to help you with your explanation. Write down your ideas.

At the prompt

Try creating 2 of your own examples to illustrate what you have learnt. Try to use a variety of different levels of precision (decimal places) and a mixture of float formatting (f) and percentage formatting (%)

In your notebooks / on paper

How did you decide what examples to use? Did you make them complicated or easy? Write down your ideas.


Activity 3 Output devices and actuators  O   A   E   W 

Look carefully at the following diagram ...

https://drive.google.com/file/d/19YkZdUN581dMV1_iYjEx1bwEv4xikX13/preview
The IPSO model of computer systems with output highlighted. Click to engage

It's all well and good gathering lots of useful data from the user, performing lots of super processing and formatting output using fancy .format() functions when you've got nothing to actually display the final product?

What the hell is this meant to be?



Task 3.1 Principles of operation
Where you research the principles of operation of output devices


On the worksheet

Download a copy of 'Output Devices - Principles of Operation' and save it in your documents. This is a Microsoft Publisher document - ask your teacher for help if you don't have Publisher installed on your network.

Using this document as a template, conduct some research on the following list of output devices using the World Wide Web and complete the document. There is a separate page for each device and on each page, there is a picture placeholder and two text boxes to write a description of the object and a written explanation of how it works.
  • Inkjet, laser and 3D printers
  • 2D and 3D cutters
  • Speakers and headphones
  • Actuators
  • LCD and LED display, LCD projectorsDLP (Digital Light Processing projector)


If you don't think you're going to have the time or the energy to find out about every output device, why not partner up and share the load? Remember to put your name on each sheet and make sure you have one copy of each page to stick in your notebook.


Task 3.2 Applications
Where you learn about the applications of output devices


On the worksheet

Download yourself a copy of the 'Applications of output devices' worksheet and complete the activity. Remember to put your name in the header and print your worksheet out when you have completed it.



Task 3.3 The latest big thing
Where you learn about the application and operation of 3D printers


The latest big thing is 3D printing. There are plenty of resources on the web which describe how 3D printing works and what it can be used for. You might even have a 3D printer at school. 

How about the latest cool stuff printed in 3D, delivered direct to your door? Maybe you want to start your own 3D printing store and sell your latest artwork? Check out Shapeways ...

Truly splendiferous!

Carry out some research

Use the World Wide Web to research the following things ...
  • What 3D printing is;
  • How it works;
  • What it is and could be used for.
Make sure that you record your research and also the sources - where you got it from - and the date you access the website. It is very important to credit the owner of the website if you use the information from it.

Produce a report

Your report could be a poster, video, podcast or written document. Include some images and include the references to the locations where you found the information you have used.


Assessment Task (Homework)

Right at the beginning of this lesson, I showed you the ambiguous output of three scripts which I'd written but which I'd not formatted the output correctly. The scripts are in a zip archive called scripts.zip which is available from the lesson resources. Download this zip file, extract it and edit the scripts to improve the formatting of the output. Use any method you have learnt during this lesson, but better grades will be gained from more complex formatting!

Present your work either by printing out your new scripts or by writing the code in your notebooks if you haven't got Python installed at home (which you really should have done by now).

Grading rubric

MASTER :  You have used advanced string formatting operations to produce unambiguous output for the scripts and have presented your new scripts in a suitable way.
APPRENTICE You have used simple string formatting to alter the scripts to produce unambiguous output which may not be formatted appropriately.
NOVICE : You have attempted to use some form of clarification for the output but have not attempted to format the strings in the output in any way.

Click to download revision cards
https://docs.google.com/document/d/19dOyThefVlIdsi3cl2KxejEhu4uomJJ7K0b9DrPV3-w/export?format=pdf
Remember to print them single sided

# Flash cards.png
Click to load key word list to help you make your own flash cards 

https://goo.gl/forms/1axgHMwiruuEsICA2
Try to get 5/5!


Hungry for more?

We've only scratched the surface of the string formatting mini-language. Find out more on string formatting at the Python website.

Explore more advanced string formatting operators at PyFormat - string formatting for great good.


FAQ Frequently Asked Questions


Q : Is using a plus sign easier than using a comma?
A : Good question - it depends. With the plus sign, it's easier to control how printing occurs but you must remember to typecast yourself. On the other hand, I probably wouldn't use either - my preference is the .format() method!

Q : Which is temporary, typecasting or type conversion?
A : Typecasting is a temporary conversion of a variable in one type to another during an expression. The original data type is kept. During type conversion, the original variable changes type permanently.