JIT — Intro to Data Science · Python Lab · Problem 2 of 30

Boxes that hold a value

The same programme as problem 1 — but now the name and the subject can be swapped without touching the printing.

The trouble with problem 1

In problem 1 the name was typed straight into the printing statement. That worked, but it has a weakness. Suppose the programme printed the name on ten lines instead of two, and the name had to change. You would have to hunt down all ten and edit every one. Miss one, and the programme quietly prints the wrong name.

There is a better way. Put the name in a box, give the box a label, and let the printing statements ask the box for whatever it is holding. Then a change of name is a change in one place.

New word — variable A labelled box that holds a value. You make one by writing a label, then =, then the value:
name = "Kartik Vyas"
Read the = as "put into", never as "equals". It is an instruction, not a fact.
New word — f-string An ordinary string with the letter f written just before the opening quote. Inside it, anything you put in curly brackets is treated as a box label, and Python swaps in whatever that box is holding:
print(f"My name is {name}") prints My name is Kartik Vyas
Without the f, nothing is swapped in and the brackets print exactly as typed.

What you are building

A programme with two boxes and three printed lines. With the boxes holding Kartik Vyas and data science, the output is:

Hello, world! My name is Kartik Vyas I am teaching data science

But that is only one of its outputs. Put Gayatri Phadnis and artificial intelligence in the boxes instead, change nothing else, and the same programme prints:

Hello, world! My name is Gayatri Phadnis I am teaching artificial intelligence

In stage 4 you will do exactly that, as many times as you like.

Coming later These boxes hold text. Boxes can also hold numbers, and numbers can be added, subtracted and divided. That is problem 3.

Arrange the steps

Six things have to happen. Two are already in place — the note at the top and the greeting straight after it. Click the remaining four in an order that works.

One rule decides most of it: a box has to be filled before anything can ask it for a value. Python reads top to bottom and has no way of looking ahead.

Your plan

The four steps still to place

Fill the statements

Your six steps written as Python, in the order you put them. Three pieces are missing.

Leave nothing on "choose…". A wrong pick here does not always cause an error — sometimes it just prints something you did not expect, which is the harder kind of mistake to spot.

Run and read

Here is the whole programme. The two highlighted values are yours to change — type anything you like, or pick a suggestion.

Your programme

What the boxes are holding

Output

Nothing has run yet.