Numbers
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.
2 + 2 4 50 - 5*6 20 (50 - 5*6) / 4 5.0 8 / 5 # division always returns a floating point number 1.6
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.
Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:
17 / 3 # classic division returns a float 5.666666666666667 17 // 3 # floor division discards the fractional part 5 17 % 3 # the % operator returns the remainder of the division 2 5 * 3 + 2 # floored quotient * divisor + remainder 17
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>> n # try to access an undefined variable Traceback (most recent call last): File <stdin>, line 1, in <module> NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
4 * 3.75 - 1 14.0
In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).
Strings
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result 2. \ can be used to escape quotes:
'spam eggs' # single quotes 'spam eggs' 'doesn\'t' # use \' to escape the single quote... "doesn't" "doesn't" # ...or use double quotes instead "doesn't" '"Yes," they said.' '"Yes," they said.' "\"Yes,\" they said." '"Yes," they said.' '"Isn\'t," they said.' '"Isn\'t," they said.'
Strings can be concatenated (glued together) with the + operator, and repeated with *:
# 3 times 'un', followed by 'ium' 3 * 'un' + 'ium' 'unununium'
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
'Py' 'thon' 'Python'
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
word = 'Python' word[0] # character in position 0 'P' word[5] # character in position 5 'n'
Indices may also be negative numbers, to start counting from the right:
word[-1] # last character 'n' word[-2] # second-last character 'o' word[-6] 'P'
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 - 1 - 2 - 3 - 4 - 5 - 6 -6 -5 -4 -3 -2 -1
Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:
word[0] = 'J' Traceback (most recent call last): File "stdin", line 1, in module TypeError: 'str' object does not support item assignment word[2:] = 'py' Traceback (most recent call last): File "stdin", line 1, in module TypeError: 'str' object does not support item assignment
If you need a different string, you should create a new one:
'J' + word[1:] 'Jython' word[:2] + 'py' 'Pypy'
The built-in function len() returns the length of a string:
s = 'supercalifragilisticexpialidocious' len(s) 34
Lists
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
squares = [1, 4, 9, 16, 25] squares [1, 4, 9, 16, 25]
Like strings (and all other built-in sequence types), lists can be indexed and sliced:
>>> squares[0] # indexing returns the item 1 squares[-1] 25 squares[-3:] # slicing returns a new list [9, 16, 25]
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:
>>> squares[:] [1, 4, 9, 16, 25]
Lists also support operations like concatenation:
squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
cubes = [1, 8, 27, 65, 125] # something's wrong here 4 ** 3 # the cube of 4 is 64, not 65! 64 cubes[3] = 64 # replace the wrong value cubes [1, 8, 27, 64, 125]
You can also add new items at the end of the list, by using the append() method
cubes.append(216) # add the cube of 6 cubes.append(7 ** 3) # and the cube of 7 cubes [1, 8, 27, 64, 125, 216, 343]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # replace some values letters[2:5] = ['C', 'D', 'E'] letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] # now remove them letters[2:5] = [] letters ['a', 'b', 'f', 'g'] # clear the list by replacing all the elements with an empty list letters[:] = [] letters []
if Statements
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.
x = int(input("Please enter an integer: ")) if x < 0: x=0 print('Negative changed to zero') elif x==0: print('Zero') elif x==1: print('Single') else: print('More')
for Statements
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
# Measure some strings: words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w))
Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
# Strategy: Iterate over a copy for user, status in users.copy().items(): if status == 'inactive': del users[user] # Strategy: Create a new collection active_users = {} for user, status in users.items(): if status == 'active': active_users[user] = status
The range() Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:
for i in range(5): print(i) 0 1 2 3 4
The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
list(range(5, 10)) [5, 6, 7, 8, 9] list(range(0, 10, 3)) [0, 3, 6, 9] list(range(-10, -100, -30)) [-10, -40, -70]
To iterate over the indices of a sequence, you can combine range() and len() as follows:
a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) 0 Mary 1 had 2 a 3 little 4 lamb
Intermezzo: Coding Style
For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:
- Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out. - Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several pre files side-by-side on larger displays. - Use blank lines to separate functions and classes, and larger blocks of pre inside functions.
- When possible, put comments on a line of their own.
- Use docstrings.
- Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).
- Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).
- Don’t use fancy encodings if your pre is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.
- Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the pre.
Reference
All the documentation in this page is taken from The Python Tutorial