2.4.4. Your first Python session


Python and Ipython notebook versions of code (.py .ipynb).

This section assumes you have installed Python and that you know how to start it up.

Once you have started Python you should see a Python prompt in the same window in which you have typed the Python command. If you start python with the python command, the prompt looks like three arrowheads or chevrons all pointing the same direction, like this:


In ipython and in notebooks, the prompt looks like this:

In [1]:

If you position your cursor after the prompt symbol you can type things. Type the following line, then hit Enter (if you are using jupyter notebook, you must hold down the shift key while pressing Enter):

>>> total_secs = 7684

Nothing will happen, but you have told Python that you are storing the value 7684 in the variable total_secs. Further statements can make reference to that variable, and the value will be remembered. Let’s try a series of statements:

>>> hours = total_secs // 3600
>>> secs_still_remaining = total_secs % 3600
>>> minutes =  secs_still_remaining // 60
>>> secs_finally_remaining = secs_still_remaining  % 60

In each case, you set the value of a new variable by performing a computation using the value of a variable you had already defined. Python remembers the values and uses them in successive computations. Now let’s get Python to print out some of what it knows:

>>> print ("Hrs =", hours, "mins =", minutes, "secs =", secs_finally_remaining)
Hrs = 2 mins = 8 secs = 4

This time Python responds. The print function asks Python to print its arguments. When the aruments are separated by commas, it prints a space in between them. So the above command asks it to print the string “Hrs =”, followed by a space, followed by the value of the variable hours, followed by a space, followed by the string “mins =”, followed by a space, followed by the value of the variable minutes, followed by a space, followed by the string “secs =”, followed by a space, followed by that value of the variable secs_finally_remaining.

You can also look at the value of a variable just by typing the variable to the Python prompt. Python responds with the value of the variable:

>>> hours

If you type a variable Python doesn’t know the value of, Python responds with an Error Message:

>>> nanoseconds
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nanoseconds' is not defined

We will learn about error messages, because understanding error messages is an important part of interacting with Python. The most important line is the last one, which gives you the type of the error, and some specific information about it. In this case we have a NameError, which means you have used a name — in this case a variable name — that Python doesn’t know.