Please enable JavaScript to use CodeHS

Python Documentation



We can print elements to the screen by using the print command. If we want to print text, we need to surround the text with quotation marks " ".

print("Hello world")
print(2 + 2)

String Formatting

print("My name is %s and I am %d years old!" % ('Zara', 21))


We use variables to store values that can be used to control commands in our code. We can also alter these values throughout the code.

# Make a variable to store text
name = "Zach"

# Create variables that are numbers
num_one = 3
num_two = 4
sum = num_one + num_two

# We can also assign multiple variables at once
num_one, num_two = 3, 4

# The value of a variable can be changed after it has been created
num_one = num_one + 1

Variables have an associated 'type' based on their characteristics. A string (str) is a text element, an integer (int) is a whole number element, a float (float) is a number with decimal places, and a Boolean (bool) is an element that returns either True or False. We use the type command to determine the type of an element.

# The output will be str, or string

# The output will be int, or integer

# The output will be bool, or boolean

# We can change the type of an element by using the shortened name of the type
# We do this when concatenating strings, such as:

age = 16
print("My age is " + str(age))

User Input

We can use input from the user to control our code.

# Ask the user for input and save it to a variable to be used in code
# This will only work if the input is being used as a string
name = input("What is your name? ")

# If input needs to be used as a number, include the term 'int'
num_one = int(input("Enter a number: "))
num_two = int(input("Enter a second number: "))

# This input can then be used to control different parts of the code
print("Hello, " + name)
sum = num_one + num_two


We use comments to leave notes about the code to the reader. Comments are not actually run by Python, they are just there to help us read the code.

We can make multiline comments with """ and single line comments with #.

A multi-line comment describes your code
to someone who is reading it.


This program will ask the user for two numbers.
Then it will add the numbers and print the final value.
number_one = int(input("Enter a number: "))
number_two = int(input("Enter a second number: "))
print("Sum: " + str(number_one + number_two))

# Use single line comments to clarify parts of code.


# This program adds 1 and 2
added = 1 + 2

Break and Continue

We can use the break command to end our code. The continue command will leave the control structure at that point and move to the commands found afterward.

# This code will end when the use enters a negative
number = int(input("Enter a number: "))
if number < 0:

# This code will only print the numbers 0 to 3 and 6
for i in range(5):
    if i < 4:


Exception handling allows us to prevent our programs from crashing in the event of a fault.

# Try/Except with input
    my_number = int(input("Enter an integer: "))
    print("Your number: " + str(my_number))
except ValueError:
    print("That wasn't an integer!")

# Try/Except for Type Errors
    my_number = '2' + 2
except TypeError:
    print("A type error has occurred!")

# Try/Except for Key Errors
dictionary = {'1':'k', '3':'A', '4':'R', '5':'E', '6':'L'}
except KeyError:
    print("Key error")

# Try/Except for Attribute Errors
except AttributeError:
    print("Attribute Error!")

# You can also have
    my_number = int(input("Enter an integer: "))
    print("Your number: " + str(my_number))
    print("There was an error.")

Random Numbers

To be able to use the randint or choice functions, you must use import random at the beginning of your code.

# Random integer between (and including) low and high
import random
random_num = random.randint(low, high)
random_element = random.choice(string)

# Example:
# Returns random number within and including 0 and 10.
random_num = random.randint(0,10)

# Random element in a string
random_element = random.choice('abcdefghij')


We use mathematical, comparison, and logical operators in our codes to compare and alter values and make decisions.

Mathematical Operators

Use mathematical operators to alter values.

+   Addition
-   Subtraction
*   Multiplication
/   Division
%   Modulus (Remainder)
()  Parentheses (For order of operations)

# Examples
z = x + y
w = x * y

# Division
a = 5.0 / 2                     # Returns 2.5
b = 5.0 // 2                    # Returns 2.0
c = 5/2                         # Returns 2

# Increment (add one)
x += 1

# Decrement (subtract one)
x -= 1

# Absolute value
absolute_value = abs(x)

abs_val = abs(-5)               # Returns 5

# Square root
import math
square_root = math.sqrt(x)

# Raising to a power
power = math.pow(x, y)          # Calculates x^y

# Rounding
rounded_num = round(2.675, 2)   # Returns 2.68

Comparison Operators

Use comparison operators to compare elements in order to make decisions in your code. Comparison operators return booleans (True/False).

x == y      # is x equal to y
x != y      # is x not equal to y
x > y       # is x greater than y
x >= y      # is x greater than or equal to y
x < y       # is x less than y
x <= y      # is x less than or equal to y

# Comparison operators in if statements
if x == y:
    print("x and y are equal")

if x > 5:
    print("x is greater than 5.")

Logical Operators

Use logical operators to check multiple conditions at once or one condition out of multiple.

# And Operator
and_expression = x and y

# Or Operator
or_expression = x or y

# You can combine many booleans!
boolean_expression = x and (y or z)

Control Structures

If/Else Statements

We can tell the computer how to make decisions using if/else statements. Make sure that all the code inside your if/else statement is indented one level!

If Statements

Use an if statement to instruct the computer to do something only when a condition is true. If the condition is false, the command indented underneath will be skipped.

    print("This executes if BOOLEAN_EXPRESSION evaluates to True")

# Example:

# The text will only print if the user enters a negative number
number = int(input("Enter a number: "))
if number < 0:
    print(str(number) + " is negative!")

If/Else Statements

Use an if/else statement to force the computer to make a decision between multiple conditions. If the first condition is false, the computer will skip to the next condition until it finds one that is true. If no conditions are true, the commands inside the else block will be performed.

if condition_1:
    print("This executes if condition_1 evaluates to True")
elif condition_2:
    print("This executes if condition_2 evaluates to True")
    print("This executes if no prior conditions evaluate to True")

# Example:

# This program will print that the color is secondary
color == "purple"
if color == "red" or color == "blue" or color == "yellow":
    print("Primary color.")
elif color == "green" or color == "orange" or color == "purple":
    print("Secondary color.")
    print("Not a primary or secondary color.")


Loops help us repeat commands which makes our code much shorter. Make sure everything inside the loop is indented one level!

For Loops

Use for loops when you want to repeat something a fixed number of times.

# This for loop will print "hello" 5 times
for i in range(5):

# This for loop will print out even numbers 1 through 10
for number in range(2, 11, 2):

# This code executes on each item in my_list
# This loop will print 1, then 5, then 10, then 15
my_list = [1, 5, 10, 15]
for item in my_list:

While Loops

Use while loops when you want to repeat something an unknown number of times or until a condition becomes false. If there is no point where the condition becomes false, you will create an infinite loop which should always be avoided!

# This program will run as long as the variable 'number' is greater than 0
# Countdown from from 10 to 0
number = 10
while number >= 0:
    number -= 1

# You can also use user input to control a while loop
# This code will continue running while the user answers 'Yes'
answer = input("Continue code?: ")
while answer == "Yes":
    answer = input("Continue code?: ")


Writing a function is like teaching the computer a new word.

Naming Functions: You can name your functions whatever you want, but you can't have spaces in the function name. Instead of spaces, use underscores ( _ ) like_this_for_example

Make sure that all the code inside your function is indented one level!

Defining a Function

We define a function to teach the computer the instructions for a new word. We need to use the term def to tell the computer we're creating a function.

def name_of_your_function():
    # Code that will run when you make a call to
    # this function.

# Example:

# Teach the computer to add two numbers
num_one = 1
num_two = 2
def add_numbers():
    sum = num_one + num_two

Returning Values in Functions

We can use the command return to have a function give a value back to the code that called it. Without the return command, we could not use any altered values that were determined by the function.

# We add a return statement in order to use the value of the sum variable
num_one = 1
num_two = 2
def add_numbers():
    sum = num_one + num_two
    return sum

Calling a Function

We call a function to tell the computer to actually carry out the new command.

# Call the add_numbers() function once
# The computer will return a value of 3

# Call the add_numbers() function 3 times and print the output
# The output will be the number 3 printed on 3 separate lines


We can use parameters to alter certain commands in our function. We have to include arguments for the parameters in our function call.

# In this program, parameters are used to give two numbers
def add_numbers(num_one, num_two):
    sum = num_one + num_two
    return sum

# We call the function with values inside the parentheses
# This program will print '7'
print(add_numbers(3, 4))
# If we have a list with the same number of parameters, we
# can use the items to assign arguments using an asterisk
my_list = [3, 4]


Strings are pieces of text. We can gain much information about strings and alter them in many ways using various methods.

Indexing a String

We use indexing to find or take certain portions of a string. Index values always start at 0 for the first character and increase by 1 as we move to the right. From the end of the string, the final value also has an index of -1 with the values decreasing by 1 as we move to the left.

# Prints a character at a specific index
my_string = "hello!"
print(my_string[0])      # prints "h"
print(my_string[5])      # prints "!"

# Prints all the characters after the specific index
my_string = "hello world!"
print(my_string[1:])     # prints "ello world!"
print(my_string[6:])     # prints "world!"

# Prints all the characters before the specific index
my_string = "hello world!"
print(my_string[:6])     # prints "hello"
print(my_string[:1])     # prints "h"

# Prints all the characters between the specific indices
my_string = "hello world!"
print(my_string[1:6])     # prints "ello"
print(my_string[4:7])     # prints "o w"

# Iterates through every character in the string
# Will print one letter of the string on each line in order
my_string = "Turtle"
for c in my_string:

# Completes commands if the string is found inside the given string
my_string = "hello world!"
if "world" in my_string:

# Concatenation
my_string = "Tracy the"
print(my_string + " turtle")     # prints "Tracy the turtle"

# Splits the string into a list of letters
my_string = "Tracy"
my_list = list(my_string)       # my_list = ['T', 'r', 'a', 'c', 'y']

# Using enumerate will print the index number followed by a colon and the
# word at that index for each word in the list
my_string = "Tracy is a turtle"
for index, word in enumerate(my_string.split()):
    print(str(index) + ": " + word)

String Methods

There are many methods that can be used to alter strings.

# upper: To make a string all uppercase
my_string = "Hello"
my_string = my_string.upper()     # returns "HELLO"

# lower: To make a string all lowercase
my_string = "Hello"
my_string = my_string.lower()     # returns "hello"

# isupper: Returns True if a string is all uppercase letters and False otherwise
my_string = "HELLO"
print(my_string.isupper())        # returns True

# islower: Returns True if a string is all lowercase letters and False otherwise
my_string = "Hello"
print(my_string.islower())        # returns False

# swapcase: Returns a string where each letter is the opposite case from original
my_string = "PyThOn"
my_string = my_string.swapcase()  # returns "pYtHoN"

# strip: Returns a copy of the string without any whitespace at beginning or end
my_string = "       hi there       "
my_string = my_string.strip()     # returns "hi there"

# find: Returns the lowest index in the string where substring is found
# Returns -1 if substring is not found
my_string = "eggplant"
index = my_string.find("plant")   # returns 3
index = my_string.find("Tracy")   # returns -1

# split: Splits the string into a list of words at whitespace
my_string = "Tracy is a turtle"
my_list = my_string.split()       # Returns ['Tracy', 'is', 'a', 'turtle']

Data Structures


Tuples are immutable sequences of items.

Creating a Tuple

We create a tuple by listing items inside parentheses. We can include elements of any type.

# Make a new tuple named "my_tuple"
my_tuple = (1, 2, 3, 4, 5)

# Tuple with elements of different types
my_tuple = (0, 1, "Tracy", (1, 2))

# Tuple with single element
my_tuple = (3,)

# Tuple of tuples
my_tuple((0, 1), (2, 3))

Altering a Tuple

Due to the immutable nature of tuples, we cannot alter individual elements in the tuple but can perform various other tasks with them.

# Get the length of the tuple

# Accessing elements within nested tuples

# Concatenating tuples
x = (1, 2)
y = (5, 6)
my_tuple = x + (3,) + y


Lists are mutable sequences of items.

Creating a List

We create a list by listing items inside square brackets. We can include elements of any type.

# Create an empty list
my_list = []

# Create a list with any number of items
my_list = [item1, item2, item3]
# Example:
number_list = [1, 2, 4]

# A list can have any type
my_list = [integer, string, boolean]
# Example:
a_list = ["hello", 4, True]

Altering a List

Due to the mutable nature of lists, we can alter individual elements in the list.

# Access an element in a list
a_list = ["hello", 4, True]
first_element = a_list[0]    # Returns "hello"

# Set an element in a list
a_list = ["hello", 4, True]
a_list[0] = 9                # Changes a_list to be [9, 4, True]

# Looping over a list
# Prints each item on a separate line (9, then 4, then True)
a_list = [9, 4, True]
for item in a_list:

# Length of a list
a_list = [9, 4, True]
a_list_length = len(a_list)  # Returns 3

# Creates a list based on first operation
# This will create a list with numbers 0 to 4
a_list = [x for x in range(5)]
# This will create a list with multiples of 2 from 0 to 8
list_of_multiples = [2*x for x in range(5)]

List Methods

There are many methods that can be used to alter lists.

# append: Add to a list
a_list = ["hello", 4, True]
a_list.append("Puppy")       # Now a_list = ["hello", 4, True, "Puppy"]

# pop: Remove and return last element from the list
a_list = ["hello", 4, True]
last_item = a_list.pop()     # Removes True, now a_list = ["hello", 4]
# Remove and return an item from a list at index i
a_list = ["hello", 4, True]
a_list.pop(0)                # Removes "hello", now a_list = [4, True]

# index: Returns the index value of the first item in the list that matches element
# There is an error if there is no such item
a_list = ["hello", 4, True]
a_list.index(4)               # Returns 1 because 4 is found at index[1]
a_list.index("hi")            # Error because no item "hi"

# sort: Returns a sorted list
my_list = [9, 7, 1, 2, 3]
my_list.sort()               # Returns [1, 2, 3, 7, 9]

# reverse: Returns a reversed list
my_list = [1, 2, 3, 4]
my_list.reverse()            # Returns [4, 3, 2, 1]

# count: Returns the number of instances of a particular item that were found
my_list = [1, 4, 2, -4, 10, 0, 4, 2, 1, 4]
print(my_list.count(4))      # Returns 3
print(my_list.count(123))    # Returns 0 because 123 does not exist in list

# extend: Allows us to add a list to a list
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])    # Returns [1, 2, 3, 4, 5, 6]

# remove: Allows us to remove a particular item from a list
# Only removes the first instance of the item
my_list = ["apple", "banana", "orange", "grapefruit"]
my_list.remove("orange")     # Returns ["apple", "banana", "grapefruit"]

# join: Creates string out of list with specified string placed between each item
my_list = ["Tracy", "is", "a", "turtle"]
(" ").join(my_list)          # Returns the list as a string with spaces between words

2D Lists

2D Lists allow us to create lists of lists.

# Create an empty list
my_list = []

# Add to the list
my_list.append([1, 2, 3])
my_list.append([4, 5, 6])

# Access elements within the nested lists
print(my_list[0])       # Returns [1, 2, 3]
print(my_list[0][1])    # Returns 2

# Take a slice of the outer list
print(my_list[0:2])     # Returns [[1, 2, 3], [4, 5, 6]]

# Take a slice of the inner list
print(my_list[0][0:2])  # Returns [1, 2]


Dictionaries have a collections of key-value pairs.

a_dictionary = {key1:value1, key2:value2}
# Example:
my_farm = {pigs:2, cows:4}  # This dictionary keeps a farm's animal count

# Creates an empty dictionary
a_dictionary = {}

# Inserts a key-value pair
a_dictionary[key] = value
my_farm["horses"] = 1      # The farm now has one horse

# Gets a value for a key
my_dict[key] # Will return the key
my_farm["pigs"]            # Will return 2, the value of "pigs"

# Using the 'in' keyword
my_dict = {"a": 1, "b": 2}
print("a" in my_dict)      # Returns True
print("z" in my_dict)      # Returns False
print(2 in my_dict)        # Returns False, because 2 is not a key

# Iterating through a dictionary
for key in my_dict:
    print("key: " + str(key))
    print("value: " + str(my_dict[key]))


Classes hold multiple functions.

# Declare a class
class MyClass:
    # The __init__ method is called whenever we instantiate our class
    def __init__(self):
        print("Class initiated")
        self.my_num = 0

# Instantiate your class
my_class = MyClass()

# Access instance variables in your class

my_class.my_num = 10

# Adding arguments to your class
class Point:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

# Instantiate the class
p = Point(3, 4)


A set contains an unordered collection of unique and immutable objects.

# Make a new set named "new_set"
new_set = set([])
girl_scout_badges = set([])

# Add to a set
girl_scout_badges.add("Squirrel Whisperer")

# Does a set contain a value
item in my_set # Returns a boolean
"Squirrel Whisperer" in girl_scout_badges  # Returns True

# Number of elements in the set
len(girl_scout_badges)  # Returns 1 since there is only one item in the set


File Input

Use the following when importing files.

# Extracting Data from a File:

# Example File:

#        test.txt
#   ------------------
#   Hello World
#   This is File Input
#   ------------------

# Opening the file, Create a File object and store it in a Variable:
file = open('test.txt')

# Getting all text:     # Returns:
                #   Hello World
                #   This is File Input

# Getting a Line of Text:
file.readline()     # Returns:
                    #   Hello World

# Getting lines in a file:
for line in file:
    print(line + '!')   # Returns:
                        #   Hello World\n!
                        #   This is File Input\n!

# Note '\n', signifying the end of a line of text
for line in file:
    print(line + '!')   # Returns:
                        #   Hello World
                        #   !
                        #   This is File Input
                        #   !

# To remove this extra newline, we can use:
for line in file:
    print(line.strip() + '!')   # Returns:
                                #   Hello World!
                                #   This is File input!

# Closing a File


We use a custom library to add graphics to the screen.


The coordinate system used in our Python Graphics canvas is a bit different than the accepted x-y system. The (0,0) point is location in the top left hand corner, with x values increasing as you move right, and y values increasing as you move down.

# Get Canvas dimensions
width = get_width()
height = get_height()

# Set canvas size
set_size(width, height)

# Example: set a size to 200 wide by 300 tall
set_size(200, 300)

# Removes all graphic items from the canvas


We add circle to our canvas by noting the x and y positions of the center of the circle.

# To make a circle
circle = Circle(radius)

# To set the location of the center of the circle
circle.set_position(x, y)

# Example, red circle with 50px radius with center at (100, 200)
circle = Circle(50)
circle.set_position(100, 200)

# Get the radius
circle.get_radius()				# returns 50
cur_radius = circle.get_radius()	# store in variable

# Change the radius

# Get the position of the center of the circle
x = circle.get_x()  # x is 100
y = circle.get_y()  # y is 200

# Change the location of the circle
x = get_width() / 2
y = get_height() / 2
circle.set_position(x, y)   # circle center is in the center of the screen

# Adding to and removing from screen
add(circle) # Add to screen
remove(circle) # Remove from screen

# Move the circle dx horizontally and dy vertically
circle.move(dx, dy)


We add rectangles to our canvas by noting the x and y positions of the top left corner of the rectangle.

# To make a rectangle
rect = Rectangle(width, height)

# To set location of the upper left corner of rectangle
rect.set_position(x, y)

# Example, 200x50 blue rectangle with upper left corner at (100, 200)
rect = Rectangle(200, 50)
rect.set_position(100, 200)

# Get location of the upper left corner of the rectangle
x = rect.get_x() # x is 100
y = rect.get_y() # y is 200

# Change location of the rectangle
x = get_width() / 2
y = get_height() / 2
rect.set_position(x, y)  # upper left corner is at center of screen

# Adding to and removing from screen
add(rect) # Add rectangle
remove(rect) # Remove rectangle

# Move the rect dx horizontally and dy vertically
rect.move(dx, dy)


We add lines to our canvas by noting the x and y positions of each point.

# To draw a line from (x1, y1) to (x2, y2)
line = Line(x1, y1, x2, y2)

# Set the line color to green

# Adding to and removing from screen

# Move the line dx horizontally and dy vertically
line.move(dx, dy)

# Change the starting point of the line to (x1, y1)
line.set_position(x1, y1)

# Change the end point of the line to (x2, y2)
line.set_endpoint(x2, y2)

# Get the starting point of the line
x = line.get_x()    # x has same value as x1
y = line.get_y()    # y has same value as y1


We add text to our canvas by noting the x and y position of the lower left corner of the text.

# To make a graphical text object
txt = Text(label)

# To set the position of the lower left corner of the text
txt.set_position(x, y)

# Example
txt = Text("Hello, world!")
txt.set_position(100, 200)
txt.set_font("30pt Arial")

# Change what the text says

# Get the location of the lower left corner of text
x = txt.get_x() # x is 100
y = txt.get_y() # y is 200

# Change the location of the text
var x = get_width() / 2
var y = get_height() / 2
txt.set_position(x, y)   # text's lower left corner is
						# in the center of the screen

# Adding to and removing from screen
add(txt) // Add text
remove(txt) // Remove text

# Move the text dx horizontally and dy vertically
txt.move(dx, dy)


Hex Colors

# You can use any color combination you want using hex colors # To find hex values, you can use this color picker:
# This will se the object to be a gold color

We can use also use some accepted color names to set the colors of attributes in our Python Graphics programs.

# There are many color constants. You can set an objects
# color like

# Specifically,

# List of preset colors:


A web image can be added to the graphics canvas using the Image function. Images are created, sized, and positioned much like other graphics objects.

# To create a new Image, use a URL that links
# directly to the image on the Internet (you will
# not be able to use an image that is stored
# only on your computer).

copter = Image("" +
						  "wikipedia/commons/4/41/" +
copter.set_size(300, 150)
copter.set_position(get_width()/4, get_height()/2)
add(copter) # Adding copter to screen
remove(copter) # Removing copter from screen

# Note that the URL to the image must be directly
# to the image file itself. It should end with
# something like .png, .jpg, or another image file type.

Getting Pixel Data

We can get basic pixel data to help us alter our images.

# Getting pixel data
get_pixel(x, y)

# Pixel data is returned as a list of 3 elements:
# [red, green, blue]
# each element ranges from 0 to 255
# store the pixel to help analyze it.

# Example:

pxl = Pixel(50, 100)
red = pxl[0]
green = pxl[1]
blue = pxl[2]

Setting Pixel Data

We can set new values for our pixels to help us alter our images.

# setting pixel data - values are from 0 to 255
img.set_red(x, y, value)
img.set_green(x, y, value)
img.set_blue(x, y, value)

# Example: Update pixel at 50, 75 to have 
# a blue value of 255
img = Image("")
img.set_blue(50, 75, 255)


The following graphic objects can be rotated: Rectangle, Line, Image

# Set the rotation of the object using radians

rect.set_rotation(math.pi)    # Sets rotation of the rectangle to math.pi radians
rect.set_rotation(math.radians(45)) # Using math.radians(degrees) to set
                                    # rotation to 45 degrees


We can use timers to have a function run on a delay. The function will continue to execute after each interval.

from browser import timer                    # import the timer module
timer_id = timer.set_interval(fn, delay)   # Create a timer and store the id
timer.clear_interval(timer_id) 		# Stop a timer

# Example: call move_ball every 40 milliseconds
def move_ball():
	ball.move(5, 0)

timer.set_interval(move_ball, 40)

Mouse Click Events

We add mouse click events by binding a function to a specific mouse click. The function name does not include parenthesis, but the mouse click event does pass the x and y coordinates of the mouse click to the function.

# General format

# Callback function
def callback(x, y):
    # do something


# Example: Create circle with a radius of 10 and centered
# at the mouse click
def make_circle(x, y):
    circle = Circle(10)
    circle.set_position(x, y)


Keyboard Events

We can add keyboard events similar to mouse click events by binding a function to the key event. The function name does not include parenthesis, but the event does pass information about which key was presssed. We can use that event information to find out which ket was pressed.

# General format

# Callback function
def callback(event):
    key = event.key


# Moving square example

def move_square(event):
    if event.key == "ArrowLeft":
        square.move(-15, 0)
    if event.key == "ArrowRight":
    if event.key == "ArrowUp":
        square.move(0, -15)
    if event.key == "ArrowDown":

square = Rectangle(40, 40)