3.1. Python exampleΒΆ

Note

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

This example illustrates some Python code, and it illustrates interacting with the Python interpreter program (the program that prints the triple Chevron prompt >>> and executes, or “interprets” the commands you type):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> total_secs = 7684
>>> hours = total_secs // 3600
>>> secs_still_remaining = total_secs % 3600
>>> minutes =  secs_still_remaining // 60
>>> secs_finally_remaining = secs_still_remaining  % 60
>>> hours
2
>>> print hours
2
>>> print "Hrs =", hours, "mins =", minutes, "secs =", secs_finally_remaining
Hrs = 2 mins = 8 secs =  4

Lines 1-4 set some names to values. For example, line 2, sets the name hours to the value 2. Python types nothing back for any of these commands. But in line 6, we see we see that Python remembers the value of the name hours when we type that name to the prompt, and Python responds by printing out its value. The print command in Line 6 essentially makes the same thing happen, but there’s an important difference. Pieces of code can have values; when you type a piece of code with a value to the Python interpreter, it prints out the value. That’s what happens in line 7. The print command has no value. The printing is done by the command itself, not by the Python interpreter. Thus, there’s a difference between what a piece of code prints out and what it’s value is. This difference is sometimes confusing to beginners, but it’s essential to understand it in getting more complex programs to work right, and we will come back to it.

Finally, in Line 8, the print command is given a series of things to print out, separated by commas. If you count commas, you’ll see there are six things printed out, three of the names defined above, and three strings. When the Python print command receives a sequences of things to print out separated by commas, it prints them out one after another inserting spaces between them. So five commas means five spaces separating six things.