2  Variables and printing output

2.1 Variables, values and their types

The cell below contains Python code that can be executed by the Python interpreter. One of the most basic things that we can do with Python is to use it as a calculator:

2+2
4

Great, but there are many calculators. It gets more interesting when we use variables to store information. This is done with the = operator. In Python, variable names:

  • can include letters, digits, and underscores
  • cannot start with a digit
  • are case sensitive.
x = 3.0

Once assigned, variables can be used in new operations:

y = 2.0
x + y
5.0

Python knows various types of data. Three common ones are:

  • integer numbers
  • floating point numbers
  • strings
text = "Data Carpentry"
number = 42
pi_value = 3.14159265358

In the example above, three variables are assigned. Variable number is an integer number with a value of 42 while pi_value is a floating point number and text is of type string.

Using the type command, it is possible to check the data type of a variable.

text
'Data Carpentry'
type(text)
str
number
42
type(number)
int
pi_value
3.14159265358
type(pi_value)
float

2.2 Output versus printing

In the above examples, most of the times output is printed directly below the cell, but not always the output is printed and not all operations are printed. The print command can be used to control what is printed when.

Note, that text (strings) always has to be surrounded by " or '.

print("Hello World")
Hello World

In the example below we first print the value of the variable number using the print command, and then call the variable:

print(number)
number
42
42

Now we do it the other way around:

number
print(number)
42

When not using the print command, only the output of the last operation in the input cell is printed. If the last operation is the assignment of a variable, nothing will be printed.

In general print is the only way to print output to the screen when you are not working in an interactive environment like Jupyter (as we are doing now).

Rule of thumb: use the normal output for quick checking the output of an operation while developing in your Jupyter notebook, use print for printing output that still needs to be there in the future while your scripts get more complicated.

Continue with the following chapter Operators and Built-in Functions