1. Statements, variables and data types#

Solutions to exercises#

Exercise 1.1.#

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

print('Hello world!')

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. 
print('This is the first line.\nThis second line. contains a \ttab. ')

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'

# Use swap to 'back up' the colour1 value before assigning colour2's value to colour1
swap = colour1
colour1 = colour2
# Restore the original value of colour1 to colour2
colour2 = swap

print( colour1 )
print( colour2 )

Exercise 1.4.#

Try to debug the code below.

# You can 'escape' a quote using the backslash
print( 'It\'s not always easy to see the mistakes in your code.' )
# Two single quotes are not the same as one double quote!
print( "The ability to debug can be really useful." )
# Triple quotes allow us to include line breaks and single quotes inside a string
print( """Don't forget to read the error messages! 
      They're often very useful.""")

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?

## When you add a float and an integer, the result becomes a float

a = float(3)
b = 4
c = a+b
print(c)
print(type(c))
## When you try to add a string and an integer, Python produces an error message

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