Python Programming/Operators

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: Sets Index Next: Flow control


Contents

[edit] Basics

Python math works like you would expect.

>>> x = 2
>>> y = 3
>>> z = 5
>>> x * y
6
>>> x + y
5
>>> x * y + z
11
>>> (x + y) * z
25

Note that Python adheres to the PEMDAS order of operations.

[edit] Powers

There is a builtin exponentiation operator '**', which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations.

[edit] Division and Type Conversion

Dividing two integers uses integer division, also known as floor division. Using division this way is deprecated because it is intended to change in the future. Instead, if you want floor division, use '//'.

Dividing by or into a floating point number (there are no fractional types in Python) will cause Python to use true division. To coerce an integer to become a float, 'float()' with the integer as a parameter

>>> x = 5
>>> float(x)
5.0

This can be generalized for other numeric types: int(), complex(), long().

[edit] Modulo

The modulus (remainder of the division of the two operands, rather than the quotient) can be found using the % operator, or by the divmod builtin function. The divmod function returns a tuple containing the quotient and remainder.

[edit] Negation

Unlike some other languages, variables can be negated directly:

>>> x = 5
>>> -x
-5

[edit] Augmented Assignment

There is shorthand for assigning the output of an operation to one of the inputs:

>>> x = 2
>>> x # 2
2
>>> x *= 3
>>> x # 2 * 3
6
>>> x += 4
>>> x # 2 * 3 + 4
10
>>> x /= 5
>>> x # (2 * 3 + 4) / 5
2
>>> x **= 2
>>> x # ((2 * 3 + 4) / 5) ** 2
4
>>> x %= 3
>>> x # ((2 * 3 + 4) / 5) ** 2 % 3
1
 
>>> x = 'repeat this  '
>>> x  # repeat this
repeat this
>>> x *= 3  # fill with x repeated three times
>>> x
repeat this  repeat this  repeat this

[edit] Boolean

or:

if a or b:
    do_this
else:
    do_this

and:

if a and b:
    do_this
else:
    do_this
Previous: Sets Index Next: Flow control
Personal tools