An Informal Introduction to Python

<< Click to Display Table of Contents >>

Navigation:  Scriptiing > Python >

An Informal Introduction to Python

In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and ...): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

Some examples:

# this is the first comment

spam = 1  # and this is the second comment

          # ... and now a third!

text = "# This is not a comment because it's inside quotes."


Using Python as a Calculator

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)


The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:


>>> 2 + 2


>>> 50 - 5*6


>>> (50 - 5.0*6) / 4


>>> 8 / 5.0



The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the tutorial.

The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are. The remainder can be calculated with the % operator:

>>> 17 / 3  # int / int -> int
>>> 17 / 3.0  # int / float -> float
>>> 17 // 3.0  # explicit floor division discards the fractional part
>>> 17 % 3  # the % operator returns the remainder of the division
>>> 5 * 3 + 2  # result * divisor + remainder

With Python, it is possible to use the ** operator to calculate powers [1]: