1. Statements, variables and data types#

This is the first step into understanding and creating a Python program. Statements instruct the computer to do something. In this section, we start with storing different kinds of data values in the computer memory and showing their values to the user.

Statements#

Computer programs are generally written to solve specific problems or to automate certain activities. They consist of instructions or commands, which tell the computer what to do. Such instructions are referred to as statements.

In the Python language, the individual statements are separated by hard returns. The end of the statement (i.e. the hard return) is a cue which triggers the Python parser to interpret and to execute the statement.

A simple program may consist of a single statement, or more statements, that are executed in order starting at the top. We will later see and create more complex programs that execute statements conditionally and/or repeatedly. In such programs some statements may be not executed, or in a different order than the order in which they appear in the program.

Variables#

Virtually all programming languages make use of variables of some sort. Variables can be thought of as containers or as boxes in which information can be stored temporarily. Variables always need to be given a name. This name can be used to retrieve the ‘contents’ of the variable. These contents (the data assigned to the variable) are referred to as the variable’s value.

Variables names can consist of any combination of alphanumerical characters that you can think of. Underscores are also allowed in variable names. Variable names cannot begin with a number, however, and they cannot contain a hyphen or spaces.

Although it is possible to work with any sequence of characters, your script will evidently be most understandable when you make use of variable names which are meaningful.

Note that there are a number of reserved words which have a particular function in the Python language, and which cannot be used as variable names for this reason. The list of reserved words includes for, in, is, global, def, if, elif and else.

As mentioned, variables can be given a value. The act of giving a value to a certain variable is called assignment. In the example below, the variable named place_name is assigned the value ‘Leiden’. In this first example, the value of the variables consists of alphanumerical characters, surrounded by quotes. Such texts fragments are referred to as strings. The second variable, named number_of_inhabitants is used to capture a number.

place_name = 'Leiden'
number_of_inhabitants = 123924

Printing output#

Programs often produce some output. This output can be the result of a calculation, for instance. The print() function can be used to communicate the output of the program to the user. A function is a named collection of statements.

The print() function is always used with parentheses. Inside the parentheses, you can provide the string that you would like the computer to display. A string, as was explained above, is a sequence of alphanumerical characters and spaces.

The print() function adds a line break after the string by default.

print('This program works!')
print('This sentence is on a second line.')

You can also add some formatting to the text, to some extent. The character ‘\t’ prints a tab, and ‘\n’ creates a hard return.

print('This sentence is followed by two line breaks. \n')
print('This line contains \ta tab. ')

When you provide the name of a variable inside the print() fuction, this will display the value that is assigned to this variable, and not the name of this variable.

age = 25
print(age)

If you try to print a variable that not been defined yet, Python will produce an error message.

print(height)

As mentioned, the print() function places a line break (i.e. a hard return) after the text provided in parentheses. If you would like to replace this standard line break with another character, you can specify this character in the end parameter of the print() function.

print('This is the string sentence' , end='; ')
print('This second string is printed on the same line.')

Exercise 1.1.#

Write code that can print the sentence “Hello world” or any other sentence that you can think of.

Exercise 1.2.#

Using a single print statement, try to produce the following output:

This is the first line.
This second line contains a        tab.

Exercise 1.3.#

We created two variables named colour1 and colour2, and assign the values blue and yellow to these two variables, respectively.

colour1 = 'blue'
colour2 = 'yellow'

Next, write some code which can swap the values of these two variables. In other words, make sure that, at the end of the program, colour1 has value ‘yellow’ and colour2 has value ‘blue’. Tip: you can do this by working with a third variable named swap, for example, which temporarily stores the value of one of these two variables.

colour1 = 'blue'
colour2 = 'yellow'

Data types#

As mentioned in Variables, the values that are assigned to variables are always of a certain type. We can distinguish three general types: strings, numbers and boolean values.

Strings#

A string stores a text fragment: a sequence of alphanumeric characters and spaces. Strings can be created either with single quotes, double quotes or triple quotes ('''). The single quote and the double quote are most common. They are often used interchangeably. You can find a number of examples of strings below.

"Hello world!"
'This is a string created with single quotes'
'''The triple quotes are conventionally used to create longer strings,
e.g. strings that span multiple lines.'''

The strings that you want to work with may sometimes contain single or double quotes themselves. Python would normally treat such quotes as the characters that end the end of a string. You need to take special measures to ensure that such strings containing quotes do not lead to syntax errors. If the string only contains single quotes, you can surround it with double quotes. Vice versa, a string containing double quotes can be created using a single quote.

"Code is like humour. When you have to explain it, it's bad."
'According to Oscar Wilde, "Experience is the name everyone gives to their mistakes.". '

If your string contains both single and double quotes, you may work with the triple quotes.

quote = '''
"But I don’t want to go among mad people", Alice remarked.
"Oh, you can’t help that," said the Cat: "we're all mad here. I'm mad. You're mad."
'''

Yet another approach is to place a backslash in front of the quote. This backslash used within string is the escape character. It indicates that the character that follows immediately does not have its regular function, and that it should be treated as a literal character. If you need to to include an actual backslash in a string, you should escape it using a second backslash.

print("According to Larry Wall, \"The three chief virtues of a programmer are laziness, impatience and hubris\".")

Exercise 1.4#

‘Debugging’ is the process of finding and correcting mistakes in a computer program. It is a very useful skill to have as a programmer.

Try to debug the code below.

print( 'It's not always easy to see the mistakes in your code.' )
print( "The ability to debug can be really useful.'' )
print( Don't forget to read the error messages!
      They're often very useful.)

Numbers#

Numbers form the second data type. In Python, there are two types of numbers. Integers, firstly, are whole numbers. They are natural numbers without a fractional or decimal part. Integers can also be negative numbers.

age = 20
nr_pages = 273
negative = -3

Next to such integers, Python can also work with real numbers. They are called floats or floating point numbers.

pi = 3.14159265359

The type of the data represented by a variable can always be found by using the type() function.

age = 20
print( type(age) )
## this will print <class 'int'>
pi = 3.14159265359
print( type(pi) )
# <class 'float'>

Unlike strings, numbers are never surrounded by quotes. When you place a single number in a pair of quotes, this will automatically convert the number into a string.

number_of_inhabitants = "123924"
print( type(number_of_inhabitants) )
# this will print <class 'str'>. 'str' stands for 'string'

An integer can be converted into a floating point number using the float() function. This process of converting data of one type into another type is called coercion. When an integer is coerced into a float, this creates a number with a 0 following the decimal point.

grade = 7
grade_float = float(grade)
print(grade_float)

By the same token, a floating point number can also be coerced into an integer using the int() function.

grade = 7.5
grade_int = int(grade)
print(type(grade_int))
print(grade_int)

Note that the conversion from a float into an integer may result in a loss of information. When the grade 7.5 is coerced into an integer, the value of this variable will be 7. The use of the int() function does not round off the number to the nearest integer, but removes all the digits following the decimal point.

To actually round off a floating point number to the nearest integer, you can work with round().

grade = 7.5
grade_rounded = round(grade)
print(grade_rounded)

If needed, numbers can also be converted into strings using the function str().

age = 25
age_str = str(25)
print( type(age_str) )
# this will print <class 'str'>. 'str' stands for 'string'

Boolean values#

A Boolean variable can only be assigned two values: either True or False (with this exact capitalisation!). They are often used to test whether something is the case. These values will be discussed in more detail in the section on ‘Flow Control’.

Comments#

In the Python language, lines can be preceded by the hash (‘#’) symbol. Lines that start with a hash are called comments. Comments are always ignored by the Python interpreter. They are included for human readers of the code.

Such comments can be very useful when you want to document your code. Computer programs can sometimes be difficult to understand, and, in such situations, comments may help to explain in understandable language what happens exactly in specific parts of the code.

Exercise 1.5.#

As will be explained in the next notebook, you can work with variables in calculations. The code below gives an example.

a = 3
b = 4
c = a+b
print(c)

What happens when you try to make calculations with numbers that have different types?

To examine this question, convert the type of variable ‘a’ to a floating point number using the float() function. Next, try to determine the type of variable that results from the addition.

What happens when you coerce variable ‘a’ into a string, using the str() function?

a = 3
b = 4
c = a+b
print(c)