Python Documentation

Comments

# Comments allow us to describe our program so that other
# people can read it more easily.

# Multiline comments are prefixed and suffixed with """ such as:

"""
This program will ask the user for a number.
Then it will square that number and print the final value.
"""
import math

number = int(input("Enter a number: "))
print "Squared: " + str(math.pow(number, 2))

# Single line comments in Python are prefixed with a '#' such as:

# This program adds 1 and 2
a = 1 + 2
print a

Printing

print "Hello world"
print 2 + 2
print 10

String Formatting

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

Variables

# Create a variable named `name`
name = "Zach"
print name

# Create variables that are numbers
a = 3
b = 4
c = a + b

# Get the type of the variable
type_string = "Hello world!"
type_int = 1110

print type(type_string)
print type(type_int)

User Input

# You should replace the word prompt with
# the question you'd like to ask. For example:
person = input('Enter your name: ')
print('Hello', person)

Math

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

import math

# 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
square_root = math.sqrt(x)

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

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

Comparison Operators

# Comparison operators return booleans (true/false values)

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

Random Numbers

# Random integer between (and including) low and high
import random  # you need to import it to be able to use randint!
random_num = random.randint(low, high)

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

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

String Methods

# To make a string all uppercase
my_string = “hello”
my_string = my_string.upper()     # returns “HELLO”

# To make a string all lowercase
my_string = “HELLO”
my_string = my_string.lower()     # returns “hello”

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

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

# Returns a string in which each letter is the opposite case as
# the original string
my_string = “PyThOn”
my_string = my_string.swapcase()      # returns “pYtHoN”

# Returns a copy of the string you call it on, without any
# whitespace at the beginning or end
my_string = “       hi there       “
my_string = my_string.strip()          # returns “hi there”

# 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

# Concatenation
my_string = "Karel the"
print my_string + " dog"

# Returns a character at a specific index
my_string = "hello!"
print my_string[0]  # returns "h"
print my_string[5]  # returns "!"

# Returns all the characters after the specific index
my_string = "hello world!"
print my_string[1:] # returns "ello world!"
print my_string[6:] # returns "world!"

# Returns all the characters before the specific index
my_string = "hello world!"
print my_string[:6] # returns "hello"
print my_string[:1] # returns "h"

# Iterates through every character in the string
my_string = "Turtle"

for c in my_string:
    print c

# Splits the string into a list of words
my_string = "Karel is a dog"
my_list = my_string.split()     # Returns ['Karel', 'is', 'a', 'dog']

# Using enumerate
my_string = "This is a dog"
for index, word in enumerate(my_string.split()):
    print str(index) + ": " + word

Type Conversion

# Type conversion allows us to convert variables to different types
# String to Integer conversion
my_string = "3"
to_int = int(my_string)

# Integer to String conversion
my_int = 11
to_string = str(my_int)

# Other conversions
my_list = [4, 5, 6]
new_tuple = tuple(my_list)

my_tuple = (3,2)
new_list = list(my_tuple)

my_list = [4, 5, 6]
new_set = set(my_list)

my_list = [4, 5]
new_dict = dict([my_list])

Exceptions

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

# Try/Except with input
try:
    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
try:
    my_number = '2' + 2
except TypeError:
    print "A type error has occured!"

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

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

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

Booleans

# A boolean is either True or False
my_boolean = True

anotherBoolean = False

Operators

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

If Statements, If/Else

if BOOLEAN_EXPRESSION:
    print "This executes if BOOLEAN_EXPRESSION evaluates to True"


if BOOLEAN_EXPRESSION:
    print "This executes if BOOLEAN_EXPRESSION evaluates to True"
else:
    print "This executes if BOOLEAN_EXPRESSION does not evaluate to True"


if x < 0:
    print "x is negative."


if color == "red" or color == "blue" or color == "yellow":
    print "Primary color."
else:
    print "Not a primary color."


# You can use elif if you have multiple
# conditions, but only one should happen.
if condition_1:
    print "condition_1 evaluates to True"
elif condition_2:
    print "condition_2 evaluates to True"
elif condition_3:
    print "condition_3 evaluates to True"
else:
    print "None of the above conditions evaluated to True. So I execute."



# You can always write these using nested
# if/else. For example:
if condition_1:
    print "condition_1 evaluates to True"
else:
    if condition_2:
        print "condition_2 evaluates to True"
    else:
        print "condition_2 evaluates to False"

For Loops

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


# This for loop will print out the numbers 0 through 9
for number in range(10):
    print number


my_list = [1,5,10,15]

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


# Return a list of each number doubled
new_list = [] # Make a new empty list
for number in my_list:
    number *= 2
    new_list.append(number)
return new_list

While Loops

while BOOLEAN_EXPRESSION:
    # Repeat code betweeen brackets while
    # 'boolean expression' is true

# Countdown from from 15 to 10
i = 15
while i >= 10:
    print i
    i -= 1

Functions

# Define a function that returns the sum of two numbers
def add(x, y):
    return x + y

# Use the `add` function to print the sum
print add(1, 2)

Classes

# 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
print my_class.my_num

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)

Lists

# Create an empty list
my_list = []

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

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

# Access a element in a list
element = my_list[i]
first_element = a_list[0] # Returns "hello"


# Set an element in a list
my_list[i] = item
a_list[0] = 9 # a_list = [9, 4, True]

# Looping over a list
for item in my_list:
    print "code that executes on each item"
for thing in a_list:
    print thing  # Prints all the items in a_list in order

# Length of a list
list_length = len(my_list)
a_list_length = len(a_list) # Returns 3

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

# Remove and return last element from the list
last = my_list.pop()
last_item = a_list.pop() # Returns and removes "Puppy"


# Remove and return an item from a list at index i
my_list.pop(i)
a_list.pop(0) # Returns and removes "hello"

# Return the index in the list of the first item whose value is x.
# It is an error if there is no such item
my_list.index(x)
a_list.index(4)
# Since currently a_list = [4, True] this will return 0
# Because 0 is the index of 4 in the list.

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

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

# Returns the number of instances
# of a particular thing that were found.
my_list = [1, 4, 2, -4, 10, 0, 4, 2, 1, 4]

print my_list.count(4)
print my_list.count(0)
print my_list.count(1)
print my_list.count(12313)

# 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]

# Allows us to remove a particular item from a list
my_list = ["apple", "banana", "orange", "grapefruit"]

# Returns ["apple", "banana", "grapefruit"]
my_list.remove("orange")


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 [[0, 0, 0], [1, 2, 4]]

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

Dictionaries

# Dictionaries have a collection of key, value pairs

a_dictionary = {key1:value1, key2:value2}

my_farm = {pigs:2, cows:4}  # A dictionary can keep a farm's animal count!

# Create an empty dictionary
a_dictionary = {}

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

# Get 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])

Sets

# 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
new_set.add(item)
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(my_set)
len(girl_scout_badges) #Returns 1 since there is only one item in the set

Tuples

# Tuples are immutable sequences of items.
# Make a new tuple named "my_tuple"
my_tuple = (1, 2, 3, 4, 5)

# Print the item at a specific index
print my_tuple[0]
print my_tuple[4]

# Slice the tuple at the specific index
print my_tuple[:3]

# Get the length of the tuple
print len(my_tuple)

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

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

# Accessing elements within nested tuples
print my_tuple[0][0]
print my_tuple[1][0]

# Tuple with single element
my_tuple = (3,)

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

File Input

# 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:
file.read()     # 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
file.close()