CodeSkulptor3 is a browser-based Python interpreter, as featured in the online course “Fundamentals of Computing”. It implements a subset of Python 3 plus the addition of three graphical libraries, SimpleGui, SimpleMap, and SimplePlot.
It does not support NotImplemented, Ellipsis, complex numbers, Unicode strings, bytearrays, frozensets, exceptions, xrange objects, or memory view objects.
Mutable types are those that have operations that mutate or update part of the value. Other types are immutable. Numbers, Booleans, strings, tuples, and functions are immutable, while all other types are mutable.
In Python, all values are objects, and objects can have attributes. Attributes that are functions are known as methods. An object is an instance of a class. Some classes are built-in, like lists and sets, but others can be user-defined.
For user-defined classes, Codeskulptor supports only “classic” or “old-style” classes, not “new-style” classes. It supports instance methods, but not the less commonly used class methods and static methods.
Hashable values are any for which the Python implementation defines a way to convert it into an integer (its hash value). In practice, a value is hashable if it is immutable. CodeSkulptor does not support the standard __hash__()
method.
CodeSkulptor supports all forms of Python expressions.
See the other sections of this documentation for details on which types, operations, functions, and methods are supported.
Simple statements are those which cannot contain other statements. I.e., they are not compound. Note that in Python 3, print
is no longer a statement and is now a function.
The only unsupported simple statements are exec
, raise
.
Compound statements are those that can be built from smaller statements.
CodeSkulptor does not support try-except
statements, with
statements, “new-style” class definitions. (Note: try-except
is partially implemented, but its use is not currently recommended.)
Good code and documentation style makes programs easier to read and debug. Using a style that is consistent with other programmers further helps others to read your code.
The Python Guide on Code Style provides a good summary with examples. For a more details, see the official Python style guides for code (“PEP 8”) and docstrings (“PEP 257”).
The single value None
is known as the null object. Its type is the NoneType. It serves as a placeholder return value for functions that would otherwise return nothing. It is also used as an special argument value to some operations, such as filter()
and a_str.split()
.
int
float
+
-
*
/
//
%
**
~
&
|
^
<<
>>
abs
round
bin
oct
hex
chr
ord
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
callable
range
max
min
math.isinf
math.isnan
math.ceil
math.floor
math.trunc
math.fabs
math.log
math.log10
math.exp
math.pow
math.factorial
math.sqrt
math.e
math.pi
math.degrees
math.radians
math.hypot
math.sin
math.cos
math.tan
math.asin
math.acos
math.atan
math.atan2
math.sinh
math.cosh
math.tanh
math.asinh
math.acosh
math.atanh
random.randint
random.randrange
random.random
random.uniform
random.triangular
random.seed
time.time
simpleplot.plot_lines
simpleplot.plot_bars
simpleplot.plot_scatter
a_matrix[]
a_matrix.summation
Integers have an arbitrary number of digits.
Floating-point numbers have a decimal point and a limited number of digits. Arithmetic operations on floating-point numbers can give somewhat inaccurate results because of the limited precision.
Code | Output |
---|---|
print(12) | 12 |
print(-12.0) | -12 |
print(0b1001) | 9 |
print(021) | 17 |
print(-021) | -17 |
print(0x3A8) | 936 |
print(12345678901234567890123456789012345678901234567890) | 12345678901234567890123456789012345678901234567890 |
print(+12.12345) | 12.12345 |
print(-12.12345) | -12.12345 |
print(1.2e3) | 1200 |
print(1.2e-3) | 0.0012 |
Integers can be given in any of four bases:
Integers can be preceded by a positive or negative sign.
Floating-point numbers consist of a series of digits, a decimal point, and another series of digits. They can be preceded by an optional positive or negative sign. They can be followed by an optional exponent — the letter e
, an optional positive or negative sign, and a series of digits.
int(x)
float(x)
Code | Output |
---|---|
print(int()) | 0 |
print(int('234')) | 234 |
print(int(1.6)) | 1 |
print(int(False)) | 0 |
print(float()) | 0.0 |
print(float('3.89')) | 3.89 |
print(float('inf')) | inf |
print(float('-inf')) | -inf |
print(float(3)) | 3.0 |
print(float(False)) | 0.0 |
round()
— Rounds to nearest integermath.trunc()
— Rounds to zero (same int()
on integers)math.ceil()
— Rounds upmath.floor()
— Rounds downGiven a number, int()
returns the integer part of it, i.e., they round towards zero. Given a Boolean, they return zero (i.e., 0
, or 0.0
) for False
, and one (i.e., 1
, or 1.0
) for True
. Given a string containing a printed representation of an integer, int()
returns that integer. Similarly, given a string containing a printed representation of a number, float()
returns that number. Special cases for float()
are the inputs "inf"
and "-inf"
, representing positive and negative infinity, respectively. Given any other string, these raise a ValueError
.
a + b
Code | Output |
---|---|
print(3 + 12) | 15 |
print(3.0 + 12) | 15.0 |
print(3 + 12.0) | 15.0 |
Returns the sum of a
and b
. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard addition operation.
Addition and assignment can be combined with the shorthand a += b
, which is equivalent to a = a + b
.
a - b
- a
Code | Output |
---|---|
print(12 - 3) | 9 |
print(12.0 - 3) | 9.0 |
print(12 - 3.0) | 9.0 |
a = 3 print(-a) | -3 |
With two arguments, returns the difference of a
and b
. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard subtraction operation.
With one argument, return the negation of a
. Equivalent to 0 - a
.
Subtraction and assignment can be combined with the shorthand a -= b
, which is equivalent to a = a - b
.
a * b
Code | Output |
---|---|
print(3 * 12) | 36 |
print(3.0 * 12) | 36.0 |
print(3 * 12.0) | 36.0 |
Returns product of a
and b
. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard multiplication operation.
Multiplication and assignment can be combined with the shorthand a *= b
, which is equivalent to a = a * b
.
a / b
a // b
Code | Output |
---|---|
print(12 / 3) | 4.0 |
print(11 / 3) | 3.6666666666666665 |
print(11 // 3) | 3 |
print(12 / 3.0) | 4.0 |
print(11.0 / 3) | 3.6666666666666665 |
print(11.0 // 3.0) | 3.0 |
The standard division operation, /
, returns the quotient of a
and b
. The result is a floating-point number.
The integer division operation, //
, returns the floor of the quotient of a
and b
, i.e., the integer part. The result is an integer if both inputs are; otherwise, it is a floating-point.
Division and assignment can be combined with the shorthand a /= b
and a //= b
, which are equivalent to a = a / b
and a = a // b
, respectively.
x % m
Code | Output |
---|---|
print(11 % 3) | 2 |
Returns the remainder of x // m
.
Modulo and assignment can be combined with the shorthand x %= m
, which is equivalent to x = x % m
.
x ** y
Code | Output |
---|---|
print(3 ** 4) | 81 |
print(3.0 ** 4) | 81.0 |
print(3 ** 4.0) | 81.0 |
pow()
— Built-in exponentiation functionmath.pow()
and math.exp()
— Similar exponentiation functionsReturns x
to the power of y
. The result is an integer if both inputs are; otherwise, it is a floating-point.
Exponentiation and assignment can be combined with the shorthand x **= y
, which is equivalent to x = x ** y
.
pow(x, y)
pow(x, y, m)
Code | Output |
---|---|
print(pow(3, 4)) | 81 |
print(pow(3.0, 4)) | 81.0 |
print(pow(3, 4.0)) | 81.0 |
print(pow(3, 4, 2)) | 1 |
**
— Built-in exponentiation operatormath.pow()
and math.exp()
— Similar exponentiation functionsGiven no m
, this returns x
to the power of y
, just like x ** y
. Given a integer m
, this returns the remainder of integer x
to the power of integer y
, divided by m
. The result is an integer if all inputs are; otherwise, it is a floating-point.
abs(x)
Code | Output |
---|---|
print(abs(3)) | 3 |
print(abs(-3.0)) | 3.0 |
math.fabs()
— Always returns a floating-point numberReturns the absolute value of number x
. The result is of the same type as the input.
round(n)
round(n, i)
Code | Output |
---|---|
print(round(12)) | 12 |
print(round(12.5)) | 13 |
print(round(-12.5)) | -12 |
print(round(123.4567, 2)) | 123.46 |
print(round(123.4567, -2)) | 100.0 |
int()
— Round to zeromath.trunc()
— Rounds to zeromath.ceil()
— Rounds upmath.floor()
— Rounds downWith one number argument, it returns the integer nearest n
.
With two number arguments, it returns the floating-point number that represents n
rounded to the nearest unit of 10i
, for integer i
. I.e., when i
is positive, this is the familiar idea of rounding to i
places after the decimal. However, i
can be zero or negative, as well.
In either case, a 5 digit is always rounded up.
bin(x)
oct(x)
hex(x)
Code | Output |
---|---|
print(bin(9)) | 0b1001 |
print(oct(-17)) | -021 |
print(hex(936)) | 0x3a8 |
Given an integer, returns a string representing that number in binary, octal, or hexadecimal, respectively. The resulting string is in the same syntax as Python integer constants.
chr(i)
Code | Output |
---|---|
print(chr(97)) | a |
Returns a string of one character whose ASCII code is the integer i
. This is the inverse of ord()
.
ord(x)
Code | Output |
---|---|
print(ord('a')) | 97 |
Given a string of length one, returns an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. This is the inverse of chr()
for 8-bit strings.
~x
x & y
x | y
x ^ y
x << n
x >> n
Code | Output |
---|---|
print(~0) # binary: 000 | -1 # binary: 111 |
print(~-1) # binary: 111 | 0 # binary: 000 |
print(~13) # binary: 01101 | -14 # binary: 10010 |
print(-1 & -1) # binary: 111 & 111 | -1 # binary: 111 |
print(14 & 7) # binary: 01110 & 00111 | 6 # binary: 00110 |
print(14 | 7) # binary: 01110 | 00111 | 15 # binary: 01111 |
print(14 ^ 7) # binary: 01110 ^ 00111 | 9 # binary: 01001 |
print(5 << 3) # binary: 0101 << 3 | 40 # binary: 0101000 |
print(23 >> 2) # binary: 010111 << 2 | 5 # binary: 0101 |
These operators all use the underlying twos-complement binary representation of the integral part of the numbers x
and y
.
~x
: bitwise not (negation) of x
x & y
: bitwise and (conjunction) of x
and y
x | y
: bitwise or (disjunction) of x
and y
x ^ y
: bitwise exclusive or of x
and y
x << n
: bitwise shift left of x
by n
bitsx >> n
: bitwise shift right of x
by n
bitsTrue
and False
are then treated as 1
and 0
, respectively.Booleans represent the logical truth values True and False. Expressions that evaluate to Boolean values are especially used as the tests in conditionals (if boolean_expr: …
).
True
False
There are only two Boolean constants, True
and False
. They must be capitalized as shown.
In addition, the following constants are treated like False
in a logical expression:
None
0
0.0
''
[]
()
{}
set([])
All other values are treated like True
in logical expressions.
A values of a user-defined class is treated like False
if it has a __nonzero__()
method that returns False
or if it has a __len__()
method that returns 0
.
bool(x)
Code | Output |
---|---|
print(bool(1)) | True |
print(bool(2.3)) | True |
print(bool(0)) | False |
print(bool([])) | False |
print(bool([1, 2, 3])) | True |
print(bool(())) | False |
print(bool((1, 2, 3))) | True |
print(bool('')) | False |
print(bool('abc')) | True |
print(bool({})) | False |
print(bool({1: 2})) | True |
print(bool(set([]))) | False |
print(bool(set([1, 2, 3]))) | True |
True
for any true-like value, and False
for any false-like value.x and y
Code | Output |
---|---|
print(True and True) | True |
print(False and True) | False |
print(1 and 2) | 2 |
print(0 and 2) | 0 |
If x
is False
or any false-like value, then this expression results in x
, otherwise this expression results in y
.
x | y | x and y |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
x or y
Code | Output |
---|---|
print(True or True) | True |
print(False or True) | True |
print(1 or 2) | 1 |
print(0 or 2) | 2 |
If x
is False
or any false-like value, then this expression results in y
, otherwise it results in x
.
x | y | x or y |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Note that in English, the word “or” is used in two different ways. This operation represents “inclusive or” (x or y
), where the result is True
if at least one argument is True
. In contrast, the “exclusive or” (x != y
) is True
if exactly one argument is True
.
not x
Code | Output |
---|---|
print(not True) | False |
print(not False) | True |
print(not 2) | False |
print(not 0) | True |
If x
is False
or any false-like value such as 0
or []
, then this expression results in True
, otherwise it results in False
.
x | not x |
---|---|
True | False |
False | True |
x if b else y
Code | Output |
---|---|
print(1 if True else 2) | 1 |
print(1 if False else 2) | 2 |
If the Boolean condition b
is False
is true (or true-like), then the result is x
. Otherwise, the result is y
.
str
repr
%
a_str.join
a_str.capitalize
a_str.upper
a_str.lower
a_str.replace
a_str.find
a_str.rfind
a_str.index
a_str.rindex
a_str.partition
a_str.rpartition
a_str.split
a_str.isdigit
a_str.center
a_str.ljust
a_str.rjust
a_str.startswith
a_str.endswith
a_str.strip
a_str.lstrip
a_str.rstrip
+
*
[]
[:]
[::]
a_seq.index
a_seq.count
in
not in
len
sum
max
min
zip
sorted
map
filter
reduce
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
callable
bin
oct
hex
chr
ord
re.findall
re.search
re.match
re.split
A string is an immutable sequence of characters. Many characters are familiar from what you can type on a keyboard — a letter, a number, a symbol, or a space. The string with zero characters is called the empty string.
"…"
'…'
"""…"""
'''…'''
r"…"
r'…'
r"""…"""
r'''…'''
Code | Output |
---|---|
print("") | # The empty string. |
print('Hello, world.') | Hello, world. |
print("Goodbye, cruel world.") | Goodbye, cruel world. |
print("It's a beautiful day.") | It's a beautiful day. |
print("""This is a multi-line string.""") | This is a multi-line string. |
Typically, string constants are constructed within a matched pair of single or double quotes. A string with double quotes can contain single quotes, often used as apostrophes. Similarly, a string with single quotes can contain double quotes.
Using a pair of triple-single or triple-double quotes also creates a string, but also allows the string to span over multiple lines. These are primarily used as documentation strings to document the purpose of a function, method, or class definition.
Strings can contain ASCII characters.
Strings can contain escape sequences:
\' | single quote character |
---|---|
\" | double quote character |
\\ | backslash character |
\b | backspace character |
\f | formfeed character |
\n | new line character (starts a new line) |
\r | carriage return character |
\t | horizontal tab character (moves to next tab position, which is every eight characters) |
\v | vertical tab character |
\x<var>NN</var> | ASCII character represented by a hexidecimal number NN |
However, raw strings, those preceded by an r
, do not recognize escape sequences. Raw strings are typically used for regular expressions.
str(x)
Code | Output |
---|---|
print(str()) | # The empty string |
print(str(4859202)) | 4859202 |
print(str(True)) | True |
print(str('abc')) | abc |
print(str(None)) | None |
print(str((1, 2, 3, 4, 5))) | (1, 2, 3, 4, 5) |
print(str([1, 2, 3, 4, 5])) | [1, 2, 3, 4, 5] |
print(str({1: 'a', 2: 'b', 3: 'c'})) | {1: 'a', 2: 'b', 3: 'c'} |
print(str(set([1, 2, 3, 4, 5]))) | set([1, 2, 3, 4, 5]) |
print(str(str)) | <class 'str'> |
class Silly: def __init__(self, x): self.x = xprint(repr(Silly(3))) | <__main__.Silly object> |
class Silly: def __init__(self, x): self.x = x def __str__(self): return 'Silly' + str(self.x)print(str(Silly(3))) | Silly3 |
repr()
— Emphasizes unambiguityReturns a string that is a printable representation of object an_obj
. The intent is that this string should be human-readable. For built-in types, this is the normal printed representation. For user-defined types, this defaults to a string in angle brackets that includes the type of the object. However, a class can specify what this function returns for its instances by defining a __str__()
method.
repr(an_obj)
Code | Output |
---|---|
print(repr([3, 5, 9])) | [3, 5, 9] |
class Silly: def __init__(self, x): self.x = xprint(repr(Silly(3))) | <__main__.Silly object> |
class Silly: def __init__(self, x): self.x = x def __repr__(self): return 'Silly' + str(self.x)print(repr(Silly(3))) | Silly3 |
str()
— Emphasizes readabilityReturns a string that is a printable representation of object an_obj
. The intent is that this string should be unambiguous. For built-in types, this is the normal printed representation. For user-defined types, this defaults to a string in angle brackets that includes the type of the object. However, a class can specify what this function returns for its instances by defining a __repr__()
method.
a_str.format(...)
Code | Output |
---|---|
new_style = 'The best instructors are {0} and {1}.'.format('Scott', 'Joe') print(new_style) | The best instructors are Scott and Joe. |
new_style = 'The best instructor is {1}.'.format('Scott', 'Joe') print(new_style) | The best instructor is Joe. |
Return a copy of a_str
with each instance of the substring "{n}"
replaced by the n+1st argument to format
. CodeSkulptor also supports old-style string formatting old-style string formatting. See this example for instances of both new-style and old-style string formatting.
a_str.join([iterable])
Code | Output |
---|---|
print(','.join('abcd')) | a,b,c,d |
print(' '.join(['a', 'bc', 'd'])) | a bc d |
print('zz'.join(('a', 'bc', 'd'))) | azzbczzd |
print(' '.join({'a': 'x', 'b': 'y'})) | a b |
print(' '.join(set(['a', 'b']))) | a b |
Returns a string which is the concatenation of the strings in the iterable. The string a_str
is concatenated between the other strings as a separator.
Most commonly used to combine a list of strings into a single string.
a_str.capitalize()
Code | Output |
---|---|
print('peAr'.capitalize()) | Pear |
Return a copy of the string a_str
with its first character capitalized and the rest lower-cased.
a_str.upper()
a_str.lower()
Code | Output |
---|---|
print('abc123DEF'.upper()) | ABC123DEF |
print('abc123DEF'.lower()) | abc123def |
Returns a copy of the string a_str
with all the cased characters converted to upper- or lowercase, respectively
a_str.replace(old, new)
a_str.replace(old, new, maxreplace)
Code | Output |
---|---|
print('abcdabcd'.replace('bc', 'f')) | afdafd |
print('abcdabcd'.replace('bc', 'f', 1)) | afdabcd |
print('abcdabcd'.replace('g', 'f')) | abcdabcd |
print('aaaaa'.replace('aa', 'f')) | ffa |
Returns a copy of the string a_str
with all occurrences of substring old
replaced by new
. If the optional argument maxreplace
is given, then the first at most maxreplace
occurrences are replaced.
a_str.find(sub)
a_str.find(sub, start)
a_str.find(sub, start, end)
a_str.rfind(sub)
a_str.rfind(sub, start)
a_str.rfind(sub, start, end)
a_str.index(sub)
a_str.index(sub, start)
a_str.index(sub, start, end)
a_str.rindex(sub)
a_str.rindex(sub, start)
a_str.rindex(sub, start, end)
Code | Output |
---|---|
print('abcdabcd'.find('bc')) | 1 |
print('abcdabcd'.find('bc', 3)) | 5 |
print('abcdabcd'.find('bc', 3, 6)) | 5 |
print('abcdabcd'.rfind('bc')) | 5 |
print('abcdabcd'.rfind('bc', 3)) | 5 |
print('abcdabcd'.find('f')) | -1 |
print('abcdabcd'.rfind('f')) | -1 |
print('abcdabcd'.find('bc', 6)) | -1 |
print('abcdabcd'.rfind('bc', 6)) | -1 |
print('abcdabcd'.find('bc', 3, 5)) | -1 |
Returns the highest index in the string a_str
where substring sub
is found, such that sub
is contained within a_str[start:end]
, where start
defaults to 0, and end
defaults to the length of a_str
.
If the substring isn't found, a_str.find()
and a_str.rfind()
each return -1, while a_str.index()
and a_str.rindex()
each raise an error.
a_str.partition(sep)
a_str.rpartition(sep)
Code | Output |
---|---|
print('a b c'.partition(' ')) | ('a', ' ', 'b c') |
print('a b c'.rpartition(' ')) | ('a b', ' ', 'c') |
a_str.split()
— Splits multiple timesre.split()
— Splits on more general patternsSplits the string a_str
at the first (partition
) or last (rpartition
) occurrence of substring sep
, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing two empty strings, followed by the string itself.
a_str.split()
a_str.split(sep)
a_str.split(sep, maxsplit)
Code | Output |
---|---|
print('a bc d'.split()) | ['a', 'bc', 'd'] |
print('a bc d'.split(None)) | ['a', 'bc', 'd'] |
print('a bc d'.split(' ')) | ['a', '', '', '', 'bc', 'd'] |
print('a bc d'.split(' ')) | ['a', '', ' bc d'] |
print('a bc d'.split('b')) | ['a ', 'c d'] |
print('ababbaaaa'.split('a', 2)) | ['', 'b', 'bbaaaa'] |
a_str.partition()
, etc. — Splits only oncere.split()
— Splits on more general patternsReturns a list of the words in the string a_str
, using sep
as the delimiter string. If maxsplit
is given, at most maxsplit
splits are done, the rightmost ones. If sep
is not specified or is None
, any whitespace string is a separator.
a_str.isdigit()
Code | Output |
---|---|
print(''.isdigit()) | False |
print('1234'.isdigit()) | True |
print('1234abc'.isdigit()) | False |
Returns whether all characters in the string a_str
are digits and that there is at least one character in the string.
a_str.center(width)
a_str.center(width, fillchar)
a_str.ljust(width)
a_str.ljust(width, fillchar)
a_str.rjust(width)
a_str.center(width, fillchar)
Code | Output |
---|---|
print('*' + 'abcd'.center(30) + '*') | * abcd * |
print('abcd'.ljust(30) + '*') | abcd * |
print('abcd'.rjust(30)) | abcd |
print('*' + 'abcd'.center(30, 'x') + '*') | *xxxxxxxxxxxxxabcdxxxxxxxxxxxxx* |
print('abcd'.ljust(30, 'x') + '*') | abcdxxxxxxxxxxxxxxxxxxxxxxxxxx* |
print('abcd'.rjust(30, 'x')) | xxxxxxxxxxxxxxxxxxxxxxxxxxabcd |
Returns a_str
aligned in a string of length width. The fill character defaults to a space. a_str.center()
centers the string, a_str.ljust()
left justifies it, and a_str.rjust()
right justifies it.
These are typically used in simple output formatting to produce fixed-width columns.
a_str.startswith(prefix)
Code | Output |
---|---|
print('silly string'.startswith('sil')) | True |
print('silly string'.startswith('ing')) | False |
a_str.endswith()
— Checks suffixReturns whether the string a_str
begins with the string prefix
.
a_str.endswith(suffix)
Code | Output |
---|---|
print('silly string'.endswith('sil')) | False |
print('silly string'.endswith('ing')) | True |
a_str.startswith()
— Checks prefixReturns whether the string a_str
ends with the string suffix
.
a_str.strip(s)
a_str.strip(s, chars)
a_str.lstrip(s)
a_str.lstrip(s, chars)
a_str.rstrip(s)
a_str.rstrip(s, chars)
Code | Output |
---|---|
print(' cde fgh '.strip()) | cde fgh |
print(' cde fgh '.strip(None)) | cde fgh |
print('aaababcdeababfghbaba'.strip('ab')) | cdeababfgh |
print(' cde fgh '.lstrip()) | cde fgh |
print('aaababcdeababfghbaba'.lstrip('ab')) | cdeababfghbaba |
print(' cde fgh '.rstrip()) | cde fgh |
print('aaababcdeababfghbaba'.rstrip('ab')) | aaababcdeababfgh |
These return a new string like a_str
except that leading (a_str.lstrip()
), trailing (a_str.rstrip()
), or both (a_str.strip()
) characters are removed. They remove any characters given in chars
, which defaults to any whitespace characters. Also, if chars
is None
, these also remove whitespace characters.
A bytes object is an immutable sequence of bytes. This is a representation of binary data that must be interpreted by the program. Often bytes are read from a file and represent its contents Given that they often represent characters, bytes share many operations with strings.
b"…"
b'…'
b"""…"""
b'''…'''
Code | Output |
---|---|
print(b"") | b'' # The empty bytes object. |
print(b'Hello, world.') | b'Hello, world.' |
print(b"Goodbye, cruel world.") | b'Goodbye, cruel world.' |
print(b"It's a beautiful day.") | b'It's a beautiful day.' |
print(b"""This is a multi-line bytes object.""") | b'This is\na multi-line\nbytes object.' |
Bytes constants can be constructed within a matched pair of single or double quotes preceeded by a 'b' character. A bytes object with double quotes can contain single quotes, often used as apostrophes. Similarly, a bytes object with single quotes can contain double quotes.
Using a pair of triple-single or triple-double quotes preceeded by a 'b' character also creates a bytes object, but also allows the bytes object to span over multiple lines.
Bytes objects can contain escape sequences:
\' | single quote character |
---|---|
\" | double quote character |
\\ | backslash character |
\b | backspace character |
\f | formfeed character |
\n | new line character (starts a new line) |
\r | carriage return character |
\t | horizontal tab character (moves to next tab position, which is every eight characters) |
\v | vertical tab character |
\x<var>NN</var> | byte represented by a hexidecimal number NN |
bytes(x)
Code | Output |
---|---|
print(bytes()) | b'' # The empty bytes object |
print(bytes("abc", "ascii")) | b'abc' |
print(bytes([64, 65, 66])) | b'@AB' |
print(bytes(4)) | b'' |
Returns a bytes object that contains the sequence of bytes represented by the input. A string can be converted into bytes, as long as the optional second argument is provided indicating the character encoding of the string ("ascii" or "utf-8"). Regardless of the encoding, however, all characters in the input string must be ASCII characters. A list of numbers (which all must be between 0 and 255) can be used to indicate the exact sequence of bytes. A single number can be used to create a bytes object with the given number of bytes, each with the value 0.
a_bytes.decode(encoding)
a_bytes.decode(encoding, errors)
Code | Output |
---|---|
print(b"abc".decode("ascii")) | abc |
print(bytes([65, 66, 200]).decode("utf-8", "replace")) | AB� |
a_bytes.hex()
— Returns a string with hexidecimal valuesReturns a string decoded from the given bytes. Possible encodings to use are "utf-8" and "ascii". The optional second argument indicates how to deal with data in the bytes object that are not valid string characters. Possible values are "string" (the default), meaning invalid characters raise an error, "ignore", meaning invalid characters will be ignored and not appear in the output string, and "replace", meaning invalid characters will be replaced with the Unicode replacement character (U+FFFD).
a_bytes.hex()
Code | Output |
---|---|
print(b"\xab\xf3\x08".hex()) | 'abf308' |
a_bytes.decode()
— Returns a string with the characters decoded from the given bytesReturn a string containing two hexidecimal digits for each byte.
a_bytes.join([iterable])
Code | Output |
---|---|
print(b','.join([b'a', b'b'])) | b'a,b' |
print(b' '.join([b'a', b'bc', b'd'])) | b'a bc d' |
print(b'zz'.join((b'a', b'bc', b'd'))) | b'azzbczzd' |
print(b' '.join({b'a': 'x', b'b': 'y'})) | b'a b' |
print(b' '.join(set([b'a', b'b']))) | b'a b' |
Returns a bytes object which is the concatenation of the bytes objects in the iterable. The bytes object a_bytes
is concatenated between the other bytes objects as a separator.
Most commonly used to combine a list of bytes objects into a single bytes object.
a_bytes.capitalize()
Code | Output |
---|---|
print(b'peAr'.capitalize()) | b'Pear' |
Return a copy of the bytes a_bytes
with its first character capitalized and the rest lower-cased.
a_bytes.upper()
a_bytes.lower()
Code | Output |
---|---|
print(b'abc123DEF'.upper()) | b'ABC123DEF' |
print(b'abc123DEF'.lower()) | b'abc123def' |
Returns a copy of the bytes object a_bytes
with all the cased characters converted to upper- or lowercase, respectively
a_bytes.replace(old, new)
a_bytes.replace(old, new, maxreplace)
Code | Output |
---|---|
print(b'abcdabcd'.replace(b'bc', b'f')) | b'afdafd' |
print(b'abcdabcd'.replace(b'bc', b'f', 1)) | b'afdabcd' |
print(b'abcdabcd'.replace(b'g', b'f')) | b'abcdabcd' |
print(b'aaaaa'.replace(b'aa', b'f')) | b'ffa' |
Returns a copy of the bytes object a_bytes
with all occurrences of substring old
replaced by new
. If the optional argument maxreplace
is given, then the first at most maxreplace
occurrences are replaced.
a_bytes.find(sub)
a_bytes.find(sub, start)
a_bytes.find(sub, start, end)
a_bytes.rfind(sub)
a_bytes.rfind(sub, start)
a_bytes.rfind(sub, start, end)
a_bytes.index(sub)
a_bytes.index(sub, start)
a_bytes.index(sub, start, end)
a_bytes.rindex(sub)
a_bytes.rindex(sub, start)
a_bytes.rindex(sub, start, end)
Code | Output |
---|---|
print(b'abcdabcd'.find(b'bc')) | 1 |
print(b'abcdabcd'.find(b'bc', 3)) | 5 |
print(b'abcdabcd'.find(b'bc', 3, 6)) | 5 |
print(b'abcdabcd'.rfind(b'bc')) | 5 |
print(b'abcdabcd'.rfind(b'bc', 3)) | 5 |
print(b'abcdabcd'.find(b'f')) | -1 |
print(b'abcdabcd'.rfind(b'f')) | -1 |
print(b'abcdabcd'.find(b'bc', 6)) | -1 |
print(b'abcdabcd'.rfind(b'bc', 6)) | -1 |
print(b'abcdabcd'.find(b'bc', 3, 5)) | -1 |
Returns the highest index in the bytes object a_bytes
where sub
is found, such that sub
is contained within a_bytes[start:end]
, where start
defaults to 0, and end
defaults to the length of a_bytes
.
If the bytes aren't found, a_bytes.find()
and a_bytes.rfind()
each return -1, while a_bytes.index()
and a_bytes.rindex()
each raise an error.
a_bytes.partition(sep)
a_bytes.rpartition(sep)
Code | Output |
---|---|
print(b'a b c'.partition(b' ')) | (b'a', b' ', b'b c') |
print(b'a b c'.rpartition(b' ')) | (b'a b', b' ', b'c') |
Splits the bytes object a_bytes
at the first (partition
) or last (rpartition
) occurrence of substring sep
, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing two empty bytes objects, followed by the bytes object itself.
a_bytes.startswith(prefix)
Code | Output |
---|---|
print(b'silly string'.startswith(b'sil')) | True |
print(b'silly string'.startswith(b'ing')) | False |
a_bytes.endswith()
— Checks suffixReturns whether the bytes object a_bytes
begins with the bytes prefix
.
a_bytes.endswith(suffix)
Code | Output |
---|---|
print(b'silly string'.endswith(b'sil')) | False |
print(b'silly string'.endswith(b'ing')) | True |
a_bytes.startswith()
— Checks prefixReturns whether the bytes object a_bytes
ends with the bytes suffix
.
[val0, val1, …]
Code | Output |
---|---|
print([]) | [] |
print([1, 2, 3, 8, 9]) | [1, 2, 3, 8, 9] |
print([(1, 2), 'hello', 3, ['a', 'b', 'c']]) | [(1, 2), 'hello', 3, ['a', 'b', 'c']] |
Lists are constructed with square brackets, separating items with commas.
[val0, val1, …]
Code | Output |
---|---|
print([]) | [] |
print([1, 2, 3, 8, 9]) | [1, 2, 3, 8, 9] |
print([(1, 2), 'hello', 3, ['a', 'b', 'c']]) | [(1, 2), 'hello', 3, ['a', 'b', 'c']] |
Lists are constructed with square brackets, separating items with commas.
list()
list(an_iter)
Code | Output |
---|---|
print(list()) | [] |
print(list('abc')) | ['a' ,'b', 'c'] |
print(list([1, 2, 3, 4, 5])) | [1, 2, 3, 4, 5] |
print(list((1, 2, 3, 4, 5))) | [1, 2, 3, 4, 5] |
print(list(set([1, 2, 3, 4]))) | [1, 2, 3, 4] |
print(list({1: 2, 3: 4})) | [1, 3] |
print(list(enumerate(['a', 'b', 'c', 'd']))) | [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] |
Converts any iterable or iterator into a list. If the argument is already a list, it returns a copy, i.e., a new list with the same elements.
a_list[index] = value
Code | Output |
---|---|
numbers = [4, 8, 19, 0] numbers[1] = 27 print(numbers) | [4, 27, 19, 0] |
Mutates the list to now contain the given value at the given index. The index must be within the current range of indices of the list.
range(stop)
range(start, stop)
range(start, stop, step)
Code | Output |
---|---|
print(list(range(5))) | [0, 1, 2, 3, 4] |
print(list(range(1, 10))) | [1, 2, 3, 4, 5, 6, 7, 8, 9] |
print(list(range(-10, 100, 20))) | [-10, 10, 30, 50, 70, 90] |
print(list(range(100, -10, -20))) | [100, 80, 60, 40, 20, 0] |
for i in range(5): print(i) | 0 1 2 3 4 |
This is a versatile function to create a generator-like object representing progressions. The step
cannot be zero, and it defaults to 1. The start
defaults to 0. As a list, the full form consists of a list of integers [start, start + step, start + 2 * step, …]
. If step
is positive, the last element is the largest start + i * step
less than stop
; if step
is negative, the last element is the smallest start + i * step
greater than stop
.
Note that range
does not return a list in Python 3. To create the corresponding list, one should use an expression of the form list(range(...))
. range
is often used in for
loops, as illustrated in the last example above, and does not need to be converted to a list first in order to do so. It provides a mechanism for looping a specific number of iterations.
a_list.append(x)
Code | Output |
---|---|
a_list = [1, 2, 3] a_list.append(4) a_list.append([5, 6, 7]) print(a_list) | [1, 2, 3, 4, [5, 6, 7]] |
list1 = [1, 2, 3] list2 = [1, 2, 3] list1.append([4, 5, 6]) list2.extend([4, 5, 6]) print(list1) print(list2) | [1, 2, 3, [4, 5, 6]] [1, 2, 3, 4, 5, 6] |
Add item x
to the end of the list a_list
.
A common mistake is to confuse a_list.append(x)
and a_list.extend(x)
. As shown in the last example above, the former adds one element to the list, while the latter adds a group of elements.
a_list.extend(an_iter)
Code | Output |
---|---|
a_list = [1, 2, 3] a_list.extend([]) print(a_list) | [1, 2, 3] |
a_list = [1, 2, 3] a_list.extend([4, 5, 6]) a_list.extend((7, 8)) a_list.extend('abc') a_list.extend({'d': 'e', 'f': 'g'}) | [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 'd', 'f'] |
list1 = [1, 2, 3] list2 = [1, 2, 3] list1.append([4, 5, 6]) list2.extend([4, 5, 6]) print(list1) print(list2) | [1, 2, 3, [4, 5, 6]] [1, 2, 3, 4, 5, 6] |
Add each item from the iterable an_iter
onto the end of the list a_list
. When the iterable is a list, this is also called concatenation.
A common mistake is to confuse a_list.append(x)
and a_list.extend(x)
. As shown in the last example above, the former adds one element to the list, while the latter adds a group of elements.
a_list.insert(i, x)
Code | Output |
---|---|
a_list = ['a', 'b', 'c'] a_list.insert(1, 'x') print(a_list) a_list.insert(0, 'y') print(a_list) a_list.insert(5, 'z') print(a_list) | ['a', 'x', 'b', 'c'] ['y', 'a', 'x', 'b', 'c'] ['y', 'a', 'x', 'b', 'c', 'z'] |
Inserts an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x)
inserts at the front of the list, and a.insert(len(a), x)
is equivalent to a.append(x)
.
a_list.remove(x)
Code | Output |
---|---|
a_list = ['a', 'b', 'c', 'b'] a_list.remove('b') print(a_list) | ['a', 'c', 'b'] |
Removes the first item from the list whose value is x
. It is an error if there is no such item.
a_list.pop([index])
Code | Output |
---|---|
a_list = ['a', 'b', 'c'] print(a_list.pop(1)) print(a_list) | b ['a', 'c'] |
Removes the item at the given index in the list a_list
, and returns it. If no index is specified, it defaults to the last item.
a_list.reverse()
Code | Output |
---|---|
a_list = [1, 2, 3] a_list.reverse() print(a_list) | [3, 2, 1] |
Reverses the elements of the list a_list
in place.
a_list.sort()
a_list.sort(reverse=rev_bool, key=key_fn)
Code | Output |
---|---|
a_list = [2, 1, 3, 2] a_list.sort() print(a_list) | [1, 2, 2, 3] |
a_list = [2, 1, 3, 2] a_list.sort(reverse=True) print(a_list) | [3, 2, 2, 1] |
words = 'This is a test string from Andrew.'.split() words.sort(key=str.lower print(words) | ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] |
Sorts the items of the list a_list
in ascending order in place. I.e., it mutates a_list
. It returns None
.
By default or when rev_bool
is False
, the elements are in ascending order. When rev_bool
is True
, the elements are in descending order. If the elements are of different types, then the ascending or descending ordering is based upon their hash values.
The key
argument to sort is a function that is called on each element before sorting. The result of the key function is used in the sort, but the original values in the list are put into the output.
The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.
[expr for var1 in for_expr1 …]
[expr for var1 in for_expr1 … if if_expr]
Code | Output |
---|---|
print([x*x for x in range(4)]) | [0, 1, 4, 9] |
print([x+y for x in [1,2,5] for y in [6,2,1] if y!=x]) | [7, 3, 8, 3, 11, 7, 6] |
{key_expr: val_expr for … if …}
— Dictionary comprehension{expr for … if …}
— Set comprehension(expr for … if …)
— Generator expressionSuch a list comprehension iterates over each of for_expr1
, …. For each combination of loop variables var1
, …, that passes any condition if_expr
, the value expr
is put in the resulting list.
A tuple is an immutable sequence of values of any type. Tuple elements are indexed by sequential integers, starting with zero.
(val0, val1, …)
Code | Output |
---|---|
print(()) | () |
print((1,)) | (1,) |
t = 1, print(t) | (1,) |
print((1, 2, 3, 8, 9)) | (1, 2, 3, 8, 9) |
t = 1, 2, 3, 8, 9 print(t) | (1, 2, 3, 8, 9) |
print(((1, 2), 'hello', 3, ['a', 'b', 'c'])) | ((1, 2), 'hello', 3, ['a', 'b', 'c']) |
t = 1, 2, 3 print(t) | (1, 2, 3) |
Tuples are constructed by the comma operator, with or without enclosing parentheses. An empty tuple must have the enclosing parentheses. A single item tuple must have a trailing comma.
tuple()
tuple(an_iter)
Code | Output |
---|---|
print(tuple()) | () |
print(tuple('abc')) | ('a' ,'b', 'c') |
print(tuple([1, 2, 3, 4, 5])) | (1, 2, 3, 4, 5) |
print(tuple((1, 2, 3, 4, 5))) | (1, 2, 3, 4, 5) |
print(tuple(set([1, 2, 3, 4]))) | (1, 2, 3, 4) |
print(tuple({1: 2, 3: 4})) | (1, 3) |
print(tuple(enumerate(['a', 'b', 'c', 'd']))) | ((0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')) |
Converts any iterable into a tuple. If the argument is already a tuple, it returns a copy, i.e., a new tuple with the same elements.
A dictionary is a mutable mapping from keys to values. A dictionary with no keys is called an empty dictionary. Dictionaries are also known in some programming languages as associative memories, associative arrays, or hashmaps. Unlike sequences, which are indexed by a range of integers, dictionaries are indexed by keys, which are any hashable values. Thus, dictionaries are also unordered. When printed, iterated upon, or converted into a sequence, its elements will appear in an arbitrary, implementation-dependent order.
{key<sub>0</sub>: value<sub>0</sub>, key<sub>1</sub>: value<sub>1</sub>, … }
Code | Output |
---|---|
print({}) | {} |
print({1: 'a', 2: 'b', 9: 'c'}) | {1: 'a', 2: 'b', 9: 'c'} |
print({1: 'a', (5, 'item'): [100], 'key': {True: 'hello', -9: 0}}) | {1: 'a', (5, 'item'): [100], 'key': {True: 'hello', -9: 0}} |
A dictionary is an unordered collection of key: value
pairs, with each key in a dictionary being distinct.
dict()
dict(an_iter)
Code | Output |
---|---|
print(dict()) | {} |
print(dict([(1, 'a'), (2, 'b'), (3, 'c')])) | {1: 'a', 2: 'b', 3: 'c'} |
print(dict(((1, 'a'), (2, 'b'), (3, 'c'), (3, 'd')))) | {1: 'a', 2: 'b', 3: 'd'} |
print(dict(set([(1, 'a'), (2, 'b'), (3, 'c')]))) | {1: 'a', 2: 'b', 3: 'c'} |
print(dict({1: 'a', 2: 'b', 3: 'c'})) | {1: 'a', 2: 'b', 3: 'c'} |
print(dict(enumerate(['a', 'b', 'c', 'd']))) | {0: 'a', 1: 'b', 2: 'c', 3: 'd'} |
Returns a new dictionary with the data from an_iter
. The iterable or iterator an_iter
must consist of pairs of a valid key (i.e., of immutable type) and value. If any key occurs multiple times, then the last value encountered for that key will be in the resulting dictionary. If an_iter
is already a dictionary, it returns a copy, i.e., a new dictionary with the same elements.
a_dict[key]
a_dict.get(key)
a_dict.get(key, value)
Code | Output |
---|---|
print({1: 'a', 2: 'b', 3: 'c'}[2]) | b |
print({1: 'a', 2: 'b', 3: 'c'}.get(2)) | b |
print({1: 'a', 2: 'b', 3: 'c'}.get(7)) | None |
print({1: 'a', 2: 'b', 3: 'c'}.get(7, 'not here')) | not here |
a_dict.get(key)
without a default.If the key is in the dictionary, these each return the value associated with the given key the dictionary a_dict
.
If the key is not in the dictionary, then a_dict[key]
raises a KeyError
error. However, a_dict.get(key)
returns value
if provided, and None
otherwise.
a_dict[key] = value
a_dict.__setitem__(key, value)
a_dict.setdefault(key)
a_dict.setdefault(key, value)
Code | Output |
---|---|
d = {1: 'a', 2: 'b', 3: 'c'} d[3] = 'd' d[4] = 'e' print(d) | {1: 'a', 2: 'b', 3: 'd', 4: 'e'} |
d = {1: 'a', 2: 'b', 3: 'c'} d.setdefault(3, 'd') d.setdefault(4, 'e') print(d) | {1: 'a', 2: 'b', 3: 'c', 4: 'e'} |
a_dict.__setitem__()
.a_dict[key] = value
and a_dict.__setitem__()
each mutate the dictionary a_dict
so that the given key now maps to the given value.
a_dict.setdefault(key, value)
similarly mutates the dictionary, but only if the key does not exist in the dictionary. The value
defaults to None
.
a_dict.pop(key)
a_dict.pop(key, default)
Code | Output |
---|---|
d = {1: 'a', 2: 'b', 3: 'c'} print(d.pop(1)) print(d) | a {2: 'b', 3: 'c'} |
d = {1: 'a', 2: 'b', 3: 'c'} print(d.pop(1, 'xyz')) print(d) | a {2: 'b', 3: 'c'} |
d = {1: 'a', 2: 'b', 3: 'c'} print(d.pop(4)) print(d) | Line 2: KeyError: 4 |
d = {1: 'a', 2: 'b', 3: 'c'} print(d.pop(4, 'xyz')) print(d) | xyz {1: 'a', 2: 'b', 3: 'c'} |
If key
is a key in the dictionary, this removes it from the dictionary and returns its value. The value default
is ignored in this case.
If key
is not a key in the dictionary, this returns the value default
. If no default is provided, a KeyError
is raised.
a_dict.items()
Code | Output |
---|---|
print({1: 'a', 2: 'b', 3: 'c'}.items()) | [(1, 'a'), (2, 'b'), (3, 'c')] |
sample_dict = {1: 'a', 2: 'b', 3: 'c'} for key, value in sample_dict.items(): print(key, 'maps to', value) | 1 maps to a 2 maps to b 3 maps to c |
Returns an iterable of (key, value)
pairs, for all the keys in dictionary a_dict
.
A common usage is to loop over all key/value pairs in a dictionary, as in the last example above.
a_dict.keys()
Code | Output |
---|---|
print({1: 'a', 2: 'b', 3: 'c'}.keys()) | [1, 2, 3] |
Returns an iterable consisting of the keys in dictionary a_dict
.
While you can test if something is a dictionary key explicitly, like key in a_dict.keys()
, the simpler expression key in a_dict
is equivalent. The same applies to for
-loops.
a_dict.values()
Code | Output |
---|---|
print({1: 'a', 2: 'b', 3: 'c'}.values()) | ['a', 'b', 'c'] |
sample_dict = {1: 'a', 2: 'b', 3: 'c'} for value in sample_dict.values(): print(value, 'is a value in the dictionary') | a is a value in the dictionary b is a value in the dictionary c is a value in the dictionary |
Returns an iterable consisting of the values in dictionary a_dict
.
A common usage is to loop over all values in a dictionary, as in the last example above.
a_dict.clear()
Code | Output |
---|---|
d = {1: 'a', 2: 'b', 3: 'c'} d.clear() print(d) | {} |
Mutates a dictionary to be empty. Returns None
.
a_dict.update(another_dict)
Code | Output |
---|---|
d = {1: 'a', 2: 'b', 3: 'c'} d.update({3: 'd', 4: 'e'}) print(d) | {1: 'a', 2: 'b', 3: 'd', 4: 'e'} |
Mutates a_dict
to have the key/value pairs in another_dict
. Returns None
.
{key_expr: val_expr for var1 in for_expr1 …}
{key_expr: val_expr for var1 in for_expr1 … if if_expr}
Code | Output |
---|---|
print({x: x*x for x in range(4)}) | {0: 0, 1: 1, 2: 4, 3: 9} |
print({(x,y): x+y for x in [1,2,5] for y in [6,2,1] if y!=x}) | {(1, 6): 7, (1, 2): 3, (2, 6): 8, (2, 1): 3, (5, 6): 11, (5, 2): 7, (5, 1): 6} |
[expr for … if …]
— List comprehension{expr for … if …}
— Set comprehension(expr for … if …)
— Generator expressionSuch a dictionary comprehension iterates over each of for_expr1
, …. For each combination of loop variables var1
, …, that passes any condition if_expr
, the key/value pair key_expr:val_expr
is put in the resulting dictionary.
dict()
with keyword argumentsa_dict.copy()
a_dict.popitem()
{expr for var1 in for_expr1 …}
{expr for var1 in for_expr1 … if if_expr}
Code | Output |
---|---|
print({x*x for x in range(4)}) | set([0, 1, 4, 9]) |
print({x+y for x in [1,2,5] for y in [6,2,1] if y!=x]) | set([3, 6, 7, 8, 11]) |
[expr for … if …]
— List comprehension{key_expr: val_expr for … if …}
— Dictionary comprehension(expr for … if …)
— Generator expression{value0, value1, …}
Code | Output |
---|---|
print({1, 2, 3, 4, 5, 3, 5}) | set([1, 2, 3, 4, 5]) |
print({'abc', 'def'}) | set(['abc', 'def']) |
Returns a new set with the listed values.
set()
set(an_iter)
Code | Output |
---|---|
print(set()) | set([]) |
print(set('abc')) | set(['a' ,'b', 'c']) |
print(set([1, 2, 3, 4, 5, 3, 5])) | set([1, 2, 3, 4, 5]) |
print(set((1, 2, 3, 4, 5))) | set([1, 2, 3, 4, 5]) |
print(set(set([1, 2, 3, 4]))) | set([1, 2, 3, 4]) |
print(set({1: 2, 3: 4})) | set([1, 3]) |
print(set(enumerate(['a', 'b', 'c', 'd']))) | set([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]) |
Returns a new set with the values from iterable or iterator an_iter
. If the argument is already a set, it returns a copy, i.e., a new set with the same elements.
a_set.union(an_iter)
Code | Output |
---|---|
print(set([1, 2, 3, 4, 5]).union(set([5, 6, 7]))) | set([1, 2, 3, 4, 5, 6, 7]) |
Returns the union of set a_set
and the set of elements in iterable an_iter
.
a_set.intersection(an_iter)
Code | Output |
---|---|
print(set([1, 2, 3, 4, 5]).intersection(set([5, 6, 7]))) | set([5]) |
Returns the intersection of set a_set
and the set of elements in iterable an_iter
.
a_set.difference(an_iter)
Code | Output |
---|---|
print(set([1, 2, 3, 4, 5]).difference(set([5, 6, 7]))) | set([1, 2, 3, 4]) |
Returns a set with all elements from set a_set
that are not in iterable an_iter
.
a_set.symmetric_difference(anInter)
Code | Output |
---|---|
print(set([1, 2, 3, 4, 5]).symmetric_difference(set([5, 6, 7]))) | set([1, 2, 3, 4, 6, 7]) |
Returns a set with all elements that are in exactly one of set a_set
and iterable an_iter
.
a_set.update(an_iter)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.update(set([5, 6, 7])) print(s) | set([1, 2, 3, 4, 5, 6, 7]) |
Mutates a_set
to be the union of set a_set
and the set of elements in iterable an_iter
. Returns None
.
a_set.intersection_update(an_iter)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.intersection_update(set([5, 6, 7])) print(s) | set([5]) |
Mutates a_set
to be the intersection of set a_set
and the set of elements in iterable an_iter
. Returns None
.
a_set.difference_update(an_iter)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.difference_update(set([5, 6, 7])) print(s) | set([1, 2, 3, 4]) |
Mutates a_set
to be the set difference of set a_set
and the set of elements in iterable an_iter
. Returns None
.
a_set.symmetric_difference_update(an_iter)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.symmetric_difference_update(set([5, 6, 7])) print(s) | set([1, 2, 3, 4, 6, 7]) |
Mutates a_set
to be a set with all elements that are in exactly one of set a_set
and iterable an_iter
. Returns None
.
a_set.add(x)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.add(5) print(s) s.add(6) print(s) | set([1, 2, 3, 4, 5]) set([1, 2, 3, 4, 5, 6]) |
Adds element x
to the set a_set
. Returns None
.
a_set.remove(x)
a_set.discard(x)
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) s.remove(5) print(s) s.discard(7) print(s) s.discard(3) print(s) | set([1, 2, 3, 4]) set([1, 2, 3, 4]) set([1, 2, 4]) |
Removes element x
from set a_set
. If element x
is not in a_set
, a_set.remove
raises an error, while a_set.discard
does not. Returns None
.
a_set.pop()
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) print(s.pop()) print(s) | 1 set([2, 3, 4, 5]) |
Removes and returns an arbitrary element from set a_set
. Raises an error if there are no elements to remove.
a_set.issubset(an_iter)
Code | Output |
---|---|
s = set([2, 9, 7, 1] print(s.issubset(s)) | True |
print(set([2, 9, 7, 1]).issubset(set([1, 7]))) | False |
print(set([2, 9, 7, 1]).issubset(set([1, 2, 3, 4]))) | False |
print(set([2, 9, 7, 1]).issubset(set([1, 2, 3, 4, 5, 6, 7, 8, 9]))) | True |
print(set([2, 9, 7, 1]).issubset([1, 2, 7, 9]) | True |
Returns whether the set a_set
is a subset of the set of elements in iterable an_iter
.
a_set.issuperset(an_iter)
Code | Output |
---|---|
s = set([2, 9, 7, 1] print(s.issuperset(s)) | True |
print(set([2, 9, 7, 1]).issuperset(set([1, 7]))) | True |
print(set([2, 9, 7, 1]).issuperset(set([1, 2, 3, 4]))) | False |
print(set([2, 9, 7, 1]).issuperset(set([1, 2, 3, 4, 5, 6, 7, 8, 9]))) | False |
print(set([2, 9, 7, 1]).issuperset([1, 2, 7, 9]) | True |
Returns whether the set a_set
is a superset of the set of elements in iterable an_iter
.
a_set.copy()
Code | Output |
---|---|
s = set([1, 2, 3, 4, 5]) t = s.copy() print(s == t) print(s is t) | True False |
Makes a new set with the same elements as a_set
.
|
&
-
^
|=
&=
-=
^=
s.clear()
A function is a parameterized section of code. A method is simply a function which is an attribute of an object, i.e., defined as part of a class. Functions and methods are values themselves. (However, CodeSkulptor does not yet consider built-in functions to be values.)
def a_func(var0, var1, …): …
Code | Output |
---|---|
def is_even(n): '''Returns a Boolean indicating whether n is even.''' return n % 2 == 0 print(is_even) print(is_even(2)) | <function is_even> True |
def median_3(a, b, c): '''Returns the median (middle) of the three arguments.''' if a <= b: if b <= c: return b elif a <= c: return c else: return a else: if a < c: return a elif b < c: return c else: return b print(median_3(5, 9, 2)) | 5 |
def swap_list_elts(l, index1, index2): '''Swaps l[index1] and l[index2]''' l[index1], l[index2] = l[index2], l[index1] l = ['a', 'b', 'c', 'd'] print(swap_list_elts(l, 1, 3)) print(l) | None ['a', 'd', 'c', 'b'] |
def add2(n): '''Returns the given value plus 2.''' return n + 2 print(map(add2, [1, 3, 5])) | [3, 5, 7] |
Creates a function named by a_func
. When applied to arguments, the code in the function body is run until a return
statement is reached or the end of the code is reached. In the former case, the function returns the value specified in the return
, while in the latter case, the function returns None
.
To be distinct from a generator function the body must not contain yield
statements.
For good style, each named function should also have a documentation string (docstring) immediately after its header, as illustrated in the examples.
lambda var1, var2, …: expr
Code | Output |
---|---|
is_even = lambda n : n % 2 == 0 print(is_even) print(is_even(2)) | <function <lambda>> True |
print(map(lambda n: n + 2, [1, 3, 5])) | [3, 5, 7] |
Anonymous functions are simplified forms of function definitions. First, they do not have a name. Second, the parameter list is not in parentheses. And third, the function body is just a single expression, which is implicitly returned. This simplicity is convenient especially when the function is simply passed as an argument, as in the last example above.
classmethod()
staticmethod()
a_func.func_doc
a_func.__doc__
a_func.func_name
a_func.__name__
a_func.__module__
a_func.func_defaults
a_func.func_code
a_func.func_globals
a_func.func_dict
a_func.func_closure
Generators are a kind of iterator that can be defined like functions. A generator function looks just like a regular function, except that it uses yield
instead of return
.
(expr for var1 in for_expr1 …)
(expr for var1 in for_expr1 … if if_expr)
Code | Output |
---|---|
print((x*x for x in range(4))) | <generator object <genexpr>> |
print((x*x for x in range(4)).next()) | 0 |
print(list(x*x for x in range(4))) | [0, 1, 4, 9] |
print(list(x+y for x in [1,2,5] for y in [6,2,1] if y!=x)) | [7, 3, 8, 3, 11, 7, 6] |
[expr for … if …]
— List comprehension{key_expr: val_expr for … if …}
— Dictionary comprehension{expr for … if …}
— Set comprehensionSuch a generator expression iterates over each of for_expr1
, …. For each combination of loop variables var1
, …, that passes any condition if_expr
, the value expr
is put in the resulting list.
def a_genfunc(var0, var1, …): … yield … …
Code | Output |
---|---|
def squares(n): '''Yields the squares from 0 to n-1 squared.''' for i in range(n): yield i * i g = squares(4) print(g.__next__()) print(g.__next__()) print(g.__next__()) print(g.__next__()) | 0 1 4 9 |
Creates a generator function named by an_iter
. When applied to arguments, the code in the function body is encapsulated and returned as a generator, a type of iterator. Each time the __next__()
, method is applied to the resulting generator, the code is run until the next yield
expression, and the yield
expression's value is returned from that method call. Thus, the creation of the generator does not wait for all of its elements to be generator, and the generator could even represent an infinite number of elements.
To be distinct from a function definition, the body must contain yield
statements, not return
statements.
a_gen.send(val)
Code | Output |
---|---|
def foo(): x = yield 1 print('Yielded:', x) yield 2 bar = foo() print(bar.__next__()) print(bar.send('Hi!')) | 1 Yielded: Hi! 2 |
def add1genf(n): while n != None: print('Before:', n) n = yield n + 1 print('After:', n) add1gen = add1genf(10) print('---') print(add1gen.send('This first value is ignored.')) print('---') print(add1gen.send(3)) print('---') print(add1gen.send(17)) | --- Before: 10 11 --- After: 3 Before: 3 4 --- After: 17 Before: 17 18 |
Like the __next__()
method, it runs the generator code from where it started (on the first call) or last yielded, stopping at the next yield
expression. It returns the value of the yield
expression. It also sends the value val
back to the generator's yield
expression.
a_gen.throw()
a_gen.close()
codeskulptor.file2url
— Abbreviating standard URLsThis module contains functions for obtaining input data from the web. Currently, CodeSkulptor's implementation of this module supports input only, not output, and only from a a CodeSkulptor-affiliated data storage site. To use these operations, first import the module with import urllib.request
.
File objects represent open files. A file object keeps track of the current position in the file. Each read operation gets data starting at this position and advances the position to the end of the returned data. CodeSkulptor only supports obtaining an open file via urllib.request.urlopen()
.
a_file.read()
a_file.read(size)
Code | Output |
---|---|
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.read()) | b'This is line one.\nThis is line two.\nThis is line three.\n' |
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.read(7)) | b'This is' |
a_file.readline()
— Reads one linea_file.readlines()
— Reads multiple linesWith no argument or a negative size
argument, this returns a bytes object containing the rest of the file.
With a non-negative size
argument, this returns a bytes object containing the next at-most size
bytes (characters) of the file. It returns fewer bytes than requested only when there are fewer bytes remaining in the file.
a_file.readline()
a_file.readline(size)
Code | Output |
---|---|
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.readline()) | b'This is line one.\n' |
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.read(7)) print(a_file.readline()) | b'This is' b' line one.\n' |
a_file.read()
— Readsa_file.readlines()
— Reads multiple linesWith no argument or a negative size
argument, this returns a bytes object containing the rest of the current line in the file. I.e., it returns all the characters up to and including the next newline character ' '
or end of file.
With a non-negative size
argument, this returns a bytes object containing the next at-most size
bytes (characters) of the file. It returns fewer bytes than requested only when there are fewer bytes remaining in the file.
a_file.readlines()
a_file.readlines(sizehint)
Code | Output |
---|---|
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.readlines()) | [b'This is line one.\n', b'This is line two.\n', b'This is line three.\n'] |
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.readline()) print(a_file.readlines()) | b'This is line one.\n' [b'This is line two.\n', b'This is line three.\n'] |
a_file.read()
— Readsa_file.readline()
— Reads one lineReads the rest of the file, separating its content into a sequence of lines ending in the newline character '\n'
. This sequence is returned as a list of bytes objects.
The number sizehint
is an estimate of how many bytes remain in the file. Its value does not affect the result.
list()
on file objectsa_file.close()
a_file.fileno()
a_file.flush()
a_file.isatty()
a_file.seek()
a_file.tell()
a_file.truncate()
a_file.write()
a_file.writelines()
a_file.xreadlines()
a_file.closed
a_file.encoding
a_file.errors
a_file.mode
a_file.name
a_file.newlines
a_file.softspace
enumerate(an_iter)
enumerate(an_iter, start)
Code | Output |
---|---|
print(enumerate(['a', 'b', 'c', 'd'])) | <enumerate object> |
print(list(enumerate(['a', 'b', 'c', 'd']))) | [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] |
print(list(enumerate(['a', 'b', 'c', 'd'], 5))) | [(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')] |
Returns an enumeration object, a type of iterator. Each element of the iterator is a pair of a number and an element from the given iterable or iterator an_iter
. The first number is start
(or the default zero), and successive numbers are each one greater than the previous.
Iterators are a kind of iterable, and thus support iteration or looping — e.g., for x in an_iter
. Such a loop implicitly calls an_iter.__next__()
repeatedly to get each element from the iterator, thus exhausting the elements in the iterator. Similarly, calling functions such as list()
on an iterator will implicitly loop through and exhaust the iterator.
next(an_iter)
next(an_iter, value)
an_iter.__next__()
Code | Output |
---|---|
i = enumerate(['a', 'b', 'c']) print(next(i)) print(next(i)) print(next(i, 0)) print(next(i, 0)) | (0, 'a') (1, 'b') (2, 'c') 0 |
def foo(): x = yield 1 print('Yielded:', x) yield 2 bar = foo() print(bar.__next__()) print(bar.__next__()) | 1 Yielded: None 2 |
an_iter.__next__()
.Returns the next element of the iterator and removes it from the iterator.
If the iterator has no next element, then an error is raised, except when using next(an_iter, value)
, in which case the value
is returned.
For a generator defined by a generator function, these operations' behavior can be described in more detail. The generator's code runs from where it started (on the first call) or last yielded, stopping at the next yield
expression. The generator returns the value of the yield
expression. The operation also sends the value None
back to the generator's yield
expression.
an_iter.__next__()
incorrectly does not raise an error if the iterator is empty.an_iter.__iter__()
iter()
Sequences are ordered collections of data. Their elements can be indexed by integers indicating positions.
seq1 + seq2
Code | Output |
---|---|
print('hello' + ' ' + 'world!') | hello world! |
print([1, 2, 3] + [4, 5, 6]) | [1, 2, 3, 4, 5, 6] |
print(('a', 'b', 'c') + (1, 2) + ([2, 3, 4], [1])) | ('a', 'b', 'c', 1, 2, [2, 3, 4], [1]) |
Returns the concatenation of seq1
and seq2
. I.e., it returns a new sequence that contains the contents of the first sequence, then the contents of the second sequence. The two sequences must be of the same type, and the result is of the same type.
a_seq * n
n * a_seq
Code | Output |
---|---|
print('hello' * 2) | hellohello |
print(['a', 'b', 'c'] * 3) | ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] |
print((1, 2, 3, 4) * 4) | (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4) |
x = [[1, 2]] * 3 print(x) x[0][0] = 3 print(x) | [[1, 2], [1, 2], [1, 2]] [[3, 2], [3, 2], [3, 2]] |
Returns the concatenation of n
copies of a_seq
. The copies are “shallow” in that if the sequence contains compound objects, the contents of those objects are not copied. In the last example above, each of the sub-lists [1, 2]
is the same list; they are not just lists that look alike.
a_seq[i]
a_seq.__getitem__(i)
Code | Output |
---|---|
print('abcde'[2]) | c |
print((8, 2, 4, 0)[3]) | 0 |
print([8, 2, 4, 0][-3]) | 2 |
a_seq.__getitem__()
.Returns the item in sequence a_seq
at integer index i
. Given a non-negative index, it starts counting from index 0 on the left. Given a negative index, it starts counting from index -1 on the right.
a_seq[i:j]
a_seq[i:j:k]
Code | Output |
---|---|
print('abcde'[1:3]) | bc |
print((8, 2, 4, 0)[1:-1]) | (2, 4) |
print([8, 2, 4, 0][1:]) | [2, 4, 0] |
print('abcde'[1:4:2]) | bd |
print((8, 2, 4, 0)[1::1]) | (2, 4, 0) |
print([8, 2, 4, 0][::-1]) | [0, 4, 2, 8] |
Returns a new sequence (a “slice”) of the items in the sequence a_seq
starting from integer index i
up to integer index j-1
, incrementing indices by integer k
.
Omitting index i
starts the sequence at the leftmost position. Omitting index j
ends the sequence at the rightmost position. The step k
defaults to 1, i.e., including each element in the indexed range from left to right.
The new sequence is of the same type as a_seq
.
a_seq.index(val)
a_seq.index(val, start)
a_seq.index(val, start, end)
Code | Output |
---|---|
print(['a', 'b', 'c', 'b', 'a', 'c'].index('c')) | 2 |
print(('a', 'b', 'c', 'b', 'a', 'c').index('c')) | 2 |
print('abcbac'.index('c')) | 2 |
print('abcbac'.index('ba')) | 3 |
print(['a', 'b', 'c', 'b', 'a', 'c'].index('c', 3)) | 5 |
print(('a', 'b', 'c', 'b', 'a', 'c').index('c', 3)) | 5 |
print('abcbac'.index('c', 3)) | 5 |
a_str.find()
, etc. — Similar methodsReturns the index in the sequence a_seq[start:end]
of the first item whose value is val
. If a_seq
is a string, then val
can be a string of any length, not just a single character. By default, start
is 0, and end
is the length of the string. It is an error if there is no such item.
A common mistake is to use it to find the next item:
for item in my_list: next_item = my_list[my_list.index(item) + 1] print(item, next_item)This doesn't accomplish the intended goal when the list contains duplicates, since
my_list.index(item)
finds the first instance of item
.a_seq.count(val)
a_str.count(val, start)
a_str.count(val, start, end)
Code | Output |
---|---|
print(['a', 'b', 'c', 'b', 'a', 'c'].count('b')) | 2 |
print(('a', 'b', 'c', 'b', 'a', 'c').count('b')) | 2 |
print('abcbac'.count('c')) | 2 |
print('abcbac'.count('cb')) | 1 |
print('abcbac'.count('b', 3)) | 1 |
print('abcbac'.count('b', 2, 3)) | 0 |
Returns the number of times the value val
appears in the sequence a_seq
.
For strings only, there are two differences in the method. Additional arguments limit the part of the string to search. Also, val
can be a string of any length, not just a single character. Thus, it returns the number of times val
is a substring in a_str[start:end]
. By default, start
is 0, and end
is the length of the string.
Iterables are collections of data that allow iteration or looping — e.g., for x in an_iter
.
val in an_iter
Code | Output |
---|---|
print(8 in [1, 2, 3, 4, 5, 6, 7]) | False |
print('c' in 'abcde') | True |
print((1,3) in ('a', 3, 4, (1,2), 'hello')) | False |
print(3 in {1: 'a', 2: 'b', 3: 'c'}) | True |
print(3 in {'a': 1, 'b': 2, 'c: 3}) | False |
print(8 in set([1, 2, 3, 4, 5, 6, 7])) | False |
not in
— ComplementReturns True
if value val
is in the iterable, otherwise returns False
.
val not in an_iter
Code | Output |
---|---|
print(8 not in [1, 2, 3, 4, 5, 6, 7]) | True |
print('c' not in 'abcde') | False |
print((1,3) not in ('a', 3, 4, (1, 2), 'hello')) | True |
print(3 not in {1: 'a', 2: 'b', 3: 'c'}) | False |
print(3 not in {'a': 1, 'b': 2, 'c': 3}) | True |
print(8 not in set([1, 2, 3, 4, 5, 6, 7])) | True |
in
— ComplementReturns True
if value val
is not in the iterable, otherwise returns False
.
len(an_iter)
Code | Output |
---|---|
print(len('')) | 0 |
print(len([2, 35, -2, 12])) | 4 |
print(len((2, 35, -2, 12))) | 4 |
print(len({1: 2, 3: 4})) | 2 |
print(len(set([2, 35, -2, 12]))) | 4 |
Returns the number of items in the iterable.
sum(an_iter)
sum(an_iter, start)
Code | Output |
---|---|
print(sum([10, 20, 30])) | 60 |
print(sum((10, 20, 30))) | 60 |
print(sum({1: 10, 2: 20})) | 3 |
print(sum(set([10, 20, 30)]))) | 60 |
print(sum([10, 20, 30], 2)) | 62 |
Returns the sum of start
, which defaults to 0, and the numbers in the iterable.
max(val<sub>1</sub>, val<sub>2</sub>, …)
max(an_iter)
Code | Output |
---|---|
print(max(2, 35, -2, 12)) | 35 |
print(max('c', 'x', 'cat', 'father')) | x |
print(max([2, 35, -2, 12])) | 35 |
print(max(['c', 'x', 'cat', 'father'])) | x |
print(max((2, 35, -2, 12))) | 35 |
print(max({1: 2, 3: 4})) | 3 |
print(max(set([2, 35, -2, 12]))) | 35 |
Given multiple arguments, it returns the argument with the maximum value. Given a single iterable argument (other than a string), it returns the item in the iterable with maximum value.
min(val<sub>1</sub>, val<sub>2</sub>, …)
min(an_iter)
Code | Output |
---|---|
print(min(2, 35, -2, 12)) | -2 |
print(min('c', 'x', 'cat', 'father')) | c |
print(min([2, 35, -2, 12])) | -2 |
print(min(['c', 'x', 'cat', 'father'])) | c |
print(min((2, 35, -2, 12))) | -2 |
print(min({1: 2, 3: 4})) | 1 |
print(min(set([2, 35, -2, 12]))) | -2 |
Given multiple arguments, it returns the argument with the minimum value. Given a single iterable argument (other than a string), it returns the item in the iterable with minimum value.
zip(iter1, iter2, …)
Code | Output |
---|---|
print(zip('abcd', '1234', (5, 6, 7, 8))) | [('a', '1', 5), ('b', '2', 6), ('c', '3', 7), ('d', '4', 8)] |
print(zip([1, 2, 3, 4], ['a', 'b', 'c'])) | [(1, 'a'), (2, 'b'), (3, 'c')] |
print(zip({1: 2, 3: 4}, set([5, 6]))) | [(1, 5), (3, 6)] |
print(zip([1, 2, 3])) | [(1,), (2,), (3,)] |
print(zip()) | [] |
list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['z', 'y', 'x', 'w', 'v'] for letter1, letter2 in zip(list1, list2): print(letter1 + letter2) | az by cx dw ev |
zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')] first_elts, second_elts = zip(*zipped_list) print(first_elts) print(second_elts) | [1, 2, 3] ['a', 'b', 'c'] |
Returns a list of tuples, where the ith tuple contains the ith element of each iterable. For intuition, picture the action of matching up the two sides of a standard zipper. The result's length is that of the shortest argument. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
A common usage of zip()
is to iterate over two same-length lists (or other iterables) in lock-step, as shown in the next-to-last example above.
Unzipping: There is no built-in function to do the opposite of zip()
. However, one approach is to use function argument unpacking along with zip()
to group the desired elements, as shown in the last example above.
sorted(an_iter)
sorted(an_iter, reverse=rev_bool, key=key_fn)
Code | Output |
---|---|
print(sorted('blue')) | ['b', 'e', 'l', 'u'] |
print(sorted([2, 1, 3, 2])) | [1, 2, 2, 3] |
print(sorted([2, 1, 3, 2], reverse=True)) | [3, 2, 2, 1] |
print(sorted('This is a test string from Andrew'.split(), key=str.lower)) | ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] |
a_list.sort()
— Sort a list in-placeReturns a list of the elements of the iterable in sorted order.
By default or when rev_bool
is False
, the elements are in ascending order. When rev_bool
is True
, the elements are in descending order. If the elements are of different types, then the ascending or descending ordering is based upon their hash values.
The key
argument to sorted is a function that is called on each element before sorting. The result of the key function is used in the sort, but the original values in the list are put into the output.
The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.
map(function, an_iter)
Code | Output |
---|---|
def square(n): return n * n print(map(square, [3, 7, 1])) | [9, 49, 1] |
Applies the user-defined function to the elements of the iterable an_iter
, and returns a list of the results. The ith element of the returned list is function(an_iteriter1[<var>i</var>], &hellip)
.
filter(function, an_iter)
Code | Output |
---|---|
def is_positive(n): return n > 0 print(filter(is_positive, [3, -7, 1])) | [3, 1] |
def is_positive(n): return n > 0 print(filter(is_positive, (3, -7, 1))) | (3, 1) |
def is_aorb(x): return x == 'a' or x == 'b' print(filter(is_aorb, 'acdba')) | 'aba' |
def is_positive(n): return n > 0 print(filter(is_positive, set([3, -7, 1]))) | [1, 3] |
print(filter(None, [set(), 3, {}, 0, False, '', -1, []])) | [3, -1] |
Applies the user-defined function to the elements of the iterable an_iter
, and returns a sequence of those elements for which the function returns a true-like value. If the function is None
, then the function is taken to be the identity function — i.e., it returns a sequence of those elements which are true-like values.
If the iterable an_iter
is a sequence, then the returned value is of that same type, otherwise the returned value is a list.
reduce(function, an_iter)
reduce(function, an_iter, initializer)
Code | Output |
---|---|
def add(x, y): return x + y print(reduce(add, [3, -7, 1])) | -3 |
def add(x, y): return x + y print(reduce(add, (3, -7, 1), 12)) | 9 |
def maximum(x, y): if x >= y: return x else: return y print(reduce(maximum, 'acdba', 'a')) | 'd' |
def maximum(x, y): if x >= y: return x else: return y print(reduce(maximum, 'acdba', 'z')) | 'z' |
def second(x, y): return y print(reduce(second, [1, 2, 3, 4, 5])) | 5 |
Combines the elements of the iterable an_iter
by repeatedly applying the two-argument function to an accumulator and each respective element in turn. Without an initializer, if the iterable has no elements, then an error is raise, and if the iterable has one element, that element is returned. With an initializer, if the iterable has no elements, the initializer is returned.
Without an initializer, this is equivalent to
def reduce(function, an_iter): started = False result = False if not an_iter: raise TypeError('reduce() of empty sequence with no initial value') for element in an_iter: if not started: result = element started = True else: result = function(result, element)
With an initializer, this is equivalent to
def reduce(function, an_iter, initializer): result = initializer for element in an_iter: result = function(result, element)
max()
and min()
with key
argument.map()
, filter()
, and reduce()
on built-in functions.__iter__()
iter()
x < y
x <= y
x > y
x >= y
x == y
x != y
x is y
x is not y
Code | Output |
---|---|
print(2 < 3) | True |
print(False < True) | True |
print(2 < 2) | False |
print('abc' <= 'ad') | True |
print(2 <= 2) | True |
print([1, 3] > [1, 2, 3]) | True |
print(3 > 2) | True |
print(set([1, 3, 4]) > set([3, 4])) | True |
print('xyz' >= 'abc') | True |
print(2 == 2) | True |
print(set([1, 5, 10]) == set([10, 1, 5])) | True |
print(2 != 3) | True |
s = set([1, 5, 10]) print(s is s) | True |
print(set([1, 5, 10]) is not set([10, 1, 5])) | True |
is
/is not
when ==
/!=
are appropriate.x < y
: Is x
less than y
?x <= y
: Is x
less than or equal to y
?x > y
: Is x
greater than y
?x >= y
: Is x
greater than or equal to y
?x == y
: Is x
equal to y
?x != y
: Is x
not equal to y
? (The !=
operator is meant to evoke the traditional ≠ symbol.)x is y
: Is x
the same object as y
?x is not y
: Is x
not the same object as y
?The interpretation of the ordering operators, i.e., <
, <=
, >
, >=
, depends upon the type of the arguments. In general, you should only compare values of the same type. Comparing values of different type results in a consistent ordering, but not necessarily the same ordering as in another implementation.
Numbers (both integers and floating-point) use their standard order. Booleans use the order than False
is less than True
. Strings can be thought of as using alphabetic order, although that doesn't capture the whole truth. More accurately, strings use lexicographic order with the ASCII character values. Lists use lexicographic order. Sets use subset. Dictionaries cannot be compared by these operators.
The operator is
tests whether the two operands are the same object, whereas ==
tests whether they have the same value. For mutable types, if x is y
, then mutating x
also mutates y
.
type(x)
Code | Output |
---|---|
print(type(3)) | <type 'int'> |
print(type(3.2)) | <type 'float'> |
print(type('Hello')) | <type 'str'> |
print(type(True)) | <type 'Bool'> |
print(type(None)) | <type 'NoneType'> |
print(type([1, 2, 3])) | <type 'list'> |
print(type({1: 2})) | <type 'dict'> |
print(type(set([1, 2, 3]))) | <type 'set'> |
def f(): return 3 print(type(f)) | <type 'function'> |
print(type(int)) | <type 'type'> |
All values have a type, and this returns the type of the given value. The type is itself a value.
isinstance(x, y)
Code | Output |
---|---|
print(isinstance(3, type(3))) | True |
print(isinstance(3.1, type(3.1))) | True |
print(isinstance('foo', type('foo'))) | True |
print(isinstance([], type([1, 2, 3]))) | True |
print(isinstance({1: 2}, type({3: 4}))) | True |
print(isinstance(set([1, 4]), type(set[]))) | True |
print(isinstance(3, int)) | True |
print(isinstance(3.1, float)) | True |
print(isinstance('foo', str)) | True |
print(isinstance([], list)) | True |
print(isinstance({1: 2}, dict)) | True |
print(isinstance(set([1, 4]), set)) | True |
def f(): return 3 def g(x): return x print(isinstance(f, type(g))) | True |
If the second argument is a type, for example, as returned by type()
, it returns whether the first argument is of that type. If the second argument is a type constructor, it returns whether the first argument is of the type that results from that type constructor.
dir(x)
Code | Output |
---|---|
print(dir({})) | ['get', 'items', 'keys', 'values'] |
Returns a list of strings naming the attributes defined on the object x
.
hasattr(an_obj, attr_name)
Code | Output |
---|---|
print(hasattr([], 'count')) | True |
print(hasattr({1: 2}, 'silly')) | False |
Returns whether the given object an_obj
has an attribute named by the string attr_name
.
callable(an_obj)
Code | Output |
---|---|
print(callable([1, 2, 3])) | False |
print(callable(list)) | True |
Returns whether the given object an_obj
is callable, i.e., a built-in function, named function, anonymous function, generator function, or class (which is equivalent to its class constructor).
dir
with no argumentgetattr()
setattr()
object()
hash()
id()
classmethod()
staticmethod()
issubclass()
super()
property()
memoryview()
unicode()
Also, built-in functions and methods aren't considered values and thus don't have a type — thus, type()
and isinstance()
aren't supported on these.
CodeSkulptor3 implements the following subset of the Python standard library. To use these operations, first import the relevant module with an import
statement, such as import math
.
This module contains additional mathematical operations. To use these operations, first import the module with import math
.
math.isinf(x)
Code | Output |
---|---|
import math print(math.isinf(8)) | False |
import math print(math.isinf(float('+inf'))) | True |
import math print(math.isinf(float('-inf'))) | True |
Returns whether x
is infinite.
math.isnan(x)
Code | Output |
---|---|
import math print(math.isnan(8)) | False |
import math print(math.isnan(float('NaN'))) | True |
Returns whether x
is the special floating point Not-a-Number (NaN).
math.ceil(x)
Code | Output |
---|---|
import math print(math.ceil(8)) | 8 |
import math print(math.ceil(8.1)) | 9 |
import math print(math.ceil(-8.1)) | -8 |
int()
— Round to zeroround()
— Rounds to nearest integermath.trunc()
— Rounds to zeromath.floor()
— Rounds downReturns the “ceiling” of x
, i.e., the smallest integral value greater than or equal to x
. Returns it as an integer.
math.floor(x)
Code | Output |
---|---|
import math print(math.floor(8)) | 8 |
import math print(math.floor(8.9)) | 8 |
import math print(math.floor(-8.9)) | -9 |
int()
— Round to zeroround()
— Rounds to nearest integermath.trunc()
— Rounds to zeromath.ceil()
— Rounds upReturns the “floor” of x
, i.e., the largest integral value less than or equal to x
. Returns it as an integer.
math.trunc(x)
Code | Output |
---|---|
import math print(math.trunc(8)) | 8 |
import math print(math.trunc(8.9)) | 8 |
import math print(math.trunc(-8.9)) | -8 |
int()
— Also round to zeroround()
— Rounds to nearest integermath.ceil()
— Rounds upmath.floor()
— Rounds downReturns the “truncation” of x
, i.e., the integer part of x
, ignoring any fractional part. Stated another way, it rounds the number towards zero. On numbers, this is the same behavior as int()
.
math.fabs(x)
Code | Output |
---|---|
import math print(math.fabs(3.1)) | 3.1 |
import math print(math.fabs(-3)) | 3.0 |
abs()
— Returns an integer when given an integerReturns the absolute value of the number x
as a floating-point value.
math.log(x)
math.log(x, base)
math.log10(x)
Code | Output |
---|---|
import math print(math.log(math.e ** 3)) | 3.0 |
import math print(math.log(10000, 10)) | 4.0 |
import math print(math.log10(10000)) | 4.0 |
math.log()
returns the logarithm of x
in base base
. If the base is omitted, it returns the natural logarithm, i.e., base
defaults to math.e
.
math.log10()
returns the logarithm of x
in base 10.
The result is a floating-point.
math.pow(x,y)
math.exp(y)
Code | Output |
---|---|
import math print(math.pow(2, 3)) | 8.0 |
import math print(math.exp(3)) | 20.085536923187668 |
**
— Built-in exponentiation operatorpow()
— Built-in exponentiation functionmath.pow(x,y)
returns x
raised to the power y
, xy. math.exp(y)
returns math.e
raised to the power y
, ey. The result is a floating-point.
math.factorial(x)
Code | Output |
---|---|
import math print(math.factorial(0)) | 1 |
import math print(math.factorial(4)) | 24 |
Returns the factorial of the non-negative integer x
, i.e., 1 * 2 * … * (x - 1) * x
. It raises an error on negative and non-integral values.
math.sqrt(x)
Code | Output |
---|---|
import math print(math.sqrt(16)) | 4.0 |
import math print(math.sqrt(-1)) | NaN |
Returns the square root of x
. The result is a floating-point.
math.e
Code | Output |
---|---|
import math print(math.e) | 2.718281828459045 |
The mathematical constant known as e, the base of the natural logarithm.
math.pi
Code | Output |
---|---|
import math print(math.pi) | 3.141592653589793 |
The mathematical constant known as π, the ratio between the circumference of a circle and its diameter.
math.degrees(x)
Code | Output |
---|---|
import math print(math.degrees(math.pi)) | 180.0 |
Returns the radians angle measure x
in degrees. The result is a floating-point.
math.radians(x)
Code | Output |
---|---|
import math print(math.radians(180)) | 3.141592653589793 |
Returns the degrees angle measure x
in radians. The result is a floating-point.
math.hypot(x, y)
Code | Output |
---|---|
import math print(math.hypot(3, 4)) | 5.0 |
Returns math.sqrt(x * x + y * y)
, known as the Euclidean norm. This represents each of the following:
x
, y
),x
, y
),x
and y
.The result is a floating-point.
math.sin(x)
math.cos(x)
math.tan(x)
Code | Output |
---|---|
import math print(math.sin(math.pi)) | 1.22464679915e-16 |
import math print(math.cos(math.pi)) | -1.0 |
import math print(math.tan(math.pi)) | -1.22464679915e-16 |
math.asin()
, math.acos()
, math.atan()
, math.atan2()
— Inversesmath.sinh()
, math.cosh()
, math.tanh()
— Hyperbolic versionsReturn the sine, cosine, or tangent, respectively, of x
radians. The result is a floating-point.
math.asin(x)
math.acos(x)
math.atan(x)
math.atan2(y, x)
Code | Output |
---|---|
import math print(math.asin(-1)) | -1.57079632679 |
import math print(math.acos(-1)) | 3.14159265359 |
import math print(math.atan(-1)) | -0.785398163397 |
import math print(math.atan2(1, 1)) | 0.785398163397 |
import math print(math.atan2(-1, -1)) | -2.35619449019 |
math.sin()
, math.cos()
, math.tan()
— Inversesmath.asinh()
, math.acosh()
, math.atanh()
— Hyperbolic versionsReturn the arcsine (asin
), arccosine (acos
), or arctangent (atan
), of x
. The resulting angle measurement is in radians.
atan2
returns the arctangent of y / x
in radians. The point of atan2
is that the signs of the inputs are known, so it can compute the correct quadrant for the angle, as illustrated in the above examples.
Each result is a floating-point.
math.sinh(x)
math.cosh(x)
math.tanh(x)
Code | Output |
---|---|
import math print(math.sinh(1)) | 1.17520119364 |
import math print(math.cosh(1)) | 1.54308063482 |
import math print(math.tanh(1)) | 0.761594155956 |
math.asinh()
, math.acosh()
, math.atanh()
— Inversesmath.sin()
, math.cos()
, math.tan()
— Non-hyperbolic versionsReturn the hyperbolic sine, cosine, or tangent, respectively, of x
. The result is a floating-point.
math.asinh(x)
math.acosh(x)
math.atanh(x)
Code | Output |
---|---|
import math print(math.asinh(-1)) | -0.88137358702 |
import math print(math.acosh(1)) | 0.0 |
import math print(math.atanh(0)) | 0.0 |
math.asinh()
, math.acosh()
, math.atanh()
— Inversesmath.asin()
, math.acos()
, math.atan()
, math.atan2()
— Non-hyperbolic versionsReturn the hyperbolic arcsine (asin
), arccosine (acos
), or arctangent (atan
), of x
. The result is a floating-point.
math.copysign()
math.mod()
math.frexp()
math.fsum()
math.ldexp()
math.modf()
This module contains functions that involve randomness. To use these operations, first import the module with import random
.
random.choice(a_seq)
Code | Output |
---|---|
import random print(random.choice([1, 2, 3, 4, 5, 6])) | # Results in one of the sequence's elements |
Returns a random element from the non-empty sequence a_seq
. If a_seq
is empty, raises an IndexError
.
random.randint(start, stop)
random.randrange(stop)
random.randrange(start, stop)
random.randrange(start, stop, step)
Code | Output |
---|---|
import random print(random.randint(0, 10)) | # Possible results are 0, 1, 2, …, 10 |
import random print(random.randrange(0, 10)) | # Possible results are 0, 1, 2, …, 9 |
import random print(random.randrange(0, 10, 2)) | # Possible results are 0, 2, 4, 6, 8 |
random.choice()
— Related to random.randrange()
range()
— Related to random.randrange()
random.randint(start, stop)
returns a random integer n such that start <=
n <= stop
.
random.randrange(start, stop, step)
is equivalent to random.choice(range(start, stop, step))
. In particular, random.randrange(start, stop)
returns a random integer n such that start <=
n < stop
. Each possible n is of the form start
+ i×step
, for some integral i.
For each function, each possible number is equally likely, i.e., the possible numbers are distributed uniformly.
random.random()
random.uniform(x, y)
Code | Output |
---|---|
import random print(random.random()) | # Possible results are 0.0 to 1.0, not including 1.0 |
import random lower = 5 upper = 10 range_width = upper - lower print(random.random() * range_width + lower) | # Possible results are lower to upper, not including upper |
import random print(random.uniform(2, 4)) | # Possible results are 2.0 to 4.0 |
import random print(random.uniform(4, 2)) | # Possible results are 2.0 to 4.0 |
Returns a random floating-point number. With random.random()
the result is in 0 ≤ n < 1, while with random.uniform()
the result is in x ≤ n ≤ y (when x ≤ y) or y ≤ n ≤ x (when y ≤ x). Each number is equally likely, i.e., the possible numbers are distributed uniformly.
random.triangular()
random.triangular(low)
random.triangular(low, high)
random.triangular(low, high, mode)
Code | Output |
---|---|
import random print(random.triangular()) | # Possible results are 0.0 to 1.0, not including 1.0 |
Returns a random floating-point number. The result is in low
≤ n ≤ high
with a triangular distribution centered on mode
. The mode
defaults to the midpoint of low
and high
, which results in a symmetric triangular distribution. Furthermore, low
and high
default to 0 and 1, respectively.
random.shuffle(a_list)
Code | Output |
---|---|
import random numbers = range(5) random.shuffle(numbers) print(numbers) | [3, 1, 0, 2, 4] # One possible result |
import random numbers = range(5) random.shuffle(numbers) print(numbers) | [2, 4, 3, 1, 0] # One possible result |
Mutates the list a_list
to be a random permutation of its elements.
random.seed()
random.seed(x)
Code | Output |
---|---|
random.seed() | # no output |
Changes the random number generator's seed, which is used to generate future random values. The hashable object x
's integer value is used as the seed. If x
is omitted or None
, the current system time is used.
The current system time is used as the initial seed when the module is first imported.
random.shuffle(x, random)
random.getstate()
random.setstate()
random.jumpahead()
random.getrandbits()
random.sample()
random.betavariate()
random.expovariate()
random.gammavariate()
random.gauss()
random.lognormvariate()
random.normalvariate()
random.vonmisesvariate()
random.paretovariate()
random.weibullvariate()
A default dictionary supports all the standard dictionary operations. The only difference is that when looking up a value, a_defdict[key]
, if that key
has not been added to the dictionary, then some default value can be returned, instead of an raising a KeyError
. Providing a default value is particularly useful when the dictionary values will be accumulating information, as this simplifies the initialization for the accumulator.
To use default dictionaries, first import the module with import collections
.
collections.defaultdict()
collections.defaultdict(default_fun)
collections.defaultdict(default_fun, an_iter)
Code | Output |
---|---|
import collections d = collections.defaultdict() print(d[1]) | Line 4: KeyError: 1 |
import collections d = collections.defaultdict(None) print(d[1]) | Line 4: KeyError: 1 |
import collections def factory(): '''Returns a default value.''' return 'Hi!' d = collections.defaultdict(factory) print(d[1]) | Hi! |
import collections def factory(): '''Returns a default value.''' return 'Hi!' d = collections.defaultdict(factory, [(0, 'Hello!')]) print(d[0]) print(d[1]) | Hello! Hi! |
import collections def add_to_dict(d, key, value): ''' Adds value to a list associated with that key in the defaultdict d. ''' d[key].append(value) d = collections.defaultdict(lambda : []) add_to_dict(d, 1, 'a') add_to_dict(d, 1, 'b') print(d[1]) | ['a', 'b'] |
The default_fun
argument is a zero-argument function which returns the default value for any previously undefined key during a lookup. This is known as the default factory. If the factory is the special value None
, which is the default value if no argument is given, then keys will not have a default value during lookup, and thus that default dictionary will behave like a standard dictionary.
The optional iterable or iterator an_iter
is treated the same as with dict()
to initialize the dictionary contents.
a_defdict.default_factory
Code | Output |
---|---|
import collections d = collections.defaultdict(None) print(d.default_factory) | None |
The default factory function for a default dictionary can be accessed via this attribute.
a_defdict.default_factory
.a_defdict.__missing__()
collections.Counter
a_counter.elements
a_counter.most_common
a_counter.subtract
a_counter.update
dict
[]
a_dict.get
[]=
a_dict.setdefault()
a_dict.pop
a_dict.items
a_dict.keys
a_dict.values
a_dict.clear
a_dict.update
{key_expr: val_expr for … if …}
in
not in
len
sum
max
min
zip
sorted
map
filter
reduce
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
callable
A Counter is a mapping from keys to integers. These integers are traditionally used as counts, but negative integers are also allowed. When looking up a key that has not been previously added to the counter, its value will be zero.
To use these Counters, first import the module with import collections
.
collections.Counter()
collections.Counter(an_iter)
Code | Output |
---|---|
import collections print(collections.Counter({'a': 3, 'c': -1})) | Counter({'a': 3, 'c': -1}) |
import collections c = collections.Counter() c['a'] += 1 print(c['a']) print(c['b']) | 1 0 |
import collections c = collections.Counter({'a': 3, 'c': -1}) c['a'] += 1 print(c['a']) print(c['b']) | 4 0 |
Returns a new Counter, possibly initialized with counts provided in the iterable an_iter
.
a_counter.elements()
Code | Output |
---|---|
import collections c = collections.Counter({'a': 3, 'c': 8}) i = c.elements() print(i.next()) print(i.next()) | ('a', 3) ('c', 8) |
Creates an iterator whose elements are the key/value pairs of the counter a_counter
. The iterator's elements will be in an arbitrary implementation-specific order.
a_counter.most_common()
a_counter.most_common(n)
Code | Output |
---|---|
import collections print(collections.Counter({'a': 3, 'b': 5, 'c': 1, 'd': 3}).most_common()) | [('b', 5), ('a', 3), ('d', 3), ('c', 1)] |
import collections print(collections.Counter({'a': 3, 'b': 5, 'c': 1, 'd': 3}).most_common(2)) | [('b', 5), ('a', 3)] |
Returns a list of pairs of the counter a_counter
's n
most common keys and corresponding values, listed in descending value order. Keys with the same value are listed in arbitrary order. If n
is not specified, then all key-value pairs are listed.
a_counter.subtract(an_iter)
Code | Output |
---|---|
import collections c = collections.Counter({'a': 1, 'b': 2}) c.subtract({'a': 4, 'c': 3}) print(c) | Counter({'a': -3, 'b': 2, 'c': -3}) |
Mutates counter a_counter
by subtracting each key's respective value in an_iter
from its value in a_counter
.
a_counter.update(an_iter)
Code | Output |
---|---|
import collections c = collections.Counter({'a': 1, 'b': 2}) c.update({'a': 4, 'c': 3}) print(c) | Counter({'a': 5, 'b': 2, 'c': 3}) |
Mutates counter a_counter
by adding each key's respective value in an_iter
from its value in a_counter
.
This module allows use of regular expressions, also known as regexps. To use these operations, first import the module with import re
.
Most of the Python regular expression syntax is supported.
re.findall(pattern, string)
re.findall(pattern, string, flags = val)
Code | Output |
---|---|
import re print(re.findall(r'ZZZ', 'a quick brown fox')) | [] |
import re print(re.findall(r'[a-z]*o[a-z]*', 'a quick brown fox')) | ['brown', 'fox'] |
import re print(re.findall('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE)) | ['A', 'saves'] |
Returns a list of all the matches of the regular expression pattern in the given text string.
re.search(pattern, string)
re.search(pattern, string, flags = val)
Code | Output |
---|---|
import re print(re.search(r'ZZZ', 'a quick brown fox')) | None |
import re if re.search(r'ZZZ', 'a quick brown fox'): print('Found pattern.') else: print('Did not find pattern.') | Did not find pattern. |
import re m = re.search(r'[a-z]*o[a-z]*', 'a quick brown fox') print(m.group(0)) | brown |
import re m = re.search('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE) print(m.group(0)) | A |
Returns the first match, if any, of the regular expression pattern in the given text string.
re.match(pattern, string)
re.match(pattern, string, flags = val)
Code | Output |
---|---|
import re print(re.match(r'ZZZ', 'a quick brown fox')) | None |
import re if re.match(r'ZZZ', 'a quick brown fox'): print('Found pattern.') else: print('Did not find pattern.') | Did not find pattern. |
import re print(re.match(r'[a-z]*o[a-z]*', 'a quick brown fox')) | None |
import re m = re.match('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE) print(m.group(0)) | A |
Returns the match, if any, of the regular expression pattern at the beginning of the given text string.
re.split(pattern, string)
re.split(pattern, string, maxsplit = val)
re.split(pattern, string, maxsplit = val, flags = val)
Code | Output |
---|---|
import re print(re.split(r's+', 'a quick brown fox')) | ['a', 'quick', 'brown', 'fox'] |
import re print(re.split(r's+', 'a quick brown fox', 2)) | ['a', 'quick', 'brown fox'] |
import re print(re.split(r'(s+)', 'a quick brown fox')) | ['a', ' ', 'quick', ' ', 'brown', ' ', 'fox'] |
import re print(re.split('a', 'A stitch in time saves nine.', 0, re.IGNORECASE)) | ['', ' stitch in time s', 'ves nine.'] |
Splits the given text string into a list of strings, using the pattern regular expression as separators. If the regular expression is surrounded by parentheses, then the instances of the separators are included in the list of strings, otherwise they are not.
If maxsplit
is positive, then it splits the text at the first maxsplit
occurrences of the pattern. If flags
is positive, then the pattern is modified by the flags.
re.I
re.IGNORECASE
Flag to indicate that regular expression pattern matching should be case-insensitive. By default, matching is case sensitive.
match_obj.group(a_num)
match_obj.groups(a_num)
re.compile()
re.finditer()
re.sub()
re.subn()
re.escape()
re.purge()
re.DEBUG
re.L
re.LOCALE
re.M
re.MULTILINE
re.S
re.DOTALL
re.U
re.UNICODE
re.X
re.VERBOSE
match_obj.expand()
match_obj.groupdict()
match_obj.start()
match_obj.end()
match_obj.span()
match_obj.pos
match_obj.endpos
match_obj.lastindex
match_obj.lastgroup
match_obj.re
match_obj.string
This module includes operations that measure the passage of time. To use these operations, first import the module with import time
.
time.time()
Code | Output |
---|---|
import time print(time.time()) | 1349712380.59 # One possible output. |
import time time1 = time.time() … # The code being timed time2 = time.time() print('Time elapsed:', time2 - time1) | Time elapsed: 2.64113 # One possible output. |
Returns the current time as the number of seconds since some constant system-defined time.
A common usage is to measure the time to run an operation, as in the last example above.
time.accept2dyear
time.altzone
time.asctime()
time.clock()
time.ctime()
time.daylight
time.gmtime()
time.localtime()
time.mktime()
time.sleep()
time.strftime()
time.strptime()
time.struct_time
time.timezone
time.tzname
time.tzset()
codeskulptor.file2url
— Abbreviating standard URLsThis module contains functions for obtaining input data from the web. Currently, CodeSkulptor's implementation of this module supports input only, not output, and only from a a CodeSkulptor-affiliated data storage site. To use these operations, first import the module with import urllib.request
.
File objects represent open files. A file object keeps track of the current position in the file. Each read operation gets data starting at this position and advances the position to the end of the returned data. CodeSkulptor only supports obtaining an open file via urllib.request.urlopen()
.
urllib.request.urlopen(url)
Code | Output |
---|---|
import urllib.request import codeskulptor a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print(a_file.read()) | This is line one. This is line two. This is line three. |
Returns a read-only file object of the data found at the given URL. Causes no error if there is no such URL.
Currently, the only URLs that are supported are those files provided by the CodeSkulptor authors.
urllib.request.urlopen()
with multiple argumentsurllib.request.install_opener()
urllib.request.build_opener()
CodeSkulptor3 implements three custom modules for graphics in the browser, each with an easy-to-learn interface. The SimpleGUI module is for building interactive programs and drawing. The SimpleMap module is for drawing features on maps. The SimplePlot module is for plotting numeric data. To use these operations, first import the appropriate module with import simplegui
, import simplemap
, or import simpleplot
.
simplegui.create_frame
frame.set_canvas_background
frame.start
frame.get_canvas_textwidth
frame.add_label
frame.add_button
frame.add_input
frame.set_keydown_handler
frame.set_keyup_handler
frame.set_mouseclick_handler
frame.set_mousedrag_handler
frame.set_draw_handler
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
callable
A frame is a window, which is a container for the controls, status information, and canvas. A program can create only one frame.
simplegui.create_frame(title, canvas_width, canvas_height)
simplegui.create_frame(title, canvas_width, canvas_height, control_width)
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) | # Opens frame |
import simplegui frame = simplegui.create_frame('Testing', 200, 200, 300) | # Opens frame |
Creates a new frame for interactive programs. The frame's window has the given title, a string. The frame consists of two parts: a control panel on the left and a canvas on the right. The control panel's width in pixels can be specified by the number control_width
. The canvas width in pixels is the number canvas_width
. The height in pixels of both the control panel and canvas is the number canvas_height
.
frame.set_canvas_background(color)
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) frame.set_canvas_background('Red') frame.start() | # Opens frame with a red background |
Changes the background color of the frame's canvas, which defaults to black.
frame.start()
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) frame.start() | # Opens frame |
Starts all frame event handlers — drawing and controls.
frame.get_canvas_textwidth(text, size)
frame.get_canvas_textwidth(text, size, face)
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) print frame.get_canvas_textwidth('hello', 12) | 23 |
import simplegui frame = simplegui.create_frame('Testing', 100, 100) print frame.get_canvas_textwidth('hello', 12, 'sans-serif') | 27 |
Given a text string, a font size, and a font face, this returns the width of the text in pixels. It does not draw the text. This is useful in computing the position to draw text when you want it centered or right justified in some region.
The supported font faces are the default 'serif'
, 'sans-serif'
, and 'monospace'
.
Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down in the order of creation. Status information is at the bottom of the control panel.
frame.add_label(text)
frame.add_label(text, width)
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) label1 = frame.add_label('My first label') label2 = frame.add_label('My second label', 200) label3 = frame.add_label('My third label', 20) | # Opens frame with three labels |
control.get_text()
— Gets the current label textcontrol.set_text()
— Sets the current label textAdds a text label to the control panel. The width of the label defaults to fit the width of the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the label.
frame.add_button(text, button_handler)
frame.add_button(text, button_handler, width)
Code | Output |
---|---|
import simplegui def button_handler(): … frame = simplegui.create_frame('Testing', 100, 100) button1 = frame.add_button('Label 1', button_handler) button2 = frame.add_button('Label 2', button_handler, 50) | # Opens frame with two buttons |
control.get_text()
— Gets the current label textcontrol.set_text()
— Sets the current label textAdds a button to the frame's control panel with the given text label. The width of the button defaults to fit the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the button.
The handler should be defined with no parameters, as in the above example.
frame.add_input(text, input_handler, width)
Code | Output |
---|---|
import simplegui def input_handler(text_input): … frame = simplegui.create_frame('Testing', 100, 100) inp = frame.add_input('My label', input_handler, 50) | # Opens frame with one input box |
control.get_text()
— Gets the current input textcontrol.set_text()
— Sets the current input text, e.g., to specify a default valueAdds a text input field to the control panel with the given text label. The input field has the given width in pixels.
The handler should be defined with one parameter, as in the above example. This parameter will receive a string of the text input when the user presses the Enter key.
control.get_text()
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) label = frame.add_label('Label') label.set_text('New label') print(label.get_text()) | New label |
import simplegui def button_handler(): … frame = simplegui.create_frame('Testing', 100, 100) button = frame.add_button('Press this button', button_handler) print(button.get_text()) | Press this button |
import simplegui def input_handler(text_input): … frame = simplegui.create_frame('Testing', 100, 100) inp = frame.add_input('Label', input_handler, 50) print(inp.get_text()) |
control.set_text()
— Sets the textReturns the text in a label, the text label of a button, or the text in the input field of a text input, respectively. For an input field, this is useful to look at the contents of the input field before the user presses the Enter key.
control.set_text(text)
Code | Output |
---|---|
import simplegui frame = simplegui.create_frame('Testing', 100, 100) label = frame.add_label('Label') label.set_text('New label') | # Opens frame with a text string |
import simplegui def button_handler(): … frame = simplegui.create_frame('Testing', 100, 100) button = frame.add_button('Label', button_handler) button.set_text('New label') | # Opens frame with one button |
import simplegui def input_handler(text_input): … frame = simplegui.create_frame('Testing', 100, 100) inp = frame.add_input('Label', input_handler, 50) inp.set_text('Default contents') | # Opens frame with one input box |
control.get_text()
— Gets the textChanges the text in a label, the text label of a button, or the text in the input field of a text input, respectively. For a button, it also resizes the button if the button wasn't created with a particular width. For an input field, this is useful to provide a default input for the input field.
frame.set_keydown_handler(key_handler)
frame.set_keyup_handler(key_handler)
Code | Output |
---|---|
import simplegui def key_handler(key): … frame = simplegui.create_frame('Testing', 100, 100) frame.set_keydown_handler(key_handler) frame.start() | # Opens frame with active keydown handler |
These add keyboard event handlers waiting for keydown, and keyup events, respectively. When any key is pressed, the keydown handler is called once. When any key is released, the keyup handler is called once.
The handler for each should be defined with one parameter, as in the above example. This parameter will receive an integer representing a keyboard character.
frame.set_mouseclick_handler(mouse_handler)
frame.set_mousedrag_handler(mouse_handler)
Code | Output |
---|---|
import simplegui def mouse_handler(position): … frame = simplegui.create_frame('Testing', 100, 100) frame.set_mouseclick_handler(mouse_handler) frame.start() | # Opens frame with active mouseclick handler |
These add keyboard event handlers waiting for mouseclick and mousedrag events, respectively. When a mouse button is clicked, i.e., pressed and released, the mouseclick handler is called once. When a mouse is dragged while the mouse button is being pressed, the mousedrag handler is called for each new mouse position.
The handler for each should be defined with one parameter, as in the above example. This parameter will receive a pair of screen coordinates, i.e., a tuple of two non-negative integers.
The canvas is where you can draw text and shapes.
frame.set_draw_handler(draw_handler)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): … frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame with active draw handler |
Adds an event handler that is responsible for all drawing.
The handler should be defined with one parameter, as in the above example. This parameter will receive a canvas object.
canvas.draw_text(text, point, font_size, font_color)
canvas.draw_text(text, point, font_size, font_color, font_face)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_text('A', (20, 20), 12, 'Red') canvas.draw_text('B', [30, 50], 20, 'Blue') canvas.draw_text('C', (80, 50), 12, 'Gray', 'serif') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws three letters |
Writes the given text string in the given font size, color, and font face. The point is a 2-element tuple or list of screen coordinates representing the lower-left-hand corner of where to write the text.
The supported font faces are 'serif'
(the default), 'sans-serif'
, and 'monospace'
.
In order to position the text where you want, you may want to determine the text's width.
canvas.draw_line(point1, point2, line_width, line_color)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_line((10, 20), (30, 40), 12, 'Red') canvas.draw_line([10, 20], [80, 70], 20, 'Blue') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws two lines |
Draws a line segment between the two points, each of which is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive.
canvas.draw_polyline(point_list, line_width, line_color)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_polyline([(10, 20), (30, 20), (90, 70)], 12, 'Red') canvas.draw_polyline([[40, 20], [80, 40], [30, 90]], 20, 'Blue') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws two polylines |
Draws a sequence of line segments between each adjacent pair of points in the non-empty list. It is an error for the list of points to be empty. Each point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive.
canvas.draw_polygon(point_list, line_width, line_color)
canvas.draw_polygon(point_list, line_width, line_color, fill_color = color)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_polygon([(10, 20), (20, 30), (30, 10)], 12, 'Green') canvas.draw_polygon([[30, 20], [40, 40], [50, 20], [10, 10]], 12, 'Red') canvas.draw_polygon([(50, 70), (80, 40), (30, 90)], 5, 'Blue', 'White') canvas.draw_polygon([[90, 70], [80, 40], [70, 90], [70, 70]], 12, 'Yellow', 'Orange') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws four polygons |
Draws a sequence of line segments between each adjacent pair of points in the non-empty list, plus a line segment between the first and last points. It is an error for the list of points to be empty. Each point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels, and must be positive. The fill color defaults to None
. If the fill color is specified, then the interior of the polygon is colored.
canvas.draw_circle(center_point, radius, line_width, line_color)
canvas.draw_circle(center_point, radius, line_width, line_color, fill_color = color)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_circle((10, 10), 20, 12, 'Green') canvas.draw_circle([20, 30], 30, 12, 'Red') canvas.draw_circle((50, 50), 20, 5, 'Blue', 'White') canvas.draw_circle([70, 80], 30, 10, 'Yellow', 'Orange') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws four circles |
Draws a circle at the given center point having the given radius. The point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive. The fill color defaults to None
. If the fill color is specified, then the interior of the circle is colored.
canvas.draw_arc(center_point, radius, start_angle, end_angle, line_width, line_color)
canvas.draw_arc(center_point, radius, start_angle, end_angle, line_width, line_color, fill_color = color)
Code | Output |
---|---|
import simplegui import math def draw_handler(canvas): canvas.draw_arc((10, 10), 20, 0, math.pi, 12, 'Green') canvas.draw_arc([20, 30], 30, math.pi, 2*math.pi, 12, 'Red') canvas.draw_arc((50, 50), 20, 0.5*math.pi, 1.5*math.pi, 5, 'Blue', 'White') canvas.draw_arc([70, 80], 30, 0, 0.5*math.pi, 10, 'Yellow', 'Orange') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws four arcs |
Draws an arc at the given center point having the given radius. The point is a 2-element tuple or list of screen coordinates. The starting and ending angles indicate which part of a circle should be drawn. Angles are given in radians, clockwise starting with a zero angle at the 3 o'clock position. The line's width is given in pixels and must be positive. The fill color defaults to None
. If the fill color is specified, then the interior of the circle is colored.
canvas.draw_point(point, color)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_point((10, 10), 'Green') canvas.draw_point([20, 30], 'Red') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws two points |
Draws a 1×1 rectangle at the given point in the given color. The point is a 2-element tuple or list of screen coordinates.
canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest)
canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest, rotation)
Code | Output |
---|---|
import simplegui import codeskulptor def draw_handler(canvas): canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100)) image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg')) frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws a scaled map |
import simplegui import codeskulptor def draw_handler(canvas): canvas.draw_image(image, (1521 // 2, 1818 // 2), (1521, 1818), (40, 70), (100, 100), 2) image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg')) frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws a strangely rotated scaled map |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsimplegui.load_image
— Loading image fileDraw an image that was previously loaded. center_source
is a pair of coordinates giving the position of the center of the image, while center_dest
is a pair of screen coordinates specifying where the center of the image should be drawn on the canvas. width_height_source
is a pair of integers giving the size of the original image, while width_height_dest
is a pair of integers giving the size of how the images should be drawn. The image can be rotated clockwise by rotation
radians.
You can draw the whole image file or just part of it. The source information (center_source
and width_height_source
) specifies which pixels to display. If it attempts to use any pixels outside of the actual file size, then no image will be drawn.
Specifying a different width or height in the destination than in the source will rescale the image.
A timer calls an event handler repeatedly at a specified interval.
A program can have an arbitrary number of timers running simultaneously. However, having many timers running will slow CodeSkulptor.
simplegui.create_timer(interval, timer_handler)
Code | Output |
---|---|
import simplegui def timer_handler(): … timer = simplegui.create_timer(500, timer_handler) timer.start() | # starts a timer |
Creates a timer. Once started, it will repeatedly call the given event handler at the specified interval, which is given in milliseconds.
The handler should be defined with no arguments, as in the above example.
timer.start()
Code | Output |
---|---|
import simplegui def timer_handler(): … timer = simplegui.create_timer(500, timer_handler) timer.start() | # starts a timer |
Starts or restarts the timer.
timer.stop()
Code | Output |
---|---|
import simplegui def timer_handler(): timer.stop() timer = simplegui.create_timer(500, timer_handler) timer.start() | # starts a timer and stops it on its first tick |
Stops the timer. It can be restarted.
timer.is_running()
Code | Output |
---|---|
import simplegui def timer_handler(): pass timer = simplegui.create_timer(100, timer_handler) print(timer.is_running()) timer.start() print(timer.is_running()) timer.stop() print(timer.is_running()) | False True False |
Returns whether the timer is running, i.e., it has been started, but not stopped.
An image must be loaded before it can be drawn.
simplegui.load_image(URL)
Code | Output |
---|---|
import simplegui import codeskulptor def draw_handler(canvas): canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100)) image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg')) frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() | # Opens frame and draws a scaled map |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLcanvas.draw_image
— Drawing image fileLoads an image from the specified URL. The image can be in any format supported by the browser. No error is raised if the file isn't found or is of an unsupported format.
image.get_width()
Returns the width of the image in pixels. While the image is still loading, it returns zero.
image.get_height()
Returns the height of the image in pixels. While the image is still loading, it returns zero.
A sound must be loaded before it can be played. To restart playing a sound from the beginning, it must first be rewound. Separate sounds are played in separate audio channels and may overlap. The number of sounds that can be played simultaneously is system-dependent.
simplegui.load_sound(URL)
Code | Output |
---|---|
import simplegui import codeskulptor sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg')) |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsound.play()
— How to play the soundLoads a sound from the specified URL. Supports whatever audio formats that your browser supports. No error is raised if the file isn't found or is of an unsupported format.
sound.play()
Code | Output |
---|---|
import simplegui import codeskulptor sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg')) sound.play() | # plays a sound |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsimplegui.load_sound()
— How to load a soundStarts playing a sound, or restarts playing it at the point it was paused.
sound.pause()
Code | Output |
---|---|
import simplegui import codeskulptor sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg')) sound.play() sound.pause() | # starts to play a sound, then immediately pauses |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsimplegui.load_sound()
— How to load a soundsound.play()
— How to play the soundStops the playing of the sound. Playing can be restarted at the stopped point with sound.play()
.
sound.rewind()
Code | Output |
---|---|
import simplegui import codeskulptor sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg')) sound.play() sound.rewind() sound.play() | # starts to play a sound, rewinds it, then plays it again from the beginning |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsimplegui.load_sound()
— How to load a soundsound.play()
— How to play the soundStops the playing of the sound, and makes it so the next sound.play()
will start playing the sound at the beginning.
sound.set_volume(volume)
Code | Output |
---|---|
import simplegui import codeskulptor sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg')) sound.set_volume(0.7) sound.play() |
codeskulptor.file2url
— Converting CodeSkulptor filename to URLsimplegui.load_sound()
— How to load a soundsound.play()
— How to play the soundChanges the volume for the sound to be the given level on a 0 (silent)–1.0 (maximum) scale. Default is 1.
The following color names are considered the most standard.
'Aqua' | |
---|---|
'Black' | |
'Blue' | |
'Fuchsia' | |
'Gray' | |
'Green' | |
'Lime' | |
'Maroon' | |
'Navy' | |
'Olive' | |
'Orange' | |
'Purple' | |
'Red' | |
'Silver' | |
'Teal' | |
'White' | |
'Yellow' |
More generally, you may use any HTML color name. Furthermore, custom colors and transparencies can be specified in a any CSS color format, including hexadecimal, RGB, RGBA, HSL, and HSLA.
simplegui.KEY_MAP[character]
Code | Output |
---|---|
import simplegui print(simplegui.KEY_MAP['left']) | 37 |
The keyboard event handlers receive the relevant key as an integer. Because different browsers can give different values for the same keystrokes, SimpleGUI provides a way to get the appropriate key integer for a given meaning.
The acceptable strings for character
are the letters 'a'
…'z'
and 'A'
…'Z'
, the digits '0'
…'9'
, 'space'
, 'left'
, 'right'
, 'up'
, and 'down'
. Note that other keyboard symbols are not defined in simplegui.KEY_MAP
.
The SimpleMap module provides an interface for drawing and annotating maps. The underlying maps are provided by Google Maps. Points on the map are referred to by a pair of numbers representing latitude and longitude.
The module uses three types of objects: maps, markers, and lines.
simplemap.create_map(title, coordinates, map_width, map_height)
simplemap.create_map(title, coordinates, map_width, map_height, control_width)
Code | Output |
---|---|
import simplemap simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) | # Creates a map. |
Creates a map in a new window titled by the string title
and with the given width and height in pixels. The map contents are centered on the given coordinates in latitude and longitude.
If a control_width
is given, it also creates an control panel. By default, no area is created, and such button controls are not allowed.
a_map.add_marker(description, id, icon_url, coordinates, handler)
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) | # Creates a map with one marker. |
Draws a marker on the map, adds a corresponding marker object to the map object, and returns the marker object. The marker is represented graphically by the image found at the URL string icon_url
. The marker is placed at the latitude and longitude specified by the pair of numbers coordinates
. The marker has a description
string which appears when you hover the mouse on the marker. The marker also has an id
data string. When the image is clicked on, the event handler function click_handler
will be called.
The handler should be defined with one parameter, as in the above example. This parameter will receive the marker object whose image was clicked on.
a_map.draw_line(start_marker, stop_marker)
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) rice.draw_line(wiess_college, duncan_hall) | # Draws a line between two map markers |
Draws a black path between the two given markers on the map. The path follows the available streets. Adds a corresponding line object to the map object, and returns the line object.
a_map.get_markers()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) for marker in rice.get_markers(): print(marker.get_description()) | Wiess College Duncan Hall |
Returns a set of all marker objects represented on the map.
map.get_lines()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) rice.draw_line(wiess_college, duncan_hall) for line in rice.get_lines(): print(line.get_start().get_description()) print(line.get_stop().get_description()) | Wiess College Duncan Hall |
Returns a set of all line objects represented on the map.
a_map.clear_markers()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) rice.draw_line(wiess_college, duncan_hall) rice.clear_markers() print(rice.get_markers()) | set([]) |
map.clear()
— Removes all markers and linesmarker.remove()
— Removes one markerErases all markers from the drawn map. Does not remove any lines between those markers. Removes all marker objects from the map object.
a_map.clear_lines()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) rice.draw_line(wiess_college, duncan_hall) rice.clear_lines() print(rice.get_lines()) | set([]) |
map.clear()
— Removes all markers and linesa_line.remove()
— Removes one lineErases all paths from the drawn map. Does not remove any markers. Removes all line objects from the map object.
a_map.clear()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) rice.draw_line(wiess_college, duncan_hall) rice.clear() print(rice.get_markers()) print(rice.get_lines()) | set([]) set([]) |
map.clear_markers()
— Removes all markersmap.clear_lines()
— Removes all linesErases all markers and line segments from the drawn map. Removes all marker objects and line objects from the map object.
a_map.add_button(text, handler)
a_map.add_button(text, handler, width)
Code | Output |
---|---|
import simplemap rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500, 150) def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) def delete_wiess (): rice.clear_markers() rice.add_button('Delete Wiess Marker', delete_wiess) | # Creates map with button that will delete a marker |
Adds a button in the map's control panel with the given text label. The width of the button defaults to the width of the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the button.
a_map.add_break()
Code | Output |
---|---|
import simplemap rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500, 150) def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) def delete_wiess (): rice.clear_markers() rice.add_button('Delete Wiess Marker', delete_wiess) rice.add_break() rice.add_button('Delete Wiess Marker', delete_wiess) | # Creates map with two buttons that will delete a marker |
Adds a line break to the map's control panel. Useful to separate buttons.
A marker object corresponds to a drawn marker icon image on the map. Its location is determined by a pair of latitude and longitude coordinates.
a_marker.get_description
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) print(wiess_college.get_description()) | Wiess College |
Returns the description string of the marker.
a_marker.get_id()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) print wiess_college.get_id() | W |
Returns the ID string of the marker.
a_marker.get_coordinates()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) print wiess_college.get_coordinates() | (29.714967, -95.400694) |
Returns the latitude and longitude coordinates of the marker as a pair of numbers.
a_marker.get_icon()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) print(wiess_college.get_icon()) | http://labs.google.com/ridefinder/images/mm_20_green.png |
Returns the icon URL of the marker.
a_marker.set_icon(URL)
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) wiess_college.set_icon(red_icon) print(wiess_college.get_icon()) | http://labs.google.com/ridefinder/images/mm_20_red.png |
Changes the icon of the marker to be the image at the given URL.
a_marker.remove()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) wiess_college.remove() print(rice.get_markers()) | set([]) |
map.clear_markers()
— Removes all markersmap.clear()
— Removes all markers and linesErases the marker from the drawn map. Does not remove any lines using the marker. Removes the marker object from the map object.
A line object corresponds to a drawn path between two markers on the map. The path follows the available streets on the map. The path color defaults to black.
a_line.get_start()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) line = rice.draw_line(wiess_college, duncan_hall) print(line.get_start().get_description()) | Wiess College |
Returns the starting, i.e., first, marker of a line.
a_line.get_stop()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) line = rice.draw_line(wiess_college, duncan_hall) print(line.get_stop().get_description()) | Duncan Hall |
Returns the stopping, i.e., second, marker of a line.
a_line.set_color(color)
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) line = rice.draw_line(wiess_college, duncan_hall) line.set_color('Yellow') | # Draws a yellow line on a map |
Changes the color of the path, which defaults to black, between the two endpoint markers of the line.
a_line.remove()
Code | Output |
---|---|
import simplemap def click_handler(a_marker): print('Clicked on marker', a_marker.get_description()) green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png' red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png' rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500) wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler) duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler) line = rice.draw_line(wiess_college, duncan_hall) line.remove() print(rice.get_lines()) | set([]) |
map.clear_lines()
— Removes all linesmap.clear()
— Removes all markers and linesErases the line from the drawn map. Does not remove the endpoint markers of the line. Removes the line object from the map object.
SimplePlot provides functions for plotting numeric data — both the x- and y-coordinate values should be numbers. To use its operations, first import the module with import simpleplot
.
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points)
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points, legends)
Code | Output |
---|---|
import simpleplot dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] simpleplot.plot_lines('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], True, ['dataset1', 'dataset2']) | # pops up a line plot |
Displays a plot in a new window named framename
with the width
and height
given in pixels. The x-axis is labeled with the string xlabel
. The y-axis is labeled with the string ylabel
.
The data to display is given in datasets
, which is a sequence of data sets. Each data set is connected with a line through each data point. Each data set can be given in either of two representations.
The optional boolean points
indicates that the individual points should be indicated. It defaults to False
.
The optional legends
is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets
.
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets, legends)
Code | Output |
---|---|
import simpleplot dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] simpleplot.plot_bars('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2']) | # pops up a bar plot |
Displays a plot in a new window named framename
with the width
and height
given in pixels. The x-axis is labeled with the string xlabel
. The y-axis is labeled with the string ylabel
.
The data to display is given in datasets
, which is a sequence of data sets. Each data point is represented by a vertical bar, and corresponding data points of each data set are grouped together. Each data set can be given in either of two representations.
The optional legends
is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets
.
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets, legends)
Code | Output |
---|---|
import simpleplot dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (1, 5), (2, 5), (4, 3), (7, 6)] simpleplot.plot_scatter('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2']) | # pops up a scatter plot |
Displays a plot in a new window named framename
with the width
and height
given in pixels. The x-axis is labeled with the string xlabel
. The y-axis is labeled with the string ylabel
.
The data to display is given in datasets
, which is a sequence of data sets. Each data point is represented by a colored dot, and corresponding data points of each data set are the same color. Each data set can be given in either of two representations.
The optional legends
is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets
.
CodeSkulptor3 implements two other custom modules. The Numeric module is for mathematics with two-dimensional matrices. The CodeSkulptor module is a small collection of miscellaneous operations. To use these operations, first import the appropriate module with import numeric
or import codeskulptor
.
The Numeric module is for mathematics with two-dimensional matrices. It provides some of the basic operations of linear algebra. Matrices are restricted to only contain numbers. This module is not a part of standard Python, rather it is a simpler and lighter weight module than the commonly used NumPy module. To use these operations, first import the module with import numeric
.
numeric.Matrix(data)
Code | Output |
---|---|
import numeric print(numeric.Matrix([[0, 1], [3, 7], [5, 2]])) | [[0, 1], [3, 7], [5, 2]] |
Returns a 2-dimensional matrix object corresponding to the given data, which must be a sequence of sequences.
numeric.identity(size)
Code | Output |
---|---|
import numeric print(numeric.identity(3)) | [[1, 0, 0], [0, 1, 0], [0, 0, 1]] |
Returns a size
×size
2-dimensional identity matrix.
a_matrix[(i, j)]
a_matrix.__getitem__((i, j))
Code | Output |
---|---|
import numeric print(numeric.identity(3)[(0, 0)]) | 1.0 |
Returns the value in the matrix a_matrix
at row i
and column j
.
a_matrix.getrow(i)
Code | Output |
---|---|
import numeric print(numeric.identity(3).getrow(1)) | [[0, 1, 0]] |
If the given matrix a_matrix
has dimensions m×n, then the result is a new 1×n matrix that is a copy of row i
of the matrix.
a_matrix.getcol(j)
Code | Output |
---|---|
import numeric print(numeric.identity(3).getcol(2)) | [[0, 0, 1]] |
If the given matrix a_matrix
has dimensions m×n, then the result is a new 1×m matrix that is a copy of column j
of the matrix.
a_matrix[(i, j)] = value
a_matrix.__setitem__((i, j), value)
Code | Output |
---|---|
import numeric matrix = numeric.identity(3) matrix[(0, 0)] = 5 print(matrix) | [[5, 0, 0], [0, 1, 0], [0, 0, 1]] |
a_matrix.__setitem__()
.Sets the value in the matrix a_matrix
at row i
and column j
to be value value
.
matrix1 + matrix2
Code | Output |
---|---|
import numeric matrix = numeric.identity(3) print(matrix + matrix) | [[2, 0, 0], [0, 2, 0], [0, 0, 2]] |
Adds two m×n matrices. The result is a new m×n matrix.
matrix1 - matrix2
Code | Output |
---|---|
import numeric matrix = numeric.identity(3) print(matrix - matrix) | [[0, 0, 0], [0, 0, 0], [0, 0, 0]] |
Subtracts m×n matrix matrix2
from m×n matrix matrix1
. The result is a new m×n matrix.
matrix1 @ matrix2
Code | Output |
---|---|
import numeric matrix1 = numeric.Matrix([[1, 2]]) matrix2 = numeric.Matrix([[3, 4, 5], [6, 7, 8]]) print(matrix1 @ matrix2) | [[15, 18, 21]] |
Muliplies m×n matrix matrix1
by n×p matrix matrix2
. The result is a new m×p matrix.
a_matrix * factor
factor * a_matrix
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[3, 4, 5], [6, 7, 8]]) print(matrix * 2) | [[6, 8, 10], [12, 14, 16]] |
Given a m×n matrix and a number factor
, it returns a new m×n matrix where each original element has been multiplied by factor
.
a_matrix.copy()
Code | Output |
---|---|
import numeric matrix1 = numeric.Matrix([[1, 2]]) matrix2 = matrix1.copy() matrix2[(0, 0)] = 5 print(matrix1) | [[1, 2]] |
Makes a new matrix with the same elements as a_matrix
.
a_matrix.inverse()
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[1, 0], [1, 2]]) print(matrix.inverse()) | [[1, 0], [-0.5, -0.5]] |
Given a n×n matrix a_matrix
, it returns its n×n matrix inverse, if it exists. Inverses exist only for some square matrices. If no inverse exists, an error is raised.
a_matrix.transpose()
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[1, 2]]) print(matrix.transpose()) | [[1], [2]] |
Given a m×n matrix a_matrix
, it returns its n×m matrix transpose. I.e., if a value is in the original matrix at row i and column j, then it is at row j and column i in its transpose.
a_matrix.abs()
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[1, -2, -5]]) print(matrix.abs()) | [[1, 2, 5]] |
Given a m×n matrix a_matrix
, it returns a new m×n matrix consisting of the absolute values of each of the original elements.
a_matrix.summation()
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[1, -2, -5], [4, -2, 0]]) print(matrix.summation()) | -4.0 |
Returns the sum of all the elements in the matrix a_matrix
.
a_matrix.shape()
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[1, -2, -5], [4, -2, 0]]) print(matrix.shape()) | (2, 3) |
Given a m×n matrix a_matrix
, it returns the pair (2-tuple) (m, n)
.
The CodeSkulptor module is a small collection of miscellaneous operations that are not in standard Python. To use these operations, first import the module with import codeskulptor
.
codeskulptor.file2url(filename)
Code | Output |
---|---|
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets-Quick_fox.txt')) print(a_file.read()) | The quick brown fox jumped over the lazy dog. |
urllib2.urlopen
— Opening text filesimplegui.load_image
— Loading image filesimplegui.load_sound
— Loading sound fileReturns a standard CodeSkulptor URL for the given filename. Such a URL is would be used as an argument to any function that opens a file. This allows you to abbreviate the URL for many files provided by the CodeSkulptor authors. This does not check whether the filename or URL exists.
codeskulptor.randomize_iteration(randomize=boolean)
Code | Output |
---|---|
import codeskulptor codeskulptor.randomize_iteration(randomize=True) s = {1, 2, 3} for element in s: print(element) for element in s: print(element) | # One possible result 2 1 3 3 2 1 |
Sets a global system flag to the given value of randomize
. By default, this flag is True
.
When this flag is True
, any iteration on dictionaries and sets is randomized, to emphasize that code should not depend upon the iteration ordering. When this flag is False
, the iteration order is determined in some implementation-dependent way.
CodeSkulptor3 is a browser-based programming environment for the programming language Python. CodeSkulptor3 runs in modern versions of Google Chrome, Mozilla Firefox, and Apple Safari. Some features may work in other browsers, such as Microsoft Internet Explorer, but do not expect full functionality.
The CodeSkulptor window consists of the following elements.
The control area is either on the left or the top, depending on the window dimensions, which consists of buttons for the main CodeSkulptor features: Run, Reset, Save, New URL, Download, Load, Join, the documentation you are currently reading, , and information about CodeSkulptor.
The left side of the main part of the page is an editor for typing in Python programs. Keyboard shortcuts are described below for Windows, Mac OS, and Linux. Also, if you double-click an identifier or other piece of text, it will highlight all the matching text.
The right side of the main part of the page is the console. When you run the program in the editor, its printed output and error messages are displayed here. The console output can be reset.
The vertical bar between the two main parts of the window can be adjusted to the left or right.
Runs the Python code that is in the CodeSkulptor editor. Prints the results of any print
statement and any error messages to the CodeSkulptor console. If you use the SimpleGUI module, your program can create a pop-up interactive window.
While the program is running, this button becomes a "Pause" button. You can pause the execution of your program at any time and the currently executing line of code will be highlighted in the editor. The editor will be read-only while the program is paused and this button becomes a "Resume" button. While paused, you can either resume the program or use the "Reset" button to end the execution of the program.
Clears the CodeSkulptor console and closes any pop-up windows created by CodeSkulptor.
Saves the contents of the CodeSkulptor editor to “cloud”-based storage. It also changes the URL shown in the browser to be one where you can access this program again. One way to remember this URL is to bookmark it in your browser.
The last part of this URL is a version number — each successive save will create a new version. Thus, each saved version is available from its own URL.
After saving, you can download the program to a file on your own computer.
On each save the URL for your program increases in version number. This button creates a new URL independent of the previous one.
Downloads a just-saved program to your own computer. This button is only active after you have saved this program and before you modify it further.
Loads a Python file from your own computer into the CodeSkulptor editor.
Allows you to create or join a collaborative editing session with others. This button will open a dialog box allowing you to enter the session ID of an existing collaborative editing session. If you leave it blank, a new session will be created.
In a collaborative editing session, the session ID will be displayed in the upper left corner of the window. You can send that session ID to others to allow them to join your session. The upper right corner of the window will display all of the users currently in the session. You can click your user to change your display name from the default.
Once in a collaborative editing session, this button becomes a "Leave" button that allows you to leave the session. You can then rejoin it later, if you desire.
Collaborative editing sessions are not permanent, and will be deleted in a day or so. Your work is not saved. Note, however, that anyone in a collaborative editing session can save the work at any time using the save button. If one person saves the file, that does not show up in any one else's editor. You either need to share the link with each other or each save your own copy.
(Chrome, Safari) Alt‑R | Run Python program. |
---|---|
(Chrome, Safari) Alt‑S | Save Python program. |
(Chrome, Safari) Alt‑X | Reset Python program. |
(Firefox) Alt‑Shift‑R | Run Python program. |
(Firefox) Alt‑Shift‑S | Save Python program. |
(Firefox) Alt‑Shift‑X | Reset Python program. |
Left Arrow | Move to the left one character. |
---|---|
Right Arrow | Move to the right one character. |
Up Arrow | Move up one line. |
Down Arrow | Move down one line. |
End | Go to the end of the current line. |
Home | Go to the beginning of the current line. |
PageUp | Move up one page. |
PageDown | Move down one page. |
Ctrl‑Home | Go to the beginning of the current page. |
Alt‑Up | Go to the beginning of the current page. |
Ctrl‑End | Go to the end of the current page. |
Ctrl‑Down | Go to the end of the current page. |
Ctrl‑Left | Move left one word. |
Ctrl‑Right | Move right one word. |
Alt‑Left | Go to the start of current line. |
Alt‑Right | Go to the end of current line. |
Delete | Delete character on the right. |
---|---|
Backspace | Delete character on the left. |
Insert | Overwrite characters on and after current location. |
Ctrl‑D | Delete current line. |
Ctrl‑Backspace | Delete word to the left. |
Ctrl‑Delete | Delete word to the right. |
Ctrl‑K | Comment all selected lines. |
Ctrl‑Shift‑K | Uncomment all selected lines. |
Ctrl‑A | Select all |
Ctrl‑C | Copy selected area |
Ctrl‑X | Cut selected area |
Ctrl‑V | Paste |
Ctrl‑Z | Undo |
Shift‑Ctrl‑Z | Redo |
Ctrl‑Y | Redo |
Tab | Indent right. Shifts cursor over to the next tab stop. |
---|---|
Shift‑Tab | “Smart” indent right. Shifts cursor over to the appropriate indentation given the context of the program. |
Ctrl‑[ | Indent left. Shifts cursor over left to the previous tab stop. |
Ctrl‑] | Indent right. Shifts cursor over right to{'key': the next tab stop. |
Cntl‑F | Start Searching |
---|---|
Cntl‑G | Find Next |
Shift‑Cntl‑G | Find Previous |
Shift‑Cntl‑F | Replace Once |
Shift‑Cntl‑R | Replace All |
(Chrome, Firefox, Safari) Ctrl‑Opt‑R | Run Python program. |
---|---|
(Chrome, Firefox, Safari) Ctrl‑Opt‑S | Save Python program. |
(Chrome, Firefox, Safari) Ctrl‑Opt‑X | Reset Python program. |
Left | Move to the left one character. |
---|---|
Right | Move to the right one character. |
Up | Move up one line. |
Down | Move down one line. |
Cmd‑Up | Go to the beginning of the current page. |
Cmd‑Down | Go to the end of the current page. |
Cmd‑Left | Go to the start of the current line. |
Cmd‑Right | Go to the end of the current line. |
Alt‑Left | Move left one word. |
Alt‑Right | Move right one word. |
Ctrl‑B | Move to the left one character. |
Ctrl‑F | Move to the right one character. |
Ctrl‑P | Move up one line. |
Ctrl‑N | Move down one line. |
Alt‑B | Move left one word. |
Alt‑F | Move right one word. |
Ctrl‑A | Go to the start of the current line. |
Ctrl‑E | Go to the end of the current line. |
Ctrl‑V | Move up one page. |
Shift‑Ctrl‑V | Move down one page. |
Delete | Delete character on the left. |
---|---|
Cmd‑D | Delete current line. |
Ctrl‑H | Delete character on the left. |
Ctrl‑D | Delete character on the right. |
Alt‑Delete | Delete word on the left. |
Alt‑D | Delete word on the right. |
Ctrl‑K | Comment all selected lines. |
Ctrl‑Shift‑K | Uncomment all selected lines. |
Cmd‑A | Select all |
Cmd‑C | Copy selected area |
Cmd‑X | Cut selected area |
Cmd‑V | Paste |
Cmd‑Z | Undo |
Shift‑Cmd‑Z | Redo |
Cmd‑Y | Redo |
Ctrl‑T | Swap positions of the character to the left and the character to the right of the cursor. |
Tab | Indent right. Shifts cursor over to the next tab stop. |
---|---|
Shift‑Tab | “Smart” indent right. Shifts cursor over to the appropriate indentation given the context of the program. |
Cmd‑[ | Indent left. Shifts cursor over left to the previous tab stop. |
Cmd‑] | Indent right. Shifts cursor over right to the next tab stop. |
Cmd‑F | Start Searching |
---|---|
Cmd‑G | Find Next |
Shift‑Cmd‑G | Find Previous |
Cmd‑Option‑F | Replace Once |
Shift‑Cmd‑Option‑F | Replace All |
(Chrome) Alt‑R | Run Python program. |
---|---|
(Chrome) Alt‑S | Save Python program. |
(Chrome) Alt‑X | Reset Python program. |
(Firefox) Alt‑Shift‑R | Run Python program. |
(Firefox) Alt‑Shift‑S | Save Python program. |
(Firefox) Alt‑Shift‑X | Reset Python program. |
Left Arrow | Move to the left one character. |
---|---|
Right Arrow | Move to the right one character. |
Up Arrow | Move up one line. |
Down Arrow | Move down one line. |
End | Go to the end of the current line. |
Home | Go to the beginning of the current line. |
PageUp | Move up one page. |
PageDown | Move down one page. |
Ctrl‑Home | Go to the beginning of the current page. |
Alt‑Up | Go to the beginning of the current page. |
Ctrl‑End | Go to the end of the current page. |
Ctrl‑Down | Go to the end of the current page. |
Ctrl‑Left | Move left one word. |
Ctrl‑Right | Move right one word. |
Alt‑Left | Go to the start of current line. |
Alt‑Right | Go to the end of current line. |
Delete | Delete character on the right. |
---|---|
Backspace | Delete character on the left. |
Insert | Overwrite characters on and after current location. |
Ctrl‑D | Delete current line. |
Ctrl‑Backspace | Delete word to the left. |
Ctrl‑Delete | Delete word to the right. |
Ctrl‑K | Comment all selected lines. |
Ctrl‑Shift‑K | Uncomment all selected lines. |
Ctrl‑A | Select all |
Ctrl‑C | Copy selected area |
Ctrl‑X | Cut selected area |
Ctrl‑V | Paste |
Ctrl‑Z | Undo |
Shift‑Ctrl‑Z | Redo |
Ctrl‑Y | Redo |
Tab | Indent right. Shifts cursor over to the next tab stop. Any new lines after the shifted current line will automatically start where the shifted line began. |
---|---|
Shift‑Tab | Indent right. Shifts cursor over to the next tab stop. Any new lines after the shifted current line will start at the beginning left margin. |
Ctrl‑[ | Indent left. Shifts cursor over left to the previous tab stop. |
Ctrl‑] | Indent right. Shifts cursor over right to the next tab stop. |
Ctrl‑F | Start Searching |
---|---|
Ctrl‑G | Find Next |
Shift‑Ctrl‑G | Find Previous |
Shift‑Ctrl‑F | Replace Once |
Shift‑Ctrl‑R | Replace All |
Searches for sections that contain all of the following space-separated text strings. Each string can contain letters, digits, and punctuation, and may represent a word or a part of a word. The search is case-insensitive.