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