Demo entry 6332880

test

   

Submitted by anonymous on Dec 02, 2016 at 18:00
Language: Python 3. Code size: 7.5 kB.

#Notes for CS121 Final

#is vs == according to convention
x is None
x is not None
x == 0 #boolean
x != 0

#Conditional
if <boolean expression>:
    <statements>
elif <boolean expression>:
    <statements>
else:
    <statements>

#For loops
for <variable> in <sequence>:
    <statements>
    break #break: use to stop for loop
for i in range(len(prices)) #iterate over indices of list

#Cumulative
x = x + 1

#While loops
while <boolean expression>:
<statements>

#Lists
l = []
len(l) #length
l = [0] * 10 = [0, 0, 0,...]
l[2] #index starts from zero
l[-1] #last element in the list
l[1:3] #slicing from 1 to 2
l[1:7:2] #slicing with 2 steps: we get the values at indexes 1, 3, and 5 (but not 7)
l.append("test")
l.extend(l2) #stick one list to another
l = l2 + l3 #new list from existing lists
l.insert(2, "test") #insted element in specific position
l.pop(2) #remove and return second element, by default removes the last one
del l[1] #operator to delete element

enumerate(l) #returns a tuple with elements of l and their index position
min(l)
max(l)
sum(l)
lst.count(4) #count occurences of 4
l.reverse()
l.sort() #ascending
l2 = sorted(l) #ascending copy

m = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] #list of lists

#Tuples (,)
Similar to lists but cannot be modified
    #iterating over list of tuples
    for name, salary in salaries: #unpack the tuple in the forloop
        print(name, "has a salary of", salary)

#Strings
s = "foobar"
s[0] = "f"
s[1:4] = "oob"
s = "foo,bar,baz"
values = s.split(",") = ['foo', 'bar', 'baz']
"|".join(values) = 'foo|bar|baz'

    #format
    "{} times {} is {}".format(a, b, a*b)
    "The value of pi is {:.2f}".format(PI) #float to 2 dp
#Abbreviated code
[ expr for val in original_list ] #creating a new list based off an old one
e.g. discounted_prices = [price * 0.9 for price in prices]

    #create lists on the fly
    for n in [x**2 for x in range(1,11)]:
        print(n)

    #with conditional
    [ expr for val in original_list if condition ]

    new_list = [x**2 for x in original_list if x > 0]

#FUNCTIONS
def name(a,b):
    <statements>
    return

#DICTIONARIES
d = {key:value}
d = {"first_name": "John",
"last_name": "Doe",
"zip_code": "60637",
"campaign": "Kang for President 2016",
"amount": 27.50}
d["first_name"] #get value associated with a key
d.get("first_name") #similar to above
d["zip_code"] = "94305" #assign new value to a key (even new)
"first_name" in d #check if key is in dictionary
del d["first_name"] #delete entry
for k in d #iterate over keys
for v in d.values() #iterate over values
for k,v in d.items() #iterate over both keys and values


#CLASSES

#Syntax
class Point(object):
    #initializer
    def __init__(self, x, y):
        self.x = x
        self.y = y
    #print
    def __repr__(self):
        return "({}, {})".format(self.x, self.y)

#Attribute x of object p1
self.x
self.p0.x #when creating compositions of classes

#Getter and setter
_x #is convention for a private attribute
class Point(object):
    def __init__(self, x, y):
        self.set_x(x)
        self.set_y(y)
    def get_x(self):
        return self._x
    def set_x(self, x):
        if not isinstance(x, (int, float)):
            raise ValueError("Not a number")  #making sure the user has inputed a number
        self._x = x

#Properties
<property_name> = property(<getter>, <setter>) #used to make private attributes accessible easily through p.x
                                                #instead of p.get_x()
x = property(get_x, set_x)
y = property(get_y, set_y) #to be added after the getter and setter methods

    #another way to do it directly
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        if not isinstance(x, (int, float)):
            raise ValueError("Not a number")
        self._x = x
    #Class method example
    def distance(self, other):
        return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)

    #Static attribute
class Client(object):
    next_identifier = 1
    def __init__(self, name):
        self.name = name
        self.identifier = Client.next_identifier
        Client.next_identifier += 1

#RECURSION
#base case and recursive case example
def factorial_r(n):
    if n == 1:
        return 1
    elif n > 1:
        return n * factorial_r(n-1) #recursive call

#SQL+Python
import sqlite3

conn = sqlite3.connect("file_name") #create connection with file
c = conn.cursor() #create cursor
c.execute("command") #call the execute method to perform SQL commands
c.commit() #save changes
c.fetchone() #retrieve single matching row
c.fetchall() #retrieve all matching rows
conn.close() #close connection
c.close #close cursor
def create_table():
    c.execute("CREATE TABLE IF NOT EXIST TableName(ColumnTitle REAL, ColumnTitle2 TEXT")
    #REAL, INT, TEXT

#Insert variables
def dynamic_data_entry():
    unix = #whatever
    datetime = #whatever
    c.execute("INSERT INTO TableName (unix, datetime) VALUES (?, ?)",(unix, datetime))
#Pull data
def read_from_db():
    c.execute('SELECT * FROM TableName WHERE ColumnTitle > 3 AND ColumnTitle2 = "Python"')  # * means all
    for row in c.fetchall(): #copy all the selection
        print(row) #you can reference the first column by row[0 ]


#SQLite Commands
INSERT INTO TableName VALUES(2342, 'text goes here') #insert values in order of columns
"INSERT INTO TableName (unix, datetime) VALUES (?, ?)",(unix, datetime) #insert variables
SELECT * #select all
SELECT ColumnTitle, ColumnTitle2 #select column
WHERE #followed by logic statement to restrict data you want to look at
UPDATE TableName SET ColumnTitle = 99 WHERE ColumnTitle = 8
DELETE FROM TableName WHERE ColumnTitle = 99

#SQL Queries
SELCT column_name, column name
FROM table_name
WHERE column_name <operator value> [AND/OR]...
WHERE NOT condition
ORDER BY column_name, column_name #ascending by default
ORDER BY column_name desc #ascending

#SQL Operators for WHERE
>
>=
<
<=
'<>' or != #not equal


BETWEEN...AND...
IN ('text', 'text')
LIKE 's%' #text that starts with s
LIKE '%s%' #s is in there
LIKE '_a%' #a is second character
LIKE '[ams]%' #first character is a, m or s

#SQL Aggregate Functions
COUNT 
MIN 
MAX 
SUM 
AVG 

    #example
    SELECT count(*) #or column name
    FROM table_name

    SELECT MIN(column_name) as column_alias, SUM(column_name) as column_alias...
    FROM table_name
    WHERE column_name = 3
#SQL GROUP BY and HAVING clauses tied to aggregate functions
SELECT
FROM
WHERE -optional
GROUP BY column_name #all selected columns must be either attached to aggregate or group by
HAVING aggregate_function(column_name) operator value #must be an aggregate function or part of the group by
ORDER BY -optional

#example

#MISCELLANEOUS

    #randomizer
    import random
    n = random.randint(0, 1000)

    #addition
    x += y <=> x = x + y

    #parameter default value
    def flip_coins(n, p_heads = 0.5):

    #lambda: instead of writing a short function and calling it as a parameter
    lambda <parameters>: <expression>
    lambda x: x*2

    #Filter
    filter(function, list) #outputs list with elements that satisfy function
    filter( lambda x: x%2==1, ls) 

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).