Anything following a # is a comment.
>>> print 1 # this is a comment 1 >>> # This whole line is a comment
Numbers can be integers or floating point. e.g.:
1
-77777
3.14159265
1.5e+12
Complex numbers, hexadecimal & octal numbers, and 'long' integers are also supported.
Strings ("string literals", to be precise) are enclosed in quotes (single or double).
Multi-line strings can be enclosed in triple-quotes.
'x'
"Hello, world"
"""Twas brillig and the slithy toves
did gyre and gimble in the wabe."""
String literals that are next to each other are concatenated. e.g.:
>>> print 'x' "y" xy
Lists are like arrays in C, but they are dynamically allocated.
This means that they can grow to any size, without being fixed in advance.
List literals are written in square brackets; individual entries are separated by commas.
List indexing starts from 0.
>>> x = ['a', 'b', 'c'] >>> print x[2] c
Because Python is dynamically typed, list elements do not all have to be of the same type.
>>> x = ['abc', 17.3] >>> x = [1, ['abc', 17.3], 2]
Variables are similar to most other languages - a variable name is a series of alphanumeric characters; the first must be a letter. Names are case-sensitive.
Variables do not need to be declared. A variable is automatically allocated when a value is assigned to it.
>>> x = 6 >>> print x * 9 54 >>> stringVariable27 = 'A string' >>> print stringVariable27 A string >>> y = x + stringVariable27 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'int' and 'str'
Standard mathematical operators exist for numbers.
Some also apply to strings and lists.
| Numbers | Strings | Lists | |
|---|---|---|---|
| + | Addition | Concatenation | Concatenation |
| - | Subtraction / negation | ||
| * | Multiplication | Repetition | Repetition |
| / | Division | ||
| % | Remainder | Formatting |
Logical operators are used for conditional expressions.
Similar to C, the logical value 'true' is represented by the numeric
value 1, and 'false' by the numeric value 0.
| or | Logical or |
| and | Logical and |
| not | Logical negation |
| < <= > >= == != | Numeric or string comparison |
| in | String or list membership |
Parentheses are used to group expressions. e.g.:
>>> 1 + 2 * 3 7 >>> (1 + 2) * 3 9
Blocks of statements are defined by their level of indentation.
The first level of statements should have no indentation.
New levels are introduced by statements such as if, while, and for.
>>> x = 7 >>> str = 'abc' * x
>>> print 'abc' * x abcabcabcabcabcabcabc
pass is a placeholder, that does nothing (a "no-op").
>>> if 1 > 2: ... print "Something's wrong" ... >>> >>> if (x > 3) and (x < 4): ... y = x ... else: ... y = x * 2 ...
>>> while x < 10: ... x = x * 2 ...
>>> for i in ['a', 'b']: ... print i ... a b >>> for j in range(0,3): ... print j ... 0 1 2
Don't forget the colon at the end of if, while, and for statements.