Quick Start With The Python Interactive Interpreter
Learn how to use the Python Interactive Interpreter to play with the Python language.
Statements
Let's look at some Python code:
greeting = 'hello'
addressee = 'world'
message = '%s, %s!' % (greeting, addressee)
print message.capitalize()
Without worrying about what this code does, notice that it's made up of four lines. Each of these lines is a statement. The statements are executed in order, like a script for a play, and then the code is finished.
Now let's look at two ways to run this code.
As a program
If we put those four lines of code alone into a simple text file, that file is then a Python program. Programs will be examined in another lesson.
In the Python Interactive Interpreter
The Python Interactive Interpreter is a place where we can type Python code, line-by-line (statement-by-statement), and it will execute each statement when we're done typing it and move on to the next line.
Open your Python Interactive Interpreter. We are presented with a line starting with this:
>>>
This is an invitation to type a Python statement. Type each line of our Python code.
>>> greeting = 'hello'
>>> addressee = 'world'
>>> message = '%s, %s!' % (greeting, addressee)
>>> print message.capitalize()
Hello, world!
>>>
Why did that last statement print out a message? Because that's what the statement said to do. You will be given messages after typing statements in the Python Interactive Interpreter for one of two reasons:
- The statement said to spit out a message, in which case the same thing would happen if the statement were in a program. (This is what we just saw.) Otherwise,
- The statement evaluated to some value and the Python Interactive Interpreter is telling you what that value was as a convenience.
It can also spit out an error message if something went wrong.
Values and Variables
The first line of our code assigns a value of 'hello' to a variable: greeting.
greeting = 'hello'
addressee = 'world'
The right sides of these two statements are called expressions. Expressions are statements that evaluate to values. The third line of our code has a more complicated expression:
message = '%s, %s!' % (greeting, addressee)
In this line, everything to the right of the = sign is the expression. It acts as a whole and evaluates to one value.
You can type an expression alone as a statement into the Python Interactive Interpreter to see what it evaluates to.
>>> 'hello'
'hello'
>>> '%s, %s!' % (greeting, addressee)
'hello, world!'
Notice that when the Python Interactive Interpreter tells you what values these statements evaluate to, it writes the values in the way that you would retype them in Python code: in quotes.
A variable can also make up an entire expression, since it evaluates to the value it holds.
>>> greeting
'hello'
>>> audience = addressee
>>> audience
'world'