Text stringlengths 1 9.41k |
|---|
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... |
Afterwards, no result is displayed before the next
interactive prompt:
```
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
```
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 "<... |
This means that when you are
using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
```
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
```
This variable should be treated as read-only by the user. |
Don’t explicitly assign a value to it — you
would create an independent local variable with the same name masking the built-in variable with its magic
behavior.
1 Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. |
To avoid this and get
```
9, you can use (-3)**2.
```
-----
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).
#### 3.1.2 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.'
'... |
While this might sometimes look different from the input (the enclosing quotes could change),
the two strings are equivalent. |
The string is enclosed in double quotes if the string contains a single quote
and no double quotes, otherwise it is enclosed in single quotes. |
The print() function produces a more
readable output, by omitting the enclosing quotes and by printing escaped and special characters:
```
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(... |
One way is using triple-quotes: """...""" or '''...'''. End of
lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of
the line. |
The following example:
2 Unlike other languages, special characters such as \n have the same meaning with both single ('...') and double ("...")
quotes. |
The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape
```
\') and vice versa.
```
-----
produces the following output (note that the initial newline is not included):
```
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to ... |
the ones enclosed between quotes) next to each other are automatically
concatenated.
```
>>> 'Py' 'thon'
'Python'
```
This feature is particularly useful when you want to break long strings:
```
>>> text = ('Put several strings within parentheses '
... |
'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
```
This only works with two literals though, not with variables or expressions:
```
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
... |
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:
-----
Note that since -0 is the same as 0, negative... |
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'
```
Note how the start is always included, and the end always excl... |
This makes sure that s[:i] + s[i:]
is always equal to s:
```
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
```
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults
to the size of the string being sliced.
```
>>> word[:2] # character from the ... |
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
```
The first row of numbers gives the position of the indices 0…6 in the string; the second row gives th... |
The slice from i to j consists of all characters between the edges labeled i
and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. |
For
example, the length of word[1:3] is 2.
Attempting to use an index that is too large will result in an error:
-----
However, out of range slice indexes are handled gracefully when used for slicing:
```
>>> word[4:42]
'on'
>>> word[42:]
''
```
Python strings cannot be changed — they are immutable. |
Therefore, assigning to an indexed position in the
string results in an error:
```
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment
```
If you need a different string, you should create a new one:
```
>>> '... |
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 type), lists can be indexed and sliced:
```
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
```
(... |
This means that the following slice
returns a new (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 (we will see mo... |
For instance,
[we can write an initial sub-sequence of the Fibonacci series as follows:](https://en.wikipedia.org/wiki/Fibonacci_number)
```
>>> # Fibonacci series:
... |
# the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... |
a, b = b, a+b
...
0
1
1
2
3
5
8
```
This example introduces several new features.
- The first line contains a multiple assignment: the variables a and b simultaneously get the new values
0 and 1. |
On the last line this is used again, demonstrating that the expressions on the right-hand side
are all evaluated first before any of the assignments take place. |
The right-hand side expressions are
evaluated from the left to the right.
- The while loop executes as long as the condition (here: a < 10) remains true. |
In Python, like in C,
any non-zero integer value is true; zero is false. |
The condition may also be a string or list value, in
fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used
in the example is a simple comparison. |
The standard comparison operators are written the same as in
C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal
to) and != (not equal to).
- The body of the loop is indented: indentation is Python’s way of grouping statements. |
At the interactive
prompt, you have to type a tab or space(s) for each indented line. |
In practice you will prepare more
complicated input for Python with a text editor; all decent text editors have an auto-indent facility.
When a compound statement is entered interactively, it must be followed by a blank line to indicate
completion (since the parser cannot guess when you have typed the last line). |
Note that each line
within a basic block must be indented by the same amount.
- The print() function writes the value of the argument(s) it is given. |
It differs from just writing
the expression you want to write (as we did earlier in the calculator examples) in the way it handles
multiple arguments, floating point quantities, and strings. |
Strings are printed without quotes, and a
space is inserted between items, so you can format things nicely, like this:
-----
The keyword argument end can be used to avoid the newline after the output, or end the output with
a different string:
-----
-----
**CHAPTER**
### FOUR
MORE CONTROL FLOW TOOLS
Besides ... |
For example:
```
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... |
elif x == 1:
... print('Single')
... else:
... print('More')
...
More
```
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.
### 4.2 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):
-----
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate
selected items), it is recommended that you first make a copy. |
Iterating over a sequence does not implicitly
make a copy. The slice notation makes this especially convenient:
```
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... |
if len(w) > 6:
... |
words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
```
With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over
and over again.
### 4.3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in function range... |
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’):
```
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
```
To iterate over the indices of a sequence, you can combine range() an... |
print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
```
In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.
A strange thing happens if you just print a range:
-----
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. |
It is an object
which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really
make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect
something from which they can obtain successive items un... |
We have seen that
the for statement is such an iterator. |
The function list() is another; it creates lists from iterables:
```
>>> list(range(5))
[0, 1, 2, 3, 4]
```
Later we will see more functions that return iterables and take iterables as argument.
### 4.4 break and continue Statements, and else Clauses on Loops
The break statement, like in C, breaks out of the innermo... |
This is exemplified by the following loop, which searches for prime numbers:
```
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... |
break
... else:
... # loop fell through without finding a factor
... |
print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
```
(Yes, this is the correct code. |
Look closely: the else clause belongs to the for loop, not the if statement.)
When used with a loop, the else clause has more in common with the else clause of a try statement than it
does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else
clause runs when no break oc... |
For more on the try statement and exceptions, see Handling Exceptions.
The continue statement, also borrowed from C, continues with the next iteration of the loop:
```
>>> for num in range(2, 10):
... |
if num % 2 == 0:
... print("Found an even number", num)
... continue
... |
print("Found a number", num)
Found an even number 2
```
(continues on next page)
-----
(continued from previous page)
```
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
### 4.5 pass Statements
```
The pass statement does not... |
It can be used when a statement is required syntactically but the program
requires no action. For example:
```
>>> while True:
... |
pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
```
This is commonly used for creating minimal classes:
```
>>> class MyEmptyClass:
... |
pass
...
```
Another place pass can be used is as a place-holder for a function or conditional body when you are working
on new code, allowing you to keep thinking at a more abstract level. |
The pass is silently ignored:
```
>>> def initlog(*args):
... |
pass # Remember to implement this!
...
### 4.6 Defining Functions
```
We can create a function that writes the Fibonacci series to an arbitrary boundary:
```
>>> def fib(n): # write Fibonacci series up to n
... |
"""Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... |
fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
```
The keyword def introduces a function definition. |
It must be followed by the function name and the
parenthesized list of formal parameters. |
The statements that form the body of the function start at the next
line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal is the function’s
documentation string, or docstring. |
(More about docstrings can be found in the section Documentation
-----
_Strings.) There are tools which use docstrings to automatically produce online or printed documentation,_
or to let the user interactively browse through code; it’s good practice to include docstrings in code that you
write, so make a habit of i... |
More
precisely, all variable assignments in a function store the value in the local symbol table; whereas variable
references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in
the global symbol table, and finally in the table of built-in names. |
Thus, global variables cannot be directly
assigned a value within a function (unless named in a global statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called
function when it is called; thus, arguments are passed using ca... |
The value of the function
name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned
to another name which can then also be used as a function. |
This serves as a general renaming mechanism:
```
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
```
Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t
return a value. |
In fact, even functions without a return statement do return a value, albeit a rather boring
one. This value is called None (it’s a built-in name). |
Writing the value None is normally suppressed by the
interpreter if it would be the only value written. |
You can see it if you really want to using print():
```
>>> fib(0)
>>> print(fib(0))
None
```
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing
it:
```
>>> def fib2(n): # return Fibonacci series up to n
... |
"""Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... |
return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
```
This example, as usual, demonstrates some new Python features:
- The return statement returns with a value from a function. |
return without an expression argument
returns None. Falling off the end of a function also returns None.
- The statement result.append(a) calls a method of the list object result. |
A method is a function
that ‘belongs’ to an object and is named obj.methodname, where obj is some object (this may be an
1 Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any
changes the callee makes to it (items inserted into a list).
-----
... |
Different
types define different methods. Methods of different types may have the same name without causing
ambiguity. |
(It is possible to define your own object types and methods, using classes, see Classes) The
method append() shown in the example is defined for list objects; it adds a new element at the end of
the list. |
In this example it is equivalent to result = result + [a], but more efficient.
### 4.7 More on Defining Functions
It is also possible to define functions with a variable number of arguments. |
There are three forms, which
can be combined.
#### 4.7.1 Default Argument Values
The most useful form is to specify a default value for one or more arguments. |
This creates a function that
can be called with fewer arguments than it is defined to allow. |
For example:
```
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
... |
This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
```
i = 5
def f(arg=i):
print(arg)
i = 6
f()
```
will print 5.
**Important warning: The default value is evaluated only once. |
This makes a difference when the default is**
a mutable object such as a list, dictionary, or instances of most classes. |
For example, the following function
accumulates the arguments passed to it on subsequent calls:
-----
This will print
```
[1]
[1, 2]
[1, 2, 3]
```
If you don’t want the default to be shared between subsequent calls, you can write the function like this
instead:
```
def f(a, L=None):
if L is None:
L = []
L.a... |
For instance, the following
function:
```
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
```
accepts one required a... |
This
function can be called in any of the following ways:
```
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 p... |
All the keyword arguments
passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument
for the parrot function), and their order is not important. |
This also includes non-optional arguments (e.g.
```
parrot(voltage=1000) is valid too). No argument may receive a value more than once. |
Here’s an example
```
that fails due to this restriction:
-----
When a final formal parameter of the form **name is present, it receives a dictionary (see typesmapping)
containing all keyword arguments except for those corresponding to a formal parameter. |
This may be
combined with a formal parameter of the form *name (described in the next subsection) which receives
a tuple containing the positional arguments beyond the formal parameter list. |
(*name must occur before
```
**name.) For example, if we define a function like this:
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.