As we learned at the beginning of the chapter, Python commands are called statements. One kind of statement is an expression statement, or expression for short. You're familiar with mathematical expressions like 3 + 4 and 2-3/5; each expression is built out of values like 2 and 3 / 5 and operators like + and -, which combine their operands in different ways.
Like any programming language, Python can evaluate basic mathematical expressions. For example, the following expression adds 4 and 13:
When an expression is evaluated, it produces a single result. In the previous expression, 4+13 produced the result 17.
It's not surprising that 4 + 13 is 17. However, computers do not always play by the rules you learned in primary school. For example, look at what happens when we divide 17 by 10:
You would expect the result to be 1.7, but Python produces 1 instead. This is because every value in Python has a particular type, and the types of values determine how they behave when they're combined.
In the latest version of Python (Python 3.0), 5 / 2 is 2.5 rather than 2. Python 3.0 is currently less widely used than its predecessors, so the examples in this book use the "classic" behavior.
In Python, an expression involving values of a certain type produces a value of that same type. For example, 17 and 10 are integers—in Python, we say they are of type int. When we divide one by the other, the result is also an int.
Notice that Python doesn't round integer expressions. If it did, the result would have been 2. Instead, it takes the floor of the intermediate result. If you want the leftovers, you can use Python's modulo operator (%) to return the remainder:
Be careful about using % and / with negative operands. Since Python takes the floor of the result of an integer division, the result is one smaller than you might expect:
When using modulo, the sign of the result matches the sign of the second operand:
Python has another type called float to represent numbers with fractional parts. The word float is short for floating point, which refers to the decimal point that moves around between digits of the number.
An expression involving two floats produces a float:
When an expression's operands are an int and a float, Python automatically converts the int to a float. This is why the following two expressions both return the same answer as the earlier one:
If you want, you can omit the zero after the decimal point when writing a floating-point number:
However, most people think this is bad style, since it makes your programs harder to read: it's very easy to miss a dot on the screen and see "17" instead of "17."
Was this article helpful?