3.1. Python example¶
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>>> total_secs = 7684
2>>> hours = total_secs // 3600
3>>> secs_still_remaining = total_secs % 3600
4>>> minutes = secs_still_remaining // 60
5>>> secs_finally_remaining = secs_still_remaining % 60
6>>> hours
72
8>>> print(hours)
92
10>>> print("Hrs =", hours, "mins =", minutes, "secs =", secs_finally_remaining)
11Hrs = 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.