Flow and variables

Resources

Flow

The computer executes the programming code one line (or statement) at a time. The order in which the lines are executed is called flow.

Order the lines in the following code, we want the computer to first say Hello, then Your Name, and, finally, an invitation to play.

Note

Remember that the lines are executed in order, so change the order of the lines.

Tip
print("Hello")
print("John")
print("Do you want to play a nice game of chess?")

Variables

When we run programs we store information in the memory of the computer for later use. This is a fundamental idea in computers. You can think about the memory of a computer as a file cabinet in which we can store values like numbers and strings of letters. Internally the memory is divided in small pieces, like the drawers of a filing cabinet, and the computer assings a numeric adress to each of those drawers. So, for instance, we could tell the computer to store the number 42 in the address 00000100, but it would be very cumbersome to use these numeric addresses, so, instead, the we use variables, names that we create, to refer to the memory locations and contents.

In different programming languages a variable can refer to the value stored or to the memory address (pointer). In Python a variable will always be a reference to the object stored. You can think of it as a label in the file cabinet drawer or an arrow that points to the drawer.

Value stored in a variable

In Python we store a variable in memory by using the assigment operator =.

Python is doing quite a lot of things for us when we write “favorite_number = 42”:

  1. It reserves a space in the memory to be able to store the object that is going to create.
  2. It creates the object 42.
  3. It assigns the favorite_number variable as a reference to the created and stored object.

Create and print variables

Create two variables, one with your name, and another one with your surname and print them.

Tip

Write the name and year of release of any movie using two variables.

Tip

Change the value of a variable

The variables can be changed to refer to different values/objects. Fix the program to show your real name by changing the value of the variable.

Tip

Given the following code, think about the expected output, what will the program print when you execute it?

Variables are not text strings

Fix the following code to print the correct name of your Pokemons.

Note

Remember that variable names are not enclosed by quotes and that if you put something inside a quote Python will consider it a text string.

Tip

It is very important to understand the difference between variables and text:

  • variable names are not enclosed by quotes.

Fix the following code:

Tip

Assignment unpaking

Python allows for several variables to be set at the same time.