CodeSkulptor is a browser-based Python interpreter, as featured in the online course “An Introduction to Interactive Programming in Python”. It implements a subset of Python 2, 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. In particular, when CodeSkulptor raises a Python error, it simply prints an error message, rather than returning an exception value.
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, except dictionary and set comprehensions.
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.
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
long
float
+
-
*
/
//
%
**
~
&
|
^
<<
>>
abs
round
bin
oct
hex
chr
ord
range
max
min
math.ceil
math.floor
math.trunc
math.fabs
math.log
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.seed
time.time
simpleplot.plot_lines
simpleplot.plot_bars
simpleplot.plot_scatter
a_matrix[]
a_matrix.summation
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
str
repr
Integers have a limited number of digits, whereas long integers can have an arbitrary number of digits. Operations that normally produce an integer will instead produce a long integer, if more digits are needed. Operations on long integers are slower than on other numbers.
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 12L | 12 |
print 12345678901234567890123456789012345678901234567890 | 12345678901234567890123456789012345678901234567890 |
print 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL | 340282366920938463463374607431768211455 |
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.
Any integer followed by an L
or whose absolute
value is greater than some minimum is consider a
long integer.
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()
, long()
,
float()
int(x)
long(x)
float(x)
Code | Output |
---|---|
print int() | 0 |
print int('234') | 234 |
print int(1.6) | 1 |
print int(False) | 0 |
print long() | 0 |
print long('234') | 234 |
print long(1.6) | 1 |
print long(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()
and long()
on integers)math.ceil()
— Rounds upmath.floor()
— Rounds down
Given a number, int()
and long()
return the integer part of it, i.e.,
they round towards zero.
Given a Boolean, they return zero
(i.e., 0
, 0L
, or 0.0
)
for False
, and one
(i.e., 1
, 1L
, or 1.0
)
for True
.
Given a string containing a printed representation of
an integer, int()
and long()
return 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 |
Returns the sum of a
and b
.
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 |
a = 3 print -a | -3 |
With two arguments, returns the difference of
a
and b
.
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 |
Returns product of a
and b
.
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 |
print 11 / 3 | 3 |
print 11 // 3 | 3 |
print 12.0 / 3.0 | 4.0 |
print 11.0 / 3.0 | 3.6666666666666665 |
print 11.0 // 3.0 | 3.0 |
The standard division operation, /
,
returns the quotient of a
and b
.
When both a
and b
are integers,
then so is the result, i.e., the result is instead
the floor of the quotient.
The integer division operation, //
,
returns the floor of the quotient of
a
and b
, i.e., the
integer part.
When both a
and b
are integers,
then so is the result, otherwise the result is a
floating-point number with no value after the decimal.
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 |
pow()
— Built-in exponentiation functionmath.pow()
and math.exp()
— Similar exponentiation functions
Returns x
to the power of y
.
Exponentiation and assignment can be combined with the
shorthand x **= y
, which is equivalent to
x = x ** y
.
pow()
pow(x, y)
pow(x, y, m)
Code | Output |
---|---|
print pow(3, 4) | 81 |
print pow(3, 4, 2) | 1 |
**
— Built-in exponentiation operatormath.pow()
and math.exp()
— Similar exponentiation functions
Given a number m
,
this returns the remainder of x
to the power
of y
, divided by m
.
Given no m
, this returns x
to the power of y
, just like
x ** y
.
abs()
abs(x)
Code | Output |
---|---|
print abs(3) | 3 |
print abs(-3.0) | 3.0 |
math.fabs()
— Always returns a floating-point number
Returns the absolute value of number x
.
The result is of the same type as the input.
round()
round(n)
round(n, i)
Code | Output |
---|---|
print round(12) | 12.0 |
print round(12.5) | 13.0 |
print round(-12.5) | -12.0 |
print round(123.4567, 2) | 123.46 |
print round(123.4567, -2) | 100.0 |
int()
and long()
— Round to zeromath.trunc()
— Rounds to zeromath.ceil()
— Rounds upmath.floor()
— Rounds down
With one number argument, it returns the floating-point
number that represents 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()
, oct()
,
hex()
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()
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()
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
bits
x >> n
:
bitwise shift right of x
by n
bits
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: …
).
While not encouraged, Booleans can also be used anywhere
that numbers can. True
and False
are then treated as 1
and 0
,
respectively.
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
0L
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
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 |
Returns True
for any
true-like)
value, and False
for any
false-like)
value.
and
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 |
or
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
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 |
any
any(an_iter)
Code | Output |
---|---|
print any([False, False, False]) | False |
print any([False, True, False]) | True |
print any([]) | False |
print any((0, 3)) | True |
print any('abc') | True |
Returns whether
bool(x)
is True
(or
true-like)
for any element x
in the iterable.
all
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
bin
oct
hex
chr
ord
re.findall
re.search
re.match
re.split
+
*
[]
[:]
[::]
a_seq.index
a_seq.count
random.shuffle
in
not in
len
sum
max
min
zip
sorted
map
filter
reduce
any
all
enumerate
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
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'''…'''
"…"
'…'
"""…"""
'''…'''
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 |
\xNN | 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()
str(x)
Code | Output |
---|---|
print str() | # The empty list |
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 = x print 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 unambiguity
Returns 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()
repr(an_obj)
Code | Output |
---|---|
print repr([3, 5, 9]) | [3, 5, 9] |
class Silly: def __init__(self, x): self.x = x print 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 readability
Returns 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 % value
a_str % a_tuple
a_str % a_dict
a_str.join()
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()
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()
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()
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()
,
a_str.rfind()
,
a_str.index()
,
a_str.rindex()
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()
,
a_str.rpartition()
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 patterns
Splits 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()
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 patterns
Returns 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 leftmost ones.
If sep
is not specified or is None
,
any whitespace string is a separator.
a_str.isdigit()
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()
,
a_str.ljust()
,
a_str.rjust()
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()
a_str.startswith(prefix)
Code | Output |
---|---|
print 'silly string'.startswith('sil') | True |
print 'silly string'.startswith('ing') | False |
a_str.endswith()
— Checks suffix
Returns whether the string a_str
begins
with the string prefix
.
a_str.endswith()
a_str.endswith(suffix)
Code | Output |
---|---|
print 'silly string'.endswith('sil') | False |
print 'silly string'.endswith('ing') | True |
a_str.startswith()
— Checks prefix
Returns whether the string a_str
ends
with the string suffix
.
a_str.strip()
,
a_str.lstrip()
,
a_str.rstrip()
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
and octal__str__()
on built-in types__repr__()
on built-in typeseval()
intern()
a_str.replace(old, new, count)
a_str.split(sep, maxsplit)
a_str.startswith(prefix)
with a tuple argumenta_str.startswith(prefix, start)
a_str.startswith(prefix, start, end)
a_str.endswith(suffix)
with a tuple argumenta_str.endswith(suffix, start)
a_str.endswith(suffix, start, end)
a_str.decode()
a_str.encode()
a_str.expandtabs()
a_str.format()
a_str.isalnum()
a_str.isalpha()
a_str.islower()
a_str.isspace()
a_str.istitle()
a_str.isupper()
a_str.rsplit()
a_str.splitlines()
a_str.swapcase()
a_str.title()
a_str.translate()
a_str.zfill()
eval()
A list is a mutable sequence of values of any type. A list with zero elements is called an empty list. List elements are indexed by sequential integers, starting with zero.
[…]
[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()
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[]=
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()
range(stop)
range(start, stop)
range(start, stop, step)
Code | Output |
---|---|
print range(5) | [0, 1, 2, 3, 4] |
print range(1, 10) | [1, 2, 3, 4, 5, 6, 7, 8, 9] |
print range(-10, 100, 20) | [-10, 10, 30, 50, 70, 90] |
print 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 lists containing
arithmetic progressions.
The step
cannot be zero, and
it defaults to 1.
The start
defaults to 0.
The full form returns 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
.
It is often used in for
loops, as illustrated
in the last example above. It provides a mechanism for
looping a specific number of iterations.
a_list.append()
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()
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()
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()
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()
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()
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()
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] |
sorted()
— Sort an iterable
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.
(Bug: It reverses when rev_bool
is False
, too.)
If the elements are of different types, then
the ascending or descending ordering is based upon their
hash values.
Need to explain and provide examples for key argument.
The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.
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()
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 can be of any immutable type. Thus, dictionaries are also unordered. When printed, iterated upon, or converted into a sequence, its elements will appear in an arbitrary, implementation-dependent order.
{}
{key0: value0, key1: value1, … }
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()
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[]
,
a_dict.get()
a_dict[key]
a_dict.get(key)
a_dict.get(key, default)
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 |
Returns the value associated with the given key the
dictionary a_dict
.
If the key is not in the dictionary,
a_dict[key]
raises a
KeyError
error.
However, a_dict.get(key)
returns the
default value default
if provided, and
None
otherwise.
a_dict[key] = value
a_dict[key] = value
Code | Output |
---|---|
d = {1: 'a', 2: 'b', 3: 'c'} d[2] = 'd' print d d[5] = 'e' print d | {1: 'a', 2: 'd', 3: 'c'} {1: 'a', 2: 'd', 3: 'c', 5: 'e'} |
Mutates the dictionary a_dict
so that the given key now maps to the given value.
a_dict.has_key()
a_dict.has_key(key)
Code | Output |
---|---|
print {1: 'a', 2: 'b', 3: 'c'}.has_key(2) | True |
print {1: 'a', 2: 'b', 3: 'c'}.has_key(4) | False |
Returns whether the given key is a key in the dictionary
a_dict
. The equivalent
key in a_dict
is considered better style.
a_dict.pop()
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()
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 a list 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()
a_dict.keys()
Code | Output |
---|---|
print {1: 'a', 2: 'b', 3: 'c'}.keys() | [1, 2, 3] |
Returns a list 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()
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 a list 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.
dict()
with keyword argumentsa_dict.clear()
a_dict.copy()
a_dict.iteritems()
a_dict.iterkeys()
a_dict.itervalues()
a_dict.popitem()
a_dict.setdefault()
a_dict.update()
a_set.set
a_set.union
a_set.intersection
a_set.difference
a_set.symmetric_difference
a_set.update
a_set.intersection_update
a_set.difference_update
a_set.symmetric_difference_update
a_set.add
a_set.remove
a_set.discard
a_set.pop
a_set.issubset
a_set.issuperset
a_set.copy
in
not in
len
sum
max
min
zip
sorted
map
filter
reduce
any
all
a_str.join
enumerate
<
<=
>
>=
==
!=
is
is not
type
isinstance
dir
hasattr
str
repr
A set is an unordered collection without duplicates. When printed, iterated upon, or converted into a sequence, its elements will appear in an arbitrary, implementation-dependent order.
set()
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
,
a_set.discard()
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()
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()
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()
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()
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()
def
)" => "more-1b_functions-structure.py",
"More Functions" => "more-1b_functions-examples.py"));
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(): …
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 (): …
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 are defined like
functions. A generator function looks just like
a regular function, except that it uses yield
instead of return
.
def a_genfunc(): … yield …
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.
For good style, each generator function should also have a documentation string (docstring) immediately after its header, as illustrated in the example.
a_gen.send()
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 URLs
This 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 urllib2
.
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
urllib2.urlopen()
.
a_file.read()
a_file.read()
a_file.read(size)
Code | Output |
---|---|
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.read() | This is line one. This is line two. This is line three. |
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.read(7) | This is |
a_file.readline()
— Reads one linea_file.readlines()
— Reads multiple lines
With no argument or a negative size
argument,
this returns a string containing
the rest of the file.
With a non-negative size
argument, this
returns a string 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()
a_file.readline(size)
Code | Output |
---|---|
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.readline() | This is line one. |
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.read(7) print a_file.readline() | This is line one. |
a_file.read()
— Readsa_file.readlines()
— Reads multiple lines
With no argument or a negative size
argument,
this returns a string 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 '\n'
or end of file.
With a non-negative size
argument, this
returns a string 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()
a_file.readlines(sizehint)
Code | Output |
---|---|
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.readlines() | ['This is line one.\n', 'This is line two.\n', 'This is line three.\n'] |
import urllib2 import codeskulptor a_file = urllib2.urlopen(codeskulptor.file2url('assets_sample_text.txt')) print a_file.readline() print a_file.readlines() | This is line one. ['This is line two.\n', 'This is line three.\n'] |
a_file.read()
— Readsa_file.readline()
— Reads one line
Reads 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 strings.
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()
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.
an_iter.next()
an_iter.next()
Code | Output |
---|---|
i = enumerate(['a', 'b', 'c']) print i.next() print i.next() print i.next() | (0, 'a') (1, 'b') (2, 'c') |
def foo(): x = yield 1 print 'Yielded:', x yield 2 bar = foo() print bar.next() print bar.next() | 1 Yielded: None 2 |
Returns the next element of the iterator and removes it from the iterator.
For a generator, it's behavior can be described in more
detail.
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 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()
next()
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[]
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 |
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]
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()
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 methods
Returns 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_itemThis 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()
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
.
in
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 |
Returns True
if value val
is in
the iterable, otherwise returns False
.
not in
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 |
Returns True
if value val
is not in
the iterable, otherwise returns False
.
len()
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()
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()
max(val1, val2, …)
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()
min(val1, val2, …)
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()
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()
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] |
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.
(Bug: It reverses when rev_bool
is False
, too.)
If the elements are of different types, then
the ascending or descending ordering is based upon their
hash values.
Need to explain and provide examples for key argument.
The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.
map()
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[i], &hellip)
.
filter()
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()
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()
<
, <=
,
>
, >=
,
==
, !=
,
is
, is not
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 |
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
is the same value as y
?
x is not y
:
Is x
is not the same value 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 leads to some
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
values are the same object, whereas ==
tests whether they just look alike.
For mutable types, if x is y
, then
mutating x
also mutates y
.
type()
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()
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()
dir(x)
Code | Output |
---|---|
print dir({}) | ['get', 'has_key', 'items', 'keys', 'values'] |
Returns a list of strings naming the attributes
defined on the object x
.
hasattr()
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
.
dir
with no argumentgetattr()
setattr()
callable()
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.
CodeSkulptor 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.ceil()
math.ceil(x)
Code | Output |
---|---|
import math print math.ceil(8) | 8.0 |
import math print math.ceil(8.1) | 9.0 |
import math print math.ceil(-8.1) | -8.0 |
int()
and long()
— Round to zeroround()
— Rounds to nearest integermath.trunc()
— Rounds to zeromath.floor()
— Rounds down
Returns the “ceiling” of x
, i.e.,
the smallest integral value greater than or equal
to x
. Returns it as a floating-point value.
math.floor()
math.floor(x)
Code | Output |
---|---|
import math print math.floor(8) | 8.0 |
import math print math.floor(8.9) | 8.0 |
import math print math.floor(-8.9) | -9.0 |
int()
and long()
— Round to zeroround()
— Rounds to nearest integermath.trunc()
— Rounds to zeromath.ceil()
— Rounds up
Returns the “floor” of x
, i.e., the
largest integral value less than or equal
to x
. Returns it as a floating-point value.
math.trunc()
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()
and long()
— Also round to zeroround()
— Rounds to nearest integermath.ceil()
— Rounds upmath.floor()
— Rounds down
Returns 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()
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 integer
Returns the absolute value of the number x
as
a floating-point value.
math.log()
math.log(x)
math.log(x, base)
Code | Output |
---|---|
import math print math.log(math.e ** 3) | 3 |
import math print math.log(10000, 10) | 4 |
Returns the logarithm of x
to base
base
. If the base is omitted,
returns the natural logarithm, i.e., base
defaults to math.e
.
math.pow()
,
math.exp()
math.pow(x,y)
math.exp(y)
Code | Output |
---|---|
import math print math.pow(2, 3) | 8 |
import math print math.exp(3) | 20.085536923187668 |
**
— Built-in exponentiation operatorpow()
— Built-in exponentiation function
math.pow(x,y)
returns
x
raised to the power y
,
xy.
math.exp(y)
returns
math.e
raised to the power y
,
ey.
math.factorial()
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()
math.sqrt(x)
Code | Output |
---|---|
import math print math.sqrt(16) | 4 |
import math print math.sqrt(-1) | NaN |
Returns the square root of x
.
math.e
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
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()
math.degrees(x)
Code | Output |
---|---|
import math print math.degrees(math.pi) | 180 |
Returns the radians angle measure x
in degrees.
math.radians()
math.radians(x)
Code | Output |
---|---|
import math print math.radians(180) | 3.141592653589793 |
Returns the degrees angle measure x
in radians.
math.hypot()
math.hypot(x, y)
Code | Output |
---|---|
import math print math.hypot(3, 4) | 5 |
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
.
math.sin()
, math.cos()
,
math.tan()
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 versions
Return the sine, cosine, or tangent, respectively,
of x
radians.
math.asin()
,
math.acos()
,
math.atan()
,
math.atan2()
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 versions
Return 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.
math.sinh()
,
math.cosh()
,
math.tanh()
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 versions
Return the hyperbolic sine, cosine, or tangent, respectively,
of x
.
math.asinh()
,
math.acosh()
,
math.atanh()
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 versions
Return the hyperbolic arcsine (asin
),
arccosine (acos
),
or arctangent (atan
),
of x
.
math.copysign()
math.mod()
math.frexp()
math.fsum()
math.isinf()
math.isnan()
math.ldexp()
math.modf()
math.log1p()
This module contains functions that involve randomness.
To use these operations, first import the module with
import random
.
random.choice()
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()
,
random.randrange()
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.random()
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 |
Returns a random floating-point number greater or equal to 0 and less than 1. Each number is equally likely, i.e., the possible numbers are distributed uniformly.
A common usage is to generate a random floating-point
number n in an arbitrary range:
lower <=
n < upper
,
as illustrated in the last example above.
random.shuffle()
random.shuffle(a_list)
Code | Output |
---|---|
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()
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.uniform()
random.triangular()
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()
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(key) 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
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__()
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()
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()
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()
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()
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()
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()
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()
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()
re.search(pattern, string)
re.search(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()
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
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()
, match_obj.groups()
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()
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 URLs
This 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 urllib2
.
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
urllib2.urlopen()
.
urllib2.urlopen()
urllib2.urlopen(url)
Code | Output |
---|---|
import urllib2 import codeskulptor a_file = urllib2.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.
urllib2.urlopen()
with multiple argumentsurllib2.install_opener()
urllib2.build_opener()
CodeSkulptor 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
.
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
,
frame.set_keyup_handler()
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()
,
frame.set_mousedrag_handler()
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()
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()
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()
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()
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()
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()
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_point()
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()
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 def draw_handler(canvas): canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100)) image = simplegui.load_image('http://commondatastorage.googleapis.com/codeskulptor-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 def draw_handler(canvas): canvas.draw_image(image, (1521 // 2, 1818 // 2), (1521, 1818), (40, 70), (100, 100), 2) image = simplegui.load_image('http://commondatastorage.googleapis.com/codeskulptor-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 |
Draw 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()
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()
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()
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()
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()
simplegui.load_image(URL)
Code | Output |
---|---|
import simplegui def draw_handler(canvas): canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100)) image = simplegui.load_image('http://commondatastorage.googleapis.com/codeskulptor-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 |
Loads 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()
image.get_width()
Returns the width of the image in pixels. While the image is still loading, it returns zero.
image.get_height()
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()
simplegui.load_sound(URL)
Code | Output |
---|---|
import simplegui sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg') sound.set_volume(0.7) |
sound.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()
sound.play()
Code | Output |
---|---|
import simplegui sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg') sound.play() | # plays a sound |
Starts playing a sound, or restarts playing it at the point it was paused.
sound.pause()
sound.pause()
Code | Output |
---|---|
import simplegui sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg') sound.play() sound.pause() | # starts to play a sound, then immediate pauses |
Stops the playing of the sound. Playing can be restarted
at the stopped point with
sound.play()
.
sound.rewind()
sound.rewind()
Code | Output |
---|---|
import simplegui sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg') sound.play() sound.rewind() sound.play() |
Stops the playing of the sound, and makes it so the next
sound.play()
will start playing the sound at the beginning.
sound.set_volume()
sound.set_volume(volume)
Code | Output |
---|---|
import simplegui sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg') sound.set_volume(0.7) |
Changes 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[]
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()
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()
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()
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()
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.
a_map.get_lines()
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()
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()
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()
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()
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_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()
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()
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()
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()
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()
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()
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()
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()
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()
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) 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()
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()
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()
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()
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
.
CodeSkulptor 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 smaller module than the common NumPy module.
To use these operations, first import the module with
import numeric
.
numeric.Matrix()
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()
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[]
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()
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()
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[]=
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]] |
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.scale()
a_matrix.scale(factor)
Code | Output |
---|---|
import numeric matrix = numeric.Matrix([[3, 4, 5], [6, 7, 8]]) print matrix.scale(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()
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()
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()
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()
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()
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()
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.set_timeout()
codeskulptor.set_timeout(seconds)
Code | Output |
---|---|
import codeskulptor codeskulptor.set_timeout(100) |
CodeSkulptor imposes a timeout on all programs, so that long-running programs don't freeze the browser. By default, the time limit is 5 seconds, but this allows you to change that limit to the given number of seconds.
codeskulptor.file2url()
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 is a browser-based programming environment for the programming language Python. CodeSkulptor runs in Google Chrome 18+, Mozilla Firefox 11+, and Apple Safari 6+. 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.
In the upper left is the control area which consists of buttons for the main CodeSkulptor features: Run, Save, Download, Fresh URL, Open Local, and Reset.
In the upper right are links to useful resources: the documentation you are currently reading, example Python programs that illustrate Python and CodeSkulptor features, and a popular massive open online course (MOOC) for which CodeSkulptor was originally created.
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.
To ensure that programs do not run forever and lock-up your browser, CodeSkulptor has a time-out feature that stops any program that runs for too long.
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.
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.
On each save the URL for your program increases in version number. This button creates a new URL independent of the previous one.
Loads a Python file from your own computer into the CodeSkulptor editor.
Clears the CodeSkulptor console and closes any pop-up windows created by CodeSkulptor.
(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 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 |
CodeSkulptor was created in 2012 as a tool for teaching Python programming, especially to beginners. A driving goal is to be very easy to use. Some of its main advantages for teaching are
It was initially created for an online course, “An Introduction to Interactive Programming in Python”, by Joe Warren, Scott Rixner, John Greiner, and Stephen Wong. It is also used in Computer Science courses at Rice University.
Scott Rixner continues to develop CodeSkulptor, while John Greiner develops CodeSkulptor's documentation.
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.