Documentation

CodeSkulptor

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.

Types

Types:

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.

Values & Objects

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.

Expressions

CodeSkulptor supports all forms of Python expressions, except dictionary and set comprehensions.

Examples:

See the other sections of this documentation for details on which types, operations, functions, and methods are supported.

Simple Statements

Simple Statements:
Examples:

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

Compound Statements:
Examples:

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.)

Python Code Style

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”).

Null Object

Operations:
Superclass:

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().

Integers & Floating-Point Numbers

Operations:
Superclass:
Tutorial:
Examples:
See also:
Math Module — Library of numeric operations

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.

Integer & Floating-point Constants

Examples:
CodeOutput
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:

  • Base ten (decimal — what people are most used to): consists of a sequence of digits, not starting with 0
  • Base two (binary): consists of 0b followed by 0's and 1's
  • Base eight (octal): consists of a 0 followed by digits in the range 0 to 7
  • Base sixteen (hexadecimal): consists of 0x followed by digits in the range 0 to 7 or letters in the range A to F (in upper or lower case)

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.

Convert Number, String, or Boolean into Numberint(), long(), float()

Syntax:
int(x)
long(x)
float(x)
Examples:
CodeOutput
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
See also:
round() — Rounds to nearest integer
math.trunc() — Rounds to zero (same int() and long() on integers)
math.ceil() — Rounds up
math.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.

Addition+

Syntax:
a + b
Example:
CodeOutput
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.

Subtraction & Negation-

Syntax:
a - b
- a
Examples:
CodeOutput
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.

Multiplication*

Syntax:
a * b
Example:
CodeOutput
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.

Division/, //

Syntax:
a / b
a // b
Examples:
CodeOutput
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
Example:

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.

Remainder (Modulo)%

Syntax:
x % m
Example:
CodeOutput
print 11 % 3
2
Example:

Returns the remainder of x // m.

Modulo and assignment can be combined with the shorthand x %= m, which is equivalent to x = x % m.

Exponentiation, xy**

Syntax:
x ** y
Example:
CodeOutput
print 3 ** 4
81
See also:
pow() — Built-in exponentiation function
math.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.

Exponentiation Remainderpow()

Syntax:
pow(x, y)
pow(x, y, m)
Examples:
CodeOutput
print pow(3, 4)
81
print pow(3, 4, 2)
1
See also:
** — Built-in exponentiation operator
math.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.

Absolute Value, |x|abs()

Syntax:
abs(x)
Examples:
CodeOutput
print abs(3)
3
print abs(-3.0)
3.0
See also:
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 to Nearestround()

Syntax:
round(n)
round(n, i)
Examples:
CodeOutput
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
See also:
int() and long() — Round to zero
math.trunc() — Rounds to zero
math.ceil() — Rounds up
math.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.

Base Conversionbin(), oct(), hex()

Syntax:
bin(x)
oct(x)
hex(x)
Examples:
CodeOutput
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.

ASCII Characterchr()

Syntax:
chr(i)
Example:
CodeOutput
print chr(97)
a

Returns a string of one character whose ASCII code is the integer i. This is the inverse of ord().

Character Codeord()

Syntax:
ord(x)
Example:
CodeOutput
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.

Bitwise Operations~, &, |, ^, <<, >>

Syntax:
~x
x & y
x | y
x ^ y
x << n
x >> n
Examples:
CodeOutput
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

Operations:
Superclass:
Examples:

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.

Boolean/Logical Constants

Syntax:
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.

Convert Value into Booleanbool

Syntax:
bool(x)
Examples:
CodeOutput
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.

Logical Conjunctionand

Syntax:
x and y
Examples:
CodeOutput
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

Logical Disjunctionor

Syntax:
x or y
Examples:
CodeOutput
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.

Logical Negationnot

Syntax:
not x
Examples:
CodeOutput
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

Is Any Iterable Element True?any

Syntax:
any(an_iter)
Examples:
CodeOutput
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.

Are All Iterable Elements True?all

Syntax:
all(an_iter)
Examples:
CodeOutput
print all([False, True, False])
False
print all([True, True, True])
True
print all([])
True
print all((0, 3))
False
print all('abc')
True

Returns whether bool(x) is True (or true-like) for all elements x in the iterable.

Strings

Operations:
Superclasses:
Tutorial:
Examples:

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.

String Constants"…", '…', """…""", '''…''', r"…", r'…', r"""…""", r'''…'''

Syntax:
"…"
'…'
"""…"""
'''…'''
r"…"
r'…'
r"""…"""
r'''…'''
Examples:
CodeOutput
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
\bbackspace character
\fformfeed character
\nnew line character (starts a new line)
\rcarriage return character
\thorizontal tab character (moves to next tab position, which is every eight characters)
\vvertical tab character
\xNNASCII 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.

Convert Value into Stringstr()

Syntax:
str(x)
Examples:
CodeOutput
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
See also:
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.

Unambiguous Printable Representation of Objectrepr()

Syntax:
repr(an_obj)
Examples:
CodeOutput
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
See also:
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.

Format String%

Syntax:
a_str % value
a_str % a_tuple
a_str % a_dict
Documentation:

Concatenate Iterable Sequences into Stringsa_str.join()

Syntax:
a_str.join([iterable])
Examples:
CodeOutput
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.

Capitalize Stringa_str.capitalize()

Syntax:
a_str.capitalize()
Example:
CodeOutput
print 'peAr'.capitalize()
Pear

Return a copy of the string a_str with its first character capitalized and the rest lower-cased.

Change Case of Stringa_str.upper(), a_str.lower()

Syntax:
a_str.upper()
a_str.lower()
Examples:
CodeOutput
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

Replace Substringa_str.replace()

Syntax:
a_str.replace(old, new)
a_str.replace(old, new, maxreplace)
Examples:
CodeOutput
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.

Find Substringa_str.find(), a_str.rfind(), a_str.index(), a_str.rindex()

Syntax:
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)
Examples:
CodeOutput
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.

Split String at One Delimetera_str.partition(), a_str.rpartition()

Syntax:
a_str.partition(sep)
a_str.rpartition(sep)
Examples:
CodeOutput
print 'a b c'.partition(' ')
('a', ' ', 'b c')
print 'a b c'.rpartition(' ')
('a b', ' ', 'c')
See also:
a_str.split() — Splits multiple times
re.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.

Split String at Multiple Delimetersa_str.split()

Syntax:
a_str.split()
a_str.split(sep)
a_str.split(sep, maxsplit)
Examples:
CodeOutput
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']
See also:
a_str.partition(), etc. — Splits only once
re.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.

Test String for Digitsa_str.isdigit()

Syntax:
a_str.isdigit()
Examples:
CodeOutput
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.

Align Stringa_str.center(), a_str.ljust(), a_str.rjust()

Syntax:
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)
Examples:
CodeOutput
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.

Check Prefixa_str.startswith()

Syntax:
a_str.startswith(prefix)
Examples:
CodeOutput
print 'silly string'.startswith('sil')
True
print 'silly string'.startswith('ing')
False
See also:
a_str.endswith() — Checks suffix

Returns whether the string a_str begins with the string prefix.

Check Suffixa_str.endswith()

Syntax:
a_str.endswith(suffix)
Examples:
CodeOutput
print 'silly string'.endswith('sil')
False
print 'silly string'.endswith('ing')
True
See also:
a_str.startswith() — Checks prefix

Returns whether the string a_str ends with the string suffix.

Remove Leading and Trailing Charactersa_str.strip(), a_str.lstrip(), a_str.rstrip()

Syntax:
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)
Examples:
CodeOutput
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.

Unsupported String Operations and Constants

  • Escape sequences \a and octal
  • __str__() on built-in types
  • __repr__() on built-in types
  • eval()
  • intern()
  • a_str.replace(old, new, count)
  • a_str.split(sep, maxsplit)
  • a_str.startswith(prefix) with a tuple argument
  • a_str.startswith(prefix, start)
  • a_str.startswith(prefix, start, end)
  • a_str.endswith(suffix) with a tuple argument
  • a_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()

Lists

Operations:
Superclasses:
Tutorials:
Examples:
See also:
Tuples — Immutable sequences
Dictionaries — More flexible indexing

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.

List Constants[…]

Syntax:
[val0, val1, …]
Examples:
CodeOutput
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.

Convert Iterable or Iterator into Listlist()

Syntax:
list()
list(an_iter)
Examples:
CodeOutput
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.

Set Value at Specific Position in Lista_list[]=

Syntax:
a_list[index] = value
Example:
CodeOutput
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.

Arithmetic Progressions Listrange()

Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
Examples:
CodeOutput
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.

Add Item to End of Lista_list.append()

Syntax:
a_list.append(x)
Examples:
CodeOutput
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.

Add Multiple Items to End of Lista_list.extend()

Syntax:
a_list.extend(an_iter)
Examples:
CodeOutput
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.

Insert Item into Lista_list.insert()

Syntax:
a_list.insert(i, x)
Example:
CodeOutput
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).

Remove Item from List by Valuea_list.remove()

Syntax:
a_list.remove(x)
Example:
CodeOutput
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.

Remove Item from List by Positiona_list.pop()

Syntax:
a_list.pop([index])
Example:
CodeOutput
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.

Reverse Items in Lista_list.reverse()

Syntax:
a_list.reverse()
Example:
CodeOutput
a_list = [1, 2, 3]
a_list.reverse()
print a_list
[3, 2, 1]

Reverses the elements of the list a_list in place.

Sort Items in List in Placea_list.sort()

Syntax:
a_list.sort()
a_list.sort(reverse=rev_bool, key=key_fn)
Examples:
CodeOutput
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]
See also:
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.

Tuples

Operations:
Superclasses:
Tutorial:
Example:
See also:
Lists — Mutable sequences
Strings — Specialized to only containing text

A tuple is an immutable sequence of values of any type. Tuple elements are indexed by sequential integers, starting with zero.

Tuple Constants(…)

Syntax:
(val0, val1, …)
Examples:
CodeOutput
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.

Convert Iterable into Tupletuple()

Syntax:
tuple()
tuple(an_iter)
Examples:
CodeOutput
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.

Unsupported Tuple Operation

  • coerce()

Dictionaries

Operations:
Subclasses:
Superclasses:
Tutorial:
Examples:
See also:
Lists — Specialized to keys 0, 1, …
Sets — Essentially dictionaries specialized to Boolean values

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.

Dictionary Constants{}

Syntax:
{key0: value0, key1: value1, … }
Examples:
CodeOutput
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.

Convert Iterable of Pairs into Dictionarydict()

Syntax:
dict()
dict(an_iter)
Examples:
CodeOutput
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.

Get Value in Dictionary by Keya_dict[], a_dict.get()

Syntax:
a_dict[key]
a_dict.get(key)
a_dict.get(key, default)
Examples:
CodeOutput
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.

Set Value for Key in Dictionarya_dict[key] = value

Syntax:
a_dict[key] = value
Example:
CodeOutput
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.

Check if Key is in Dictionarya_dict.has_key()

Syntax:
a_dict.has_key(key)
Examples:
CodeOutput
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.

Remove Key from Dictionary and Return its Valuea_dict.pop()

Syntax:
a_dict.pop(key)
a_dict.pop(key, default)
Examples:
CodeOutput
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.

Get List of all Key/Value Pairs in Dictionarya_dict.items()

Syntax:
a_dict.items()
Examples:
CodeOutput
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.

Get List of all Keys in Dictionarya_dict.keys()

Syntax:
a_dict.keys()
Example:
CodeOutput
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.

Get List of all Values in Dictionarya_dict.values()

Syntax:
a_dict.values()
Examples:
CodeOutput
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.

Unsupported Dictionary Operations

  • dict() with keyword arguments
  • a_dict.clear()
  • a_dict.copy()
  • a_dict.iteritems()
  • a_dict.iterkeys()
  • a_dict.itervalues()
  • a_dict.popitem()
  • a_dict.setdefault()
  • a_dict.update()

Sets

Operations:
Superclasses:
Tutorial:

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.

Convert Iterable into Setset()

Syntax:
set()
set(an_iter)
Examples:
CodeOutput
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.

Set Uniona_set.union()

Syntax:
a_set.union(an_iter)
Example:
CodeOutput
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.

Set Intersectiona_set.intersection()

Syntax:
a_set.intersection(an_iter)
Example:
CodeOutput
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.

Set Differencea_set.difference()

Syntax:
a_set.difference(an_iter)
Example:
CodeOutput
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.

Set Symmetric Differencea_set.symmetric_difference()

Syntax:
a_set.symmetric_difference(anInter)
Example:
CodeOutput
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.

Set Union with Mutationa_set.update()

Syntax:
a_set.update(an_iter)
Example:
CodeOutput
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.

Set Intersection with Mutationa_set.intersection_update()

Syntax:
a_set.intersection_update(an_iter)
Example:
CodeOutput
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.

Set Difference with Mutationa_set.difference_update()

Syntax:
a_set.difference_update(an_iter)
Example:
CodeOutput
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.

Set Symmetric Difference with Mutationa_set.symmetric_difference_update()

Syntax:
a_set.symmetric_difference_update(an_iter)
Example:
CodeOutput
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.

Add Element into Seta_set.add()

Syntax:
a_set.add(x)
Example:
CodeOutput
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.

Remove Specified Element from Seta_set.remove(), a_set.discard()

Syntax:
a_set.remove(x)
a_set.discard(x)
Example:
CodeOutput
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.

Remove Arbitrary Element from Seta_set.pop()

Syntax:
a_set.pop()
Example:
CodeOutput
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.

Test for Subseta_set.issubset()

Syntax:
a_set.issubset(an_iter)
Examples:
CodeOutput
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.

Test for Superseta_set.issuperset()

Syntax:
a_set.issuperset(an_iter)
Examples:
CodeOutput
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.

Copy Seta_set.copy()

Syntax:
a_set.copy()
Example:
CodeOutput
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.

Unsupported Set Operations

  • |
  • &
  • -
  • ^
  • |=
  • &=
  • -=
  • ^=
  • s.clear()

Functions & Methods

Operations:
Superclass:
emitAddExamples(array( "Function Structure (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.)

Named Functionsdef a_func(): …

Syntax:
def a_func(var0, var1, …): …
Examples:
CodeOutput
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]
Tutorial:

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.

Anonymous Functionslambda (): …

Syntax:
lambda var1, var2, …: expr
Examples:
CodeOutput
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]
Tutorial:

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.

Unsupported Function and Method Operations

  • Built-in functions and methods are not values.
  • Keyword arguments are not supported.
  • 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

Operations:
Superclasses:

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.

Generator Functionsdef a_genfunc(): … yield …

Syntax:
def a_genfunc(var0, var1, …): … yield … …
Example:
CodeOutput
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.

Get Next Element and Send Value to Generatora_gen.send()

Syntax:
a_gen.send(val)
Examples:
CodeOutput
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.

Unsupported Generator Operations

  • a_gen.throw()
  • a_gen.close()

File Objects

Operations:
Superclasses:
See also:
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().

Read from Filea_file.read()

Syntax:
a_file.read()
a_file.read(size)
Examples:
CodeOutput
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
See also:
a_file.readline() — Reads one line
a_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.

Read One Line from Filea_file.readline()

Syntax:
a_file.readline()
a_file.readline(size)
Examples:
CodeOutput
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.
See also:
a_file.read() — Reads
a_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.

Read Multiple Lines from Filea_file.readlines()

Syntax:
a_file.readlines()
a_file.readlines(sizehint)
Examples:
CodeOutput
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']
See also:
a_file.read() — Reads
a_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.

Unsupported File Object Operations

  • list() on file objects
  • a_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

Enumerations

Operations:
Superclasses:

Create an Enumerationenumerate()

Syntax:
enumerate(an_iter)
enumerate(an_iter, start)
Examples:
CodeOutput
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.

IteratorsIncludes: Generator Functions, Enumerations, File Objects

Operations:
Subclasses:
Superclasses:

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.

Get Next Element of Iteratoran_iter.next()

Syntax:
an_iter.next()
Examples:
CodeOutput
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.

Unsupported Iterator Operations

  • an_iter.next() incorrectly does not raise an error if the iterator is empty.
  • an_iter.__iter__()
  • iter()
  • next()

SequencesIncludes: Strings, Lists, Tuples

Operations:
Subclasses:
Superclasses:

Sequences are ordered collections of data. Their elements can be indexed by integers indicating positions.

Concatenation of Sequences+

Syntax:
seq1 + seq2
Examples:
CodeOutput
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.

Concatenation of Copies of one Sequence*

Syntax:
a_seq * n
n * a_seq
Examples:
CodeOutput
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.

Get Sequence Value at Specified Indexa_seq[]

Syntax:
a_seq[i]
a_seq.__getitem__(i)
Examples:
CodeOutput
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.

Select Part of Sequence by Indexing (“Slicing”)a_seq[i:j], a_seq[i:j:k]

Syntax:
a_seq[i:j]
a_seq[i:j:k]
Examples:
CodeOutput
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.

Find Item in Sequencea_seq.index()

Syntax:
a_seq.index(val)
a_seq.index(val, start)
a_seq.index(val, start, end)
Examples:
CodeOutput
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
See also:
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_item
This doesn't accomplish the intended goal when the list contains duplicates, since my_list.index(item) finds the first instance of item.

Count Occurences of Item in Sequencea_seq.count()

Syntax:
a_seq.count(val)
a_str.count(val, start)
a_str.count(val, start, end)
Examples:
CodeOutput
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.

IterablesIncludes: Iterators, Sequences, Dictionaries, Sets

Operations:
Subclasses:
Superclass:

Iterables are collections of data that allow iteration or looping — e.g., for x in an_iter.

Test if Item is in Iterablein

Syntax:
val in an_iter
Examples:
CodeOutput
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.

Test if Item is not in Iterablenot in

Syntax:
val not in an_iter
Examples:
CodeOutput
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.

Length of Iterablelen()

Syntax:
len(an_iter)
Examples:
CodeOutput
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 of Elements in Iterablesum()

Syntax:
sum(an_iter)
sum(an_iter, start)
Examples:
CodeOutput
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.

Maximum Value Among Multiple Inputs or in Iterablemax()

Syntax:
max(val1, val2, …)
max(an_iter)
Examples:
CodeOutput
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.

Minimum Value Among Multiple Inputs or in Iterablemin()

Syntax:
min(val1, val2, …)
min(an_iter)
Examples:
CodeOutput
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.

Combining ith Elements of Iterables into Tupleszip()

Syntax:
zip(iter1, iter2, …)
Examples:
CodeOutput
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.

Sort Iterable's Elements into a Listsorted()

Syntax:
sorted(an_iter)
sorted(an_iter, reverse=rev_bool, key=key_fn)
Examples:
CodeOutput
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]
See also:
a_list.sort() — Sort a list in-place

Returns 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.

Apply Function to Iterable Elementsmap()

Syntax:
map(function, an_iter)
Example:
CodeOutput
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 Iterable's Elements into a Sequencefilter()

Syntax:
filter(function, an_iter)
Examples:
CodeOutput
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.

Combine Iterable's Elements by Applying a Functionreduce()

Syntax:
reduce(function, an_iter)
reduce(function, an_iter, initializer)
Examples:
CodeOutput
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)

Unsupported Iterable Operations

  • max() and min() with key argument.
  • map(), filter(), and reduce() on built-in functions.
  • __iter__()
  • iter()

ObjectsIncludes: All types

Operations:
Subclasses:

Comparison Operators<, <=, >, >=, ==, !=, is, is not

Syntax:
x < y
x <= y
x > y
x >= y
x == y
x != y
x is y
x is not y
Examples:
CodeOutput
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
Examples:
  • 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.

Get Value's Typetype()

Syntax:
type(x)
Examples:
CodeOutput
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.

Check Value's Typeisinstance()

Syntax:
isinstance(x, y)
Examples:
CodeOutput
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.

Get Object's Attribute's Namesdir()

Syntax:
dir(x)
Example:
CodeOutput
print dir({})
['get', 'has_key', 'items', 'keys', 'values']

Returns a list of strings naming the attributes defined on the object x.

Check if Object has Attributehasattr()

Syntax:
hasattr(an_obj, attr_name)
Examples:
CodeOutput
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.

Unsupported Object Operations

  • dir with no argument
  • getattr()
  • 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.

Math Module

Operations:
Example:

This module contains additional mathematical operations. To use these operations, first import the module with import math.

Round Up, ⌈xmath.ceil()

Syntax:
math.ceil(x)
Examples:
CodeOutput
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
See also:
int() and long() — Round to zero
round() — Rounds to nearest integer
math.trunc() — Rounds to zero
math.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.

Round Down, ⌊xmath.floor()

Syntax:
math.floor(x)
Examples:
CodeOutput
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
See also:
int() and long() — Round to zero
round() — Rounds to nearest integer
math.trunc() — Rounds to zero
math.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.

Truncatemath.trunc()

Syntax:
math.trunc(x)
Examples:
CodeOutput
import math

print math.trunc(8)
8
import math

print math.trunc(8.9)
8
import math

print math.trunc(-8.9)
-8
See also:
int() and long() — Also round to zero
round() — Rounds to nearest integer
math.ceil() — Rounds up
math.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().

Absolute Value, |x|math.fabs()

Syntax:
math.fabs(x)
Examples:
CodeOutput
import math

print math.fabs(3.1)
3.1
import math

print math.fabs(-3)
3.0
See also:
abs() — Returns an integer when given an integer

Returns the absolute value of the number x as a floating-point value.

Logarithm, logbxmath.log()

Syntax:
math.log(x)
math.log(x, base)
Examples:
CodeOutput
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.

Exponentiation, xymath.pow(), math.exp()

Syntax:
math.pow(x,y)
math.exp(y)
Examples:
CodeOutput
import math

print math.pow(2, 3)
8
import math

print math.exp(3)
20.085536923187668
See also:
** — Built-in exponentiation operator
pow() — 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.

Factorial, x!math.factorial()

Syntax:
math.factorial(x)
Examples:
CodeOutput
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.

Square Root, √xmath.sqrt()

Syntax:
math.sqrt(x)
Examples:
CodeOutput
import math

print math.sqrt(16)
4
import math

print math.sqrt(-1)
NaN

Returns the square root of x.

Base of Natural Logarithm, emath.e

Syntax:
math.e
Example:
CodeOutput
import math

print math.e
2.718281828459045

The mathematical constant known as e, the base of the natural logarithm.

π (Pi)math.pi

Syntax:
math.pi
Example:
CodeOutput
import math

print math.pi
3.141592653589793

The mathematical constant known as π, the ratio between the circumference of a circle and its diameter.

Convert Radians to Degreesmath.degrees()

Syntax:
math.degrees(x)
Example:
CodeOutput
import math

print math.degrees(math.pi)
180

Returns the radians angle measure x in degrees.

Convert Degrees to Radiansmath.radians()

Syntax:
math.radians(x)
Example:
CodeOutput
import math

print math.radians(180)
3.141592653589793

Returns the degrees angle measure x in radians.

Two-dimensional distance to originmath.hypot()

Syntax:
math.hypot(x, y)
Example:
CodeOutput
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:

  • the distance from the origin to a point (x, y),
  • the length of a vector between the origin and a point (x, y),
  • the length of the hypotenuse of a right triangle with sides of length x and y.

Trigonometric Functionsmath.sin(), math.cos(), math.tan()

Syntax:
math.sin(x)
math.cos(x)
math.tan(x)
Examples:
CodeOutput
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
See also:
math.asin(), math.acos(), math.atan(), math.atan2() — Inverses
math.sinh(), math.cosh(), math.tanh() — Hyperbolic versions

Return the sine, cosine, or tangent, respectively, of x radians.

Inverse Trigonometric Functionsmath.asin(), math.acos(), math.atan(), math.atan2()

Syntax:
math.asin(x)
math.acos(x)
math.atan(x)
math.atan2(y, x)
Examples:
CodeOutput
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
See also:
math.sin(), math.cos(), math.tan() — Inverses
math.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.

Hyperbolic Functionsmath.sinh(), math.cosh(), math.tanh()

Syntax:
math.sinh(x)
math.cosh(x)
math.tanh(x)
Examples:
CodeOutput
import math

print math.sinh(1)
1.17520119364
import math

print math.cosh(1)
1.54308063482
import math

print math.tanh(1)
0.761594155956
See also:
math.asinh(), math.acosh(), math.atanh() — Inverses
math.sin(), math.cos(), math.tan() — Non-hyperbolic versions

Return the hyperbolic sine, cosine, or tangent, respectively, of x.

Inverse Hyperbolic Functionsmath.asinh(), math.acosh(), math.atanh()

Syntax:
math.asinh(x)
math.acosh(x)
math.atanh(x)
Examples:
CodeOutput
import math

print math.asinh(-1)
-0.88137358702
import math

print math.acosh(1)
0.0
import math

print math.atanh(0)
0.0
See also:
math.asinh(), math.acosh(), math.atanh() — Inverses
math.asin(), math.acos(), math.atan(), math.atan2() — Non-hyperbolic versions

Return the hyperbolic arcsine (asin), arccosine (acos), or arctangent (atan), of x.

Unsupported Math Module Operations

  • math.copysign()
  • math.mod()
  • math.frexp()
  • math.fsum()
  • math.isinf()
  • math.isnan()
  • math.ldexp()
  • math.modf()
  • math.log1p()

Random Module

Operations:
Example:

This module contains functions that involve randomness. To use these operations, first import the module with import random.

Random Element of Sequencerandom.choice()

Syntax:
random.choice(a_seq)
Example:
CodeOutput
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 Integerrandom.randint(), random.randrange()

Syntax:
random.randint(start, stop)
random.randrange(stop)
random.randrange(start, stop)
random.randrange(start, stop, step)
Examples:
CodeOutput
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
See also:
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 Floating-Point Numberrandom.random()

Syntax:
random.random()
Examples:
CodeOutput
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.

Permute Listrandom.shuffle()

Syntax:
random.shuffle(a_list)
Example:
CodeOutput
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.

Seed the Random Number Generatorrandom.seed()

Syntax:
random.seed()
random.seed(x)
Example:
CodeOutput
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.

Unsupported Random Module Operations

  • 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()

Collections Module — Default Dictionaries

Operations:
Superclasses:

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.

Create a Dictionary with Default Valuescollections.defaultdict()

Syntax:
collections.defaultdict()
collections.defaultdict(default_fun)
collections.defaultdict(default_fun, an_iter)
Examples:
CodeOutput
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']
See also:
Dictionaries — No default values
Counters — Specialized to integer values

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.

Default Value Functiona_defdict.default_factory

Syntax:
a_defdict.default_factory
Example:
CodeOutput
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.

Unsupported Default Dictionary Operations

  • Assigning to a_defdict.default_factory.
  • a_defdict.__missing__()

Collections Module — Counters

Operations:
Superclasses:

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.

Create a Countercollections.Counter()

Syntax:
collections.Counter()
collections.Counter(an_iter)
Examples:
CodeOutput
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
See also:
Dictionaries — Counters support almost all dictionary operations.
Default dictionaries — Counters are specialized to integral values.

Returns a new Counter, possibly initialized with counts provided in the iterable an_iter.

Create Iterator of Counter Elementsa_counter.elements()

Syntax:
a_counter.elements()
Example:
CodeOutput
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.

List of Most Common Elements in Countera_counter.most_common()

Syntax:
a_counter.most_common()
a_counter.most_common(n)
Examples:
CodeOutput
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.

Subtract Counts from Countera_counter.subtract()

Syntax:
a_counter.subtract(an_iter)
Example:
CodeOutput
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.

Add Counts to Countera_counter.update()

Syntax:
a_counter.update(an_iter)
Example:
CodeOutput
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.

Regular Expression Module

Operations:
Documentation:

This module allows use of regular expressions, also known as regexps. To use these operations, first import the module with import re.

Regular Expressions

Most of the Python regular expression syntax is supported.

Find All Occurrences of a Patternre.findall()

Syntax:
re.findall(pattern, string)
re.findall(pattern, string, flags = val)
Examples:
CodeOutput
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.

Syntax:
re.search(pattern, string)
re.search(pattern, string, flags = val)
Examples:
CodeOutput
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.

Find First Occurrence of a Pattern at Beginningre.match()

Syntax:
re.search(pattern, string)
re.search(pattern, string, flags = val)
Examples:
CodeOutput
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.

Split on All Occurrences of a Patternre.split()

Syntax:
re.split(pattern, string)
re.split(pattern, string, maxsplit = val)
re.split(pattern, string, maxsplit = val, flags = val)
Examples:
CodeOutput
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.

Flag to Ignore Casere.I, re.IGNORECASE

Syntax:
re.I
re.IGNORECASE

Flag to indicate that regular expression pattern matching should be case-insensitive. By default, matching is case sensitive.

Groups of Matchmatch_obj.group(), match_obj.groups()

Syntax:
match_obj.group(a_num)
match_obj.groups(a_num)
Documentation:

Unsupported Regular Expression Module Operations

  • 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

Time Module

Operation:

This module includes operations that measure the passage of time. To use these operations, first import the module with import time.

Get Current Timetime.time()

Syntax:
time.time()
Examples:
CodeOutput
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.

Unsupported Time Module Operations

  • 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()

Urllib2 Module

Operation:
See also:
File Objects — Operations on opened files
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().

Open File at URLurllib2.urlopen()

Syntax:
urllib2.urlopen(url)
Example:
CodeOutput
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.

Unsupported Urllib2 Module Operations

  • urllib2.urlopen() with multiple arguments
  • urllib2.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.

SimpleGUI Module — Frame

Operations:
Superclass:
Examples:

A frame is a window, which is a container for the controls, status information, and canvas. A program can create only one frame.

Create Framesimplegui.create_frame()

Syntax:
simplegui.create_frame(title, canvas_width, canvas_height)
simplegui.create_frame(title, canvas_width, canvas_height, control_width)
Examples:
CodeOutput
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.

Set Canvas' Background Colorframe.set_canvas_background()

Syntax:
frame.set_canvas_background(color)
Example:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_canvas_background('Red')
frame.start()
# Opens frame with a red background
See also:
Colors — Supported colors

Changes the background color of the frame's canvas, which defaults to black.

Start Frame's Interactivityframe.start()

Syntax:
frame.start()
Example:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
frame.start()
# Opens frame

Starts all frame event handlers — drawing and controls.

Get Canvas Text's Widthframe.get_canvas_textwidth()

Syntax:
frame.get_canvas_textwidth(text, size)
frame.get_canvas_textwidth(text, size, face)
Examples:
CodeOutput
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".

SimpleGUI Module — Control Objects

Operations:
Superclass:

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.

Add Text Label to Frame Control Panelframe.add_label()

Syntax:
frame.add_label(text)
frame.add_label(text, width)
Example:
CodeOutput
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
See also:
control.get_text() — Gets the current label text
control.set_text() — Sets the current label text

Adds 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.

Add Button to Frame Control Panelframe.add_button()

Syntax:
frame.add_button(text, button_handler)
frame.add_button(text, button_handler, width)
Example:
CodeOutput
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
Examples:
See also:
control.get_text() — Gets the current label text
control.set_text() — Sets the current label text

Adds 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.

Add Text Input Box to Frame Control Panelframe.add_input()

Syntax:
frame.add_input(text, input_handler, width)
Example:
CodeOutput
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
Examples:
See also:
control.get_text() — Gets the current input text
control.set_text() — Sets the current input text, e.g., to specify a default value

Adds 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.

Get the Text of Control Objectcontrol.get_text()

Syntax:
control.get_text()
Examples:
CodeOutput
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()
See also:
control.set_text() — Sets the text

Returns 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.

Set the Text of Control Objectcontrol.set_text()

Syntax:
control.set_text(text)
Examples:
CodeOutput
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
See also:
control.get_text() — Gets the text

Changes 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.

Set the Keyboard Input Handlerframe.set_keydown_handler(), frame.set_keyup_handler()

Syntax:
frame.set_keydown_handler(key_handler)
frame.set_keyup_handler(key_handler)
Example:
CodeOutput
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
Examples:

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.

Set the Mouse Input Handlerframe.set_mouseclick_handler(), frame.set_mousedrag_handler()

Syntax:
frame.set_mouseclick_handler(mouse_handler)
frame.set_mousedrag_handler(mouse_handler)
Example:
CodeOutput
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
Examples:

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.

SimpleGUI Module — Canvas

Operations:
Superclass:
Examples:

The canvas is where you can draw text and shapes.

Set the Draw Handler on Canvasframe.set_draw_handler()

Syntax:
frame.set_draw_handler(draw_handler)
Example:
CodeOutput
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.

Draw Text on Canvascanvas.draw_text()

Syntax:
canvas.draw_text(text, point, font_size, font_color)
canvas.draw_text(text, point, font_size, font_color, font_face)
Example:
CodeOutput
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
See also:
Colors — Supported colors

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.

Draw Line Segment on Canvascanvas.draw_line()

Syntax:
canvas.draw_line(point1, point2, line_width, line_color)
Example:
CodeOutput
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
Example:
See also:
Colors — Supported colors

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.

Draw Connected Line Segments on Canvascanvas.draw_polyline()

Syntax:
canvas.draw_polyline(point_list, line_width, line_color)
Example:
CodeOutput
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
See also:
Colors — Supported colors

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.

Draw Polygon on Canvascanvas.draw_polygon()

Syntax:
canvas.draw_polygon(point_list, line_width, line_color)
canvas.draw_polygon(point_list, line_width, line_color, fill_color = color)
Example:
CodeOutput
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
See also:
Colors — Supported colors

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.

Draw Circle on Canvascanvas.draw_circle()

Syntax:
canvas.draw_circle(center_point, radius, line_width, line_color)
canvas.draw_circle(center_point, radius, line_width, line_color, fill_color = color)
Example:
CodeOutput
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
See also:
Colors — Supported colors

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.

Draw Point on Canvascanvas.draw_point()

Syntax:
canvas.draw_point(point, color)
Example:
CodeOutput
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
See also:
Colors — Supported colors

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.

Draw Image on Canvascanvas.draw_image()

Syntax:
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)
Examples:
CodeOutput
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.

SimpleGUI Module — Timers

Operations:
Superclass:
Examples:

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.

Create Timersimplegui.create_timer()

Syntax:
simplegui.create_timer(interval, timer_handler)
Example:
CodeOutput
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.

Start Timertimer.start()

Syntax:
timer.start()
Example:
CodeOutput
import simplegui

def timer_handler():
    …

timer = simplegui.create_timer(500, timer_handler)
timer.start()
# starts a timer

Starts or restarts the timer.

Stop Timertimer.stop()

Syntax:
timer.stop()
Example:
CodeOutput
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.

Check if Timer is Runningtimer.is_running()

Syntax:
timer.is_running()
Example:
CodeOutput
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.

SimpleGUI Module — Images

Operations:
Superclass:
Examples:

An image must be loaded before it can be drawn.

Load Imagesimplegui.load_image()

Syntax:
simplegui.load_image(URL)
Example:
CodeOutput
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.

Get Image's Widthimage.get_width()

Syntax:
image.get_width()

Returns the width of the image in pixels. While the image is still loading, it returns zero.

Get Image's Heightimage.get_height()

Syntax:
image.get_height()

Returns the height of the image in pixels. While the image is still loading, it returns zero.

SimpleGUI Module — Sounds

Operations:
Superclass:

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.

Load Soundsimplegui.load_sound()

Syntax:
simplegui.load_sound(URL)
Example:
CodeOutput
import simplegui

sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.set_volume(0.7)
See also:
sound.play() — How to play the sound

Loads 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.

Play Soundsound.play()

Syntax:
sound.play()
Example:
CodeOutput
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.

Pause Soundsound.pause()

Syntax:
sound.pause()
Example:
CodeOutput
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().

Rewind Soundsound.rewind()

Syntax:
sound.rewind()
Example:
CodeOutput
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.

Set Sound's Volumesound.set_volume()

Syntax:
sound.set_volume(volume)
Example:
CodeOutput
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.

SimpleGUI Module — Constants

Color Constants

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.

Keyboard Character Constantssimplegui.KEY_MAP[]

Syntax:
simplegui.KEY_MAP[character]
Example:
CodeOutput
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.

SimpleMap Module — Maps

Operations:
Superclass:

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.

Create Mapsimplemap.create_map()

Syntax:
simplemap.create_map(title, coordinates, map_width, map_height)
simplemap.create_map(title, coordinates, map_width, map_height, control_width)
Example:
CodeOutput
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.

Add Marker to Mapa_map.add_marker()

Syntax:
a_map.add_marker(description, id, icon_url, coordinates, handler)
Example:
CodeOutput
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.

Draw Line on Mapa_map.draw_line()

Syntax:
a_map.draw_line(start_marker, stop_marker)
Example:
CodeOutput
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.

Get Set of all Markers on Mapa_map.get_markers()

Syntax:
a_map.get_markers()
Example:
CodeOutput
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.

Get Set of all Lines on Mapa_map.get_lines()

Syntax:
map.get_lines()
Example:
CodeOutput
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.

Clear all Markers from Mapa_map.clear_markers()

Syntax:
a_map.clear_markers()
Example:
CodeOutput
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([])
See also:
map.clear() — Removes all markers and lines
marker.remove() — Removes one marker

Erases all markers from the drawn map. Does not remove any lines between those markers. Removes all marker objects from the map object.

Clear all Lines from Mapa_map.clear_lines()

Syntax:
a_map.clear_lines()
Example:
CodeOutput
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([])
See also:
map.clear() — Removes all markers and lines
a_line.remove() — Removes one line

Erases all paths from the drawn map. Does not remove any markers. Removes all line objects from the map object.

Clear Everything from Mapa_map.clear()

Syntax:
a_map.clear()
Example:
CodeOutput
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([])
See also:
map.clear_markers() — Removes all markers
map.clear_lines() — Removes all lines

Erases all markers and line segments from the drawn map. Removes all marker objects and line objects from the map object.

Add Button Control to Mapa_map.add_button()

Syntax:
a_map.add_button(text, handler)
a_map.add_button(text, handler, width)
Example:
CodeOutput
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.

Add Line Break to Map Control Panela_map.add_button()

Syntax:
a_map.add_break()
Example:
CodeOutput
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.

SimpleMap Module — Markers

Operations:
Superclass:

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.

Get Description of Markera_marker.get_description()

Syntax:
a_marker.get_description
Example:
CodeOutput
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.

Get ID of Markera_marker.get_id()

Syntax:
a_marker.get_id()
Example:
CodeOutput
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.

Get Coordinates of Markera_marker.get_coordinates()

Syntax:
a_marker.get_coordinates()
Example:
CodeOutput
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.

Get Icon URL of Markera_marker.get_icon()

Syntax:
a_marker.get_icon()
Example:
CodeOutput
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.

Set Icon of Markera_marker.set_icon()

Syntax:
a_marker.set_icon(URL)
Example:
CodeOutput
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.

Remove Marker from Mapa_marker.remove()

Syntax:
a_marker.remove()
Example:
CodeOutput
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([])
See also:
map.clear_markers() — Removes all markers
map.clear() — Removes all markers and lines

Erases the marker from the drawn map. Does not remove any lines using the marker. Removes the marker object from the map object.

SimpleMap Module — Lines

Operations:
Superclass:

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.

Get Start Marker of Linea_line.get_start()

Syntax:
a_line.get_start()
Example:
CodeOutput
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.

Get Stop Marker of Linea_line.get_stop()

Syntax:
a_line.get_stop()
Example:
CodeOutput
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.

Set Color of Linea_line.set_color()

Syntax:
a_line.get_stop()
Example:
CodeOutput
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
See also:
Colors — Supported colors

Changes the color of the path, which defaults to black, between the two endpoint markers of the line.

Remove Line from Mapa_line.remove()

Syntax:
a_line.remove()
Example:
CodeOutput
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([])
See also:
map.clear_lines() — Removes all lines
map.clear() — Removes all markers and lines

Erases the line from the drawn map. Does not remove the endpoint markers of the line. Removes the line object from the map object.

SimplePlot Module

Operations:

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.

Make Line Plotsimpleplot.plot_lines()

Syntax:
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)
Example:
CodeOutput
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.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value. Points are displayed in order of x value.

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.

Make Bar Plotsimpleplot.plot_bars()

Syntax:
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets, legends)
Example:
CodeOutput
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.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value. Points are displayed in order of x value.

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.

Make Scatter Plotsimpleplot.plot_scatter()

Syntax:
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets, legends)
Example:
CodeOutput
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.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value.

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.

Numeric Module — Matrices

Operations:
Superclass:

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.

Create a Matrixnumeric.Matrix()

Syntax:
numeric.Matrix(data)
Example:
CodeOutput
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.

Create an Identity Matrixnumeric.identity()

Syntax:
numeric.identity(size)
Example:
CodeOutput
import numeric

print numeric.identity(3)
[[1, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]

Returns a size×size 2-dimensional identity matrix.

Get Matrix Value at Specified Indicesa_matrix[]

Syntax:
a_matrix[(i, j)]
a_matrix.__getitem__((i, j))
Example:
CodeOutput
import numeric

print numeric.identity(3)[(0, 0)]
1.0

Returns the value in the matrix a_matrix at row i and column j.

Get One Row of Matrixa_matrix.getrow()

Syntax:
a_matrix.getrow(i)
Example:
CodeOutput
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.

Get One Column of Matrixa_matrix.getcol()

Syntax:
a_matrix.getcol(j)
Example:
CodeOutput
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.

Set Matrix Value at Specified Indicesa_matrix[]=

Syntax:
a_matrix[(i, j)] = value
a_matrix.__setitem__((i, j), value)
Example:
CodeOutput
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.

Matrix Addition+

Syntax:
matrix1 + matrix2
Example:
CodeOutput
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.

Matrix Subtraction-

Syntax:
matrix1 - matrix2
Example:
CodeOutput
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.

Matrix Multiplication*

Syntax:
matrix1 * matrix2
Example:
CodeOutput
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.

Matrix Multiplication by a Numbera_matrix.scale()

Syntax:
a_matrix.scale(factor)
Example:
CodeOutput
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.

Copy Matrixa_matrix.copy()

Syntax:
a_matrix.copy()
Example:
CodeOutput
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.

Invert Matrixa_matrix.inverse()

Syntax:
a_matrix.inverse()
Example:
CodeOutput
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.

Transpose Matrixa_matrix.transpose()

Syntax:
a_matrix.transpose()
Example:
CodeOutput
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.

Absolute Value of Matrixa_matrix.abs()

Syntax:
a_matrix.abs()
Example:
CodeOutput
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.

Sum Elements in Matrixa_matrix.summation()

Syntax:
a_matrix.summation()
Example:
CodeOutput
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.

Shape of Matrixa_matrix.shape()

Syntax:
a_matrix.shape()
Example:
CodeOutput
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).

CodeSkulptor Module

Operations:

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.

Set CodeSkulptor's Timeout Limitcodeskulptor.set_timeout()

Syntax:
codeskulptor.set_timeout(seconds)
Example:
CodeOutput
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.

Get CodeSkulptor URL for Filecodeskulptor.file2url()

Syntax:
codeskulptor.file2url(filename)
Example:
CodeOutput
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.
See also:
urllib2.urlopen — Opening text file
simplegui.load_image — Loading image file
simplegui.load_sound — Loading sound file

Returns 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.

CodeSkulptor Window Features

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.

CodeSkulptor Run Button

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.

CodeSkulptor Save Button

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.

CodeSkulptor Download Button

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.

CodeSkulptor Create Fresh URL Button

On each save the URL for your program increases in version number. This button creates a new URL independent of the previous one.

CodeSkulptor Open Local File Button

Loads a Python file from your own computer into the CodeSkulptor editor.

CodeSkulptor Reset Button

Clears the CodeSkulptor console and closes any pop-up windows created by CodeSkulptor.

Windows Keybindings (Shortcuts)

Windows Button Shortcuts

(Chrome, Safari) Alt‑RRun Python program.
(Chrome, Safari) Alt‑SSave Python program.
(Chrome, Safari) Alt‑XReset Python program.
(Firefox) Alt‑Shift‑RRun Python program.
(Firefox) Alt‑Shift‑SSave Python program.
(Firefox) Alt‑Shift‑XReset Python program.

Windows Cursor Movement

Left ArrowMove to the left one character.
Right ArrowMove to the right one character.
Up ArrowMove up one line.
Down ArrowMove down one line.
EndGo to the end of the current line.
HomeGo to the beginning of the current line.
PageUpMove up one page.
PageDownMove down one page.
Ctrl‑HomeGo to the beginning of the current page.
Alt‑UpGo to the beginning of the current page.
Ctrl‑EndGo to the end of the current page.
Ctrl‑DownGo to the end of the current page.
Ctrl‑LeftMove left one word.
Ctrl‑RightMove right one word.
Alt‑LeftGo to the start of current line.
Alt‑RightGo to the end of current line.

Windows Adding/Removing Characters

DeleteDelete character on the right.
BackspaceDelete character on the left.
InsertOverwrite characters on and after current location.
Ctrl‑DDelete current line.
Ctrl‑BackspaceDelete word to the left.
Ctrl‑DeleteDelete word to the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Ctrl‑ASelect all
Ctrl‑CCopy selected area
Ctrl‑XCut selected area
Ctrl‑VPaste
Ctrl‑ZUndo
Shift‑Ctrl‑ZRedo
Ctrl‑YRedo

Windows Indentation

TabIndent 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‑FStart Searching
Cntl‑GFind Next
Shift‑Cntl‑GFind Previous
Shift‑Cntl‑FReplace Once
Shift‑Cntl‑RReplace All

Mac OS Keybindings (Shortcuts)

Mac Button Shortcuts

(Chrome, Firefox, Safari) Ctrl‑Opt‑RRun Python program.
(Chrome, Firefox, Safari) Ctrl‑Opt‑SSave Python program.
(Chrome, Firefox, Safari) Ctrl‑Opt‑XReset Python program.

Mac Cursor Movement

LeftMove to the left one character.
RightMove to the right one character.
UpMove up one line.
DownMove down one line.
Cmd‑UpGo to the beginning of the current page.
Cmd‑DownGo to the end of the current page.
Cmd‑LeftGo to the start of the current line.
Cmd‑RightGo to the end of the current line.
Alt‑LeftMove left one word.
Alt‑RightMove right one word.
Ctrl‑BMove to the left one character.
Ctrl‑FMove to the right one character.
Ctrl‑PMove up one line.
Ctrl‑NMove down one line.
Alt‑BMove left one word.
Alt‑FMove right one word.
Ctrl‑AGo to the start of the current line.
Ctrl‑EGo to the end of the current line.
Ctrl‑VMove up one page.
Shift‑Ctrl‑VMove down one page.

Mac Adding/Removing Characters

DeleteDelete character on the left.
Cmd‑DDelete current line.
Ctrl‑HDelete character on the left.
Ctrl‑DDelete character on the right.
Alt‑DeleteDelete word on the left.
Alt‑DDelete word on the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Cmd‑ASelect all
Cmd‑CCopy selected area
Cmd‑XCut selected area
Cmd‑VPaste
Cmd‑ZUndo
Shift‑Cmd‑ZRedo
Cmd‑YRedo
Ctrl‑TSwap positions of the character to the left and the character to the right of the cursor.

Mac Indentation

TabIndent 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‑FStart Searching
Cmd‑GFind Next
Shift‑Cmd‑GFind Previous
Cmd‑Option‑FReplace Once
Shift‑Cmd‑Option‑FReplace All

Linux Keybindings (Shortcuts)

Linux Button Shortcuts

(Chrome) Alt‑RRun Python program.
(Chrome) Alt‑SSave Python program.
(Chrome) Alt‑XReset Python program.
(Firefox) Alt‑Shift‑RRun Python program.
(Firefox) Alt‑Shift‑SSave Python program.
(Firefox) Alt‑Shift‑XReset Python program.

Linux Cursor Movement

Left ArrowMove to the left one character.
Right ArrowMove to the right one character.
Up ArrowMove up one line.
Down ArrowMove down one line.
EndGo to the end of the current line.
HomeGo to the beginning of the current line.
PageUpMove up one page.
PageDownMove down one page.
Ctrl‑HomeGo to the beginning of the current page.
Alt‑UpGo to the beginning of the current page.
Ctrl‑EndGo to the end of the current page.
Ctrl‑DownGo to the end of the current page.
Ctrl‑LeftMove left one word.
Ctrl‑RightMove right one word.
Alt‑LeftGo to the start of current line.
Alt‑RightGo to the end of current line.

Linux Adding/Removing Characters

DeleteDelete character on the right.
BackspaceDelete character on the left.
InsertOverwrite characters on and after current location.
Ctrl‑DDelete current line.
Ctrl‑BackspaceDelete word to the left.
Ctrl‑DeleteDelete word to the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Ctrl‑ASelect all
Ctrl‑CCopy selected area
Ctrl‑XCut selected area
Ctrl‑VPaste
Ctrl‑ZUndo
Shift‑Ctrl‑ZRedo
Ctrl‑YRedo

Linux Indentation

TabIndent 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‑TabIndent 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‑FStart Searching
Ctrl‑GFind Next
Shift‑Ctrl‑GFind Previous
Shift‑Ctrl‑FReplace Once
Shift‑Ctrl‑RReplace All

CodeSkulptor Purpose and Use

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

  • students do not need to install any software,
  • students will all have the same Python version and the same editor, and
  • students can access the same programming environment and code files from any computer.

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.

CodeSkulptor is now hosted on a different system. This has enabled several updates, including:

If you are looking for Python3, please try py3.codeskulptor.org!

There are multiple versions of CodeSkulptor: CodeSkulptor runs Python 2 and CodeSkulptor3 runs Python 3.

Mission

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

CodeSkulptor is used in two specializations that currently run on Coursera, "Fundamentals of Computing" and "An Introduction to Scripting in Python" . The courses in these specializations were created by Scott Rixner, Joe Warren, Luay Nakhleh, John Greiner, and Stephen Wong. It is also used in Computer Science courses at Rice University.

CodeSkulptor is freely available for all to use in order to help advance computer science education. It is in use across the world in both secondary and university education. We encourage you to make use of CodeSkulptor for education in any way you find valuable!

HTTPS

CodeSkulptor now uses https. This has a few implications if you have old programs that load files (images, sounds, or by using urllib2). You may no longer load such files using http. If you have files that try to load resources using URLs beginning with "http://", CodeSkulptor will try to convert those URLs to use "https://". However, if your resource does not support the https protocol, then this will not work.

All files hosted by us support loading via either http or https. If you are trying to load your own resources, you will need to make sure that you host them somewhere that supports https.

Privacy

Your privacy is important. CodeSkulptor does not collect personal information and all users are anonymous.

All saved files are stored indefinitely. These saved files are only used by CodeSkulptor for two purposes:

  1. To provide the service: Saved files are delivered to you within CodeSkulptor whenever you access their URL. If you share a CodeSkulptor URL, anyone with that URL can also access the file that is associated with that URL.
  2. To perform educational research: The files are also used for educational research into understanding and improving computer science education. They are used anonymously (there is no way to know who authored any specific file) and they are only used for the direct purposes of the research.

By saving files in CodeSkulptor, you agree to allow those files to be used for these purposes.

CodeSkulptor uses Plausible Analytics to track overall trends in the usage of the site. Plausible Analytics only collects aggregated information, does not collect personal data, and does not use cookies. You can see exactly what is being gathered on our public analytics dashboard. For more information, please see the Plausible Data Policy.

Credits

CodeSkulptor was built by Scott Rixner . CodeSkulptor's documenation was developed by John Greiner .

CodeSkulptor is based upon the following software packages:

CodeSkulptor utilizes the following services:

The CodeSkulptor documentation was built by John Greiner.