Python Interpreter
After installing Python, start by checking the version. Open a Terminal (Command Prompt for Windows) and enter the python --version
command. This command outputs the version of Python you have installed:
$ python --version Python 3.4.1 :: Anaconda 2.1.0 (x86_64)
If Python 3.4.1 (the number will be different, depending on your installed version) is displayed, as shown in the preceding code, then Python 3 has been installed successfully. Now, enter python
and start the Python interpreter:
$ python Python 3.4.1 |Anaconda 2.1.0 (x86_64)| (default, Sep 10 2014, 17:24:09) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
The Python interpreter is also referred to as interactive mode, through which you can interact with Python to write programs. An interaction means that, for example, the Python interpreter answers 3
when you ask, "What is 1+2?". Enter the following:
>>> 1 + 2 3
Hence, the Python interpreter enables you to write programs interactively. In this book, we will use an interactive mode to work with simple examples of Python programming.
Mathematical Operations
You can conduct mathematical operations, such as addition and multiplication, as follows:
>>> 1 - 2 -1 >>> 4 * 5 20 >>> 7 / 5 1.4 >>> 3 ** 2 9
Here, * means multiplication, / means division, and ** means exponentiation. (3 ** 2 is the second power of 3.) In Python 2, when you divide two integers, an integer is returned. For example, the result of 7/5 is 1. Meanwhile, in Python 3, when you divide two integers, a floating-point number is returned.
Data Types
Programming has data types. A data type indicates the character of the data, such as an integer, a floating-point number, or a string. Python provides the type()
function to check the data's type:
>>> type(10) <class 'int'> >>> type(2.718) <class 'float'> >>> type("hello") <class 'str'>
The preceding results indicate that 10
is int
(integer type), 2.718
is float
(floating-point type), and hello
is str
(string type). The words type
and class
are sometimes used in the same way. The resulting output, <class 'int'>
, can be interpreted as 10
is an int
class
 (type).
Variables
You can define variables by using alphabetical letters such as x
and y
. You can also use variables to calculate or assign another value to a variable:
>>>x = 10
# Initialize >>>print(x)
10 >>>x = 100
# Assign >>>print(x)
100 >>>y = 3.14
>>>x * y
314.0 >>>type(x * y)
<class 'float'>
Python is a dynamically typed programming language. Dynamic means that the type of a variable is determined automatically, depending on the situation. In the preceding example, the user does not explicitly specify that the type of x
is int
(integer). Python determines that the type of x
is int
because it is initialized to an integer, 10. The preceding example also shows that multiplying an integer by a decimal returns a decimal (automatic type conversion). The #
symbol comments out subsequent characters, which are ignored by Python.
Lists
You can use a list (array) to assign multiple numbers to a variable:
>>>a = [1, 2, 3, 4, 5]
# Create a list >>>print(a)
# Print the content of the list [1, 2, 3, 4, 5] >>>len(a)
# Get the length of the list 5 >>>a[0]
# Access the first element 1 >>>a[4]
5 >>>a[4] = 99
# Assign a value >>>print(a)
[1, 2, 3, 4, 99]
To access an element, you can write a[0]
, for example. The number in this [ ]
is called an index, which starts from 0 (the index 0 indicates the first element). A convenient notation called slicing
is provided for Python lists. You can use slicing to access both a single element and a sublist of the list:
>>> print(a) [1, 2, 3, 4, 99] >>> a[0:2] # Obtain from the zero index to the second index (the second one is not included!) [1, 2] >>> a[1:] # Obtain from the first index to the last [2, 3, 4, 99] >>> a[:3] # Obtain from the zero index to the third index (the third one is not included!) [1, 2, 3] >>> a[:-1] # Obtain from the first element to the second-last element [1, 2, 3, 4] >>> a[:-2] # Obtain from the first element to the third-last element [1, 2, 3]
You can slice a list by writing a[0:2]
. In this example, a[0:2]
obtains the elements from the zeroth index to the one before the second index. So, it will show the elements for the zeroth index and the first index only in this case. An index number of -1
indicates the last element, while -2
indicates the second-last element.
Dictionaries
In a list, values are stored with index numbers (0, 1, 2, ...) that start from 0. A dictionary stores data as key/value pairs. Words associated with their meanings are stored in a dictionary, just as in a language dictionary:
>>>me = {'height':180}
# Create a dictionary >>>me['height']
# Access an element 180 >>>me['weight'] = 70
# Add a new element >>>print(me)
{'height': 180, 'weight': 70}
Boolean
Python has a bool type. Its value is True
or False
. The operators for the bool type are and
, or
, and not
(a type determines which operators can be used, such as +, -, *, and / for numbers):
>>> hungry = True # Hungry? >>> sleepy = False # Sleepy? >>> type(hungry) <class 'bool'> >>> not hungry False >>> hungry and sleepy False >>> hungry or sleepy True
if Statements
You can use if
/else
to switch a process, depending on a condition:
>>> hungry = True >>> if hungry: ... print("I'm hungry") ... I'm hungry >>> hungry = False >>> if hungry: ...    print("I'm hungry") # Indent with spaces ... else: ...     print("I'm not hungry") ...     print("I'm sleepy") ... I'm not hungry I'm sleepy
In Python, spaces have an important meaning. In this if
statement example, the next statement after if
hungry
starts with four spaces. This is an indent that indicates the code that is executed when the condition (if hungry
) is met. Although you can use tab characters for an indent, Python recommends using spaces.
In Python, use spaces to represent an indent. Four spaces are usually used for each indent level.
for Statements
Use a for
statement for a loop:
>>> for i in [1, 2, 3]: ...    print(i) ... 1 2 3
This example outputs the elements of a list, [1, 2, 3]
. When you use a for … in …:
statement, you can access each element in a dataset, such as a list, in turn.
Functions
You can define a group of processes as a function:
>>> def hello(): ... print("Hello World!") ... >>> hello() Hello World!
A function can take an argument:
>>> def hello(object): ... print("Hello " + object + "!") ... >>> hello("cat") Hello cat!
Use +
to combine strings.
To close the Python interpreter, enter Ctrl+D (press the D key while holding down the Ctrl key) for Linux and macOS X. Enter Ctrl+Z and press the Enter key for Windows.