1  Introduction

Warning

Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.

1.1 Hello, world!

Let’s start with the simplest Python program possible, printing a single line of text:

Here, we have called the built-in print function and provided (or passed) a piece of text (called a string in Python) to be printed out as its argument, placed inside the parentheses ( and ). Note that the text (the string) is enclosed in quotation marks.

The print function can take multiple arguments, separated by commas, and print them on the same line with spaces in between.

As you can see, the arguments of the print function do not have to be strings, we can use numbers too.

We can also call the print function without any arguments to print an empty line:

Note that we always need the parentheses () after print. Without them, we are just referring to the function itself, not actually calling it (i.e., not asking it to do anything).

Note for beginners: Think of a friend you want to ask to write something on a piece of paper. Without the parentheses, you are just thinking about that friend, but you have not actually asked them to do anything. Including the parentheses is like going to the friend and asking them to write something down. You also need to tell them what to write, whether it is a single piece of text or several pieces, and that is exactly what the arguments are for.

1.2 Using (interactive) Python as a calculator

When using interactive Python environments, such as IPython or Jupyter notebooks, entering and running a piece of code will automatically display the last calculated value.

This allows us to use Python as a calculator:

Note that we have not called print in this example. In interactive Python environments, the last calculated value is automatically shown as the output.

However, if we run:

we still see only the output of the last calculation. To display multiple values, we can use the print function.

Here’s another example, showing that in Python we can even “add” strings and “multiply” them by integers:

In these examples, 1, 3, 2, 7.5, "Testing, ", "testing, " and "can you hear me?" are literals, fixed values written directly in the program.

Exercise: Calculate the square root of 1524157875019052100. (Hint: you can search online how to do that in Python!)

Solution

# We have several options:

# Option 1
1524157875019052100 ** 0.5

# Option 2
import math
math.sqrt(1524157875019052100)

# Option 3
import numpy as np
np.sqrt(1524157875019052100)