Python Flashcards
Function Definition
def functionname():
body return()
Importing modules
Generic Import:
import modulename
use as: modulename.functionname()
Function Import:
from modulename import functionname
use as: functionname()
Universal Import:
from modulename import *
use as functionname()
if statement
if x < 0:
x = 0 print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
List
Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name. Index starts at Zero
- list_name* = [item_1, item_2]
- empty_list* = [].
List - append function
list_name.append(new item)
append is a built-in function of lists, it appends a new item at the end of the list
List - slicing
slice = list_name[first slice item index: last slice item index + 1: stride]
strings - slicing
stringname[:3] - first 3 characters
stringname[3:5] - from fourth to fifth
stringname[3:] - from second to last
List - index function
listname.index(itemname) will return the first index that contains the item. If there is no such item will return an error
List - insert function
listname.insert(index,item) inserts item with specified index on listname
for loop
for variable in list_name:
# do stuff break
else:
# do other stuff
A variable name follows the for keyword; it will be assigned the value of each list item in turn. in list_name designates list_name as the list the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.
else statement is executed after the for loop ends, except when a break occurs
List - sort function
listname.sort()
sorts listname in increasing order
Dictionary - Definition
A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so:
d = {‘key1’ : 1, ‘key2’ : 2, ‘key3’ : 3}
This is a dictionary called d with three key-value pairs. The key ‘key1’ points to the value 1, ‘key2’ to 2, and so on.
List - Length function
len(listname)
returns the number of items on the list
Dictionary - new entry
A new key-value pair in a dictionary is created by assigning a new key, like so:
dict_name[new_key] = new_value
An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
Dictionary - Length function
len(dictionary)
returns the number of pairs on the dictionary. Each pair counts only one, even if the value is a list
Dictionary - del command and remove function
del dict_name[key_name]
will remove the pair with key_name from dict_name
my_list.remove(value)
will remove the the first item from my_list that has a value equal to value.
The difference between del and .remove() is: del deletes a key and its value based on the key you tell it to delete. .remove() removes a key and its value based on the value you tell it to delete
range
A range can take 1, 2 or 3 arguments. If you use one argument, it starts the range at zero and increments by 1 until the size reaches 1 less than the range. For instance,
range(1) # => [0]
range(2) # => [0,1]
If you use two arguments, the first argument is the start for the range and the second argument is the same as above: range(1,3) # => [1,2]
If you use 3 arguments, the range’s first argument is the number the list starts at, the second number is where the list ends, and the third argument is how much you should increment by instead of the default increment of 1. For instance: range(2,8,3) # => [2,5] range(2,9,3) # => [2,5,8]
while loop
while condition:
#code to execute break statement will exit the loop
while / else loop
while condition:
code break else: code the else will execute when the while condition is not satisfied, and the loop ends. If the while exits because of a break statement then the else is not executed
List - zip fuction
zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list. zip can handle three or more lists as well
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a>b: print a
else: print b
Iterators for dictionaries
items(), keys() and values()
items() will iterate over a dictionary and return those key/value pairs
d = {
“Name”: “Guido”,
“Age”: 56,
“BDFL”: True
}
Calling:
d.items()
Will result in
=> [(‘BDFL’, True), (‘Age’, 56), (‘Name’, ‘Guido’)]
keys() function returns an array of the dictionary’s keys
values() function returns an array of the dictionary’s values.
List comprehension
*new\_list* = [x for x in range(1,6)] # =\> [1, 2, 3, 4, 5]
doubles = [x\*2 for x in range(1,6)] # =\> [2, 4, 6, 8, 10]
list_name = [x*2 for x in range(1,6) if (x*2)%3 == 0]
=> [6]
Lambda functions
lambda x: function based on x
Lambda is a shorthand to create anonymous functions y python
Class - Basics
Class Syntax A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in parentheses. (We'll get to inheritance soon.) For now, our classes will inherit from the object class, like so:
class NewClass(object):
def \_\_init\_\_(self): # Class magic here
This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a capital letter.
Class - __init()__ and self
You can think of __init__() as the method that “boots up” a class’ instance object: the init bit is short for “initialize.”
The first argument __init__() gets is used to refer to the instance object, and by convention, that argument is called self. If you add additional arguments—for instance, a name and age for your animal—setting each of those equal to self.name and self.age in the body of __init__() will make it so that when you create an instance object of your Animal class, you need to give each instance a name and an age, and those will be associated with the particular instance you create.
class Animal(object): def \_\_init\_\_(self, name, age): self.name = name self.age = age
zebra = Animal(“Jeffrey”, 2)
giraffe = Animal(“Bruce”, 1)
Class - Scope