New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Matthew De Venecia
Matthew De Venecia

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Practice upload, but this is my actual outline for CS 101. It has many of the functions of Python.
Python Notes
Class Notes
strings, INT, floats, exceptions
25 ?




Popular in Python Notes

Popular in Computer science

This 13 page Class Notes was uploaded by Matthew De Venecia on Saturday August 20, 2016. The Class Notes belongs to CS101 at University of Illinois at Urbana-Champaign taught by Ryan in Fall 2016. Since its upload, it has received 7 views. For similar materials see Python Notes in Computer science at University of Illinois at Urbana-Champaign.

Popular in Computer science


Reviews for Practice


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 08/20/16
Strings # letters or numbers enclosed in single or double quotation marks ex; x= “Hello” Methods:  stringname.count(“character”) #returns the number of the specified character within the specified string  stringname.replace(“character1”,”character”)#replaces all occurences of the first character with the second  stringname.find(“character in string”) #provides index of the first occurrence of the character  len(string name) #provides the length of a string  stringname.swapcase() #switches the case of the letters in a string from upper to lower and lower to upper  stringname.upper() #Upper cases the letters in a string  stringname.lower() #lower cases the letters in a string  stringname.title() #Upper cases the first letter of every word in a string and lower cases the rest  stringname.isalpha() #Returns True if the string is made entirely of letters  stringname.isnumeric() #Returns True if the string is made entirely of numbers  stringname.isdigit() #same as isnumeric  stringname.split(“character”) #provides a list from a string by splitting it up at the specified character  stringname[int] #returns the character at the desired index value (start counting at 0 in python)  stringname.strip(character)# gets rid of the corresponding character at the beginning and end of the string. If no character is specified, it removes the white space at beginning and end of the string Operators:  + “string” #concatenates strings (puts them together)  * int # returns a string using the orginal repeated the indicated number of times Other:  String formatting: substituting a string into a string with % o Ex adjective = “beautiful ” o variable= “world” o print “Hello %s %s” % (adjective,variable) #will print “Hello beautiful world” o use %s to insert strings, %f to insert floats, and %i to insert ints Lists #values separated by commas within enclosed brackets ex; x =[“hello”, 4, 7.0, 15] Methods: ### Warning: never use assignment with list methods. Python will return a None Type. Also, Using things that have dot notation: like .append() or .sort() changes the list itself and gives It a new value. The list methods don’t return anything, they just change what is inside of the list itself. Ex: a=[1,2,3]. a.reverse() will change the list to [3,2,1] and therefore changes the value of a. However, it did not return anything.  “any character that you want between the words of the string”.join(listname) # Returns a string with a delimiter o ex: a=[“a”,”b”,”C”] o “3”.join(a) #will return “a3b3c”  listname.append(any data type) # will add the inserted data type to the end of the list  listname.extend(listname2) # appends the contents of listname2 to the end of listname  listname.sort() # sorts the values in the list in numerical order or alphabetical order if the items are strings (cannot sort list with ints/floats and strings. If a there is a number in the string, numbers come before letters).  len(listname) #returns the quantity of the number of items in the list  listname.reverse() # reverses the order of the list  listname [start : end : step] gives the items starting with the value at index start, and ending with index (end-1) counting by every step index. To reverse a list, step should be -1. This works like the range function  sum(listname) # only works if the list is made of ints, returns the sum of those values  del listname[index number] # deletes the item at the desired index Operators:  + # adds to list together to form one big list  * # returns a list with the original items repeated and added to the end Important Notes:  By assigning a variable to another vaiable that was assigned to a list, it creates an alias, as in the list is now represented by two different variables. o Ex a=[1,2,3] \n b=a. #now the list [1,2,3] is represented by a and b. If you use a list function on either variable, it will change the value of the list itself o If you want to copy a list, just slice it from beginning to end. Ints and Floats and Complex Numbers: Ints # positive or negative whole number values without a decimal ex; x=3, x= 0, etc. Floats #positive or negative numbers that have decimal points ex; x=3.4, x= 0.0, etc. Complex #has real and imaginary components. In python, j is used to represent imaginary numbers. Ex; 5+4j is a complex number  Complex.real #returns the real part of a complex number(without j) and no parentheses needed  Complex.imag #returns the imaginary part of a complex number (with j) Operators:  / #divides ints and floats. Always returns a float value  // #floor division always rounds down and returns an int value  * #multiplies ints and floats. Only returns ints if two ints are multiplied together  ** # raises ints and floats to the indicated power. Only returns ints if an int is raised to the power of an int  % #modulo: returns the remainder of a division operation. Only returns ints if two ints are divided by eachother  - # Subtracts ints and floats. Only returns ints if two ints are subtracted by eachother  + # adds ints and floats. Only returns ints if two ints are added together. Tuples: #exactly like lists, but they are immutable (cannot change the value of it with .append(), sort(), and reverse() functions). Denoted with parentheses instead of brackets  ex: t=(1,2.4,”hi”) #tuples don’t need parenthese, but they are just there to be helpful  you can use almost every list operator on them, but not the ones that change length: .append(), .extend(),.join(), etc.  a tuple can go on the left hand side of an assignment statement o ex; one,y,hello=(1,2.14,”Hi”) o now one=1, y=2.14, hello=”Hi”. The value on the right can be a tuple or a list o ^convenient for swapping variable values o can be used in return statements allows multiple values to be returned at once o can use with string formatting: o ex “%i %i %i” %(1,2,3) # the string is now “1 2 3” sum(tuplename) #only works if tuple item are ints. Returns the sum of the items. Notes:  items inside tuples are called literals Booleans #has either a value of True or False You cannot have Boolean operators between two different data types. (ints and strings, strings and lists, etc.) Strings: #Compares Strings as if they were in a dictionary. If the string has numbers inside, numbers come before letters. Ex.”s” > “badadsfadsfa”, “3”< “sadfas3”, etc. Ints: #compares the values of the ints Lists and tuples # only work with the == and != boolean operators. Nothing else. Floats: #WARNING when using the == operator with different float expressions, python will usually return False because it does not read the floats as exactly the same value. Use the numpy function isclose() to deal with this problem. Ex: 1.1-0.8==0.3 will return False. numpy.isclose(0.3,1.1- 0.8) will return true  > #greater than  < #less than  >= # greater than or equal to  <= #less than or equal to  == # equal to (not assignment)  != # not equal to  not # returns False if True ad True if False. Always evaluated before and and or  and #returns True only if it is between True statements  or #returns True if next to a True Statement o order of operations: not, and, then or If the Boolean expression is true, it will return True, and will return False if the expression is false (capital T and F are important) None #literally nothing Loops #runs the block of code after the : according to the type of loop  while Boolean value : #executes the subsequent block of code repeatedly as long as the Boolean value is true  for insert any variable in string/ list/ any iterable type : # runs through each individual character or item within the iterable data type and runs the subsequent code for each item  if Boolean value : # executes the subsequent block of code if the Boolean value is true  else: #paired with if and elif statements and executes the subsequent block of code if their Booleans are false  elif Boolean value : #used after an if statement that is false. executes the following code if the Boolean value is True  continue #works with the for loop and if, elif, and else statements that skips the next iteration of a loop o ex. for x in [1,2,3,4]: o if x%2==0: o continue #does nothing and skips the iterations of the loop where x is even Dictionaries # an iterable container type (like a list)that provides custom indexes created by the user instead of just integers Formatting:  Ex. X={key1:value1, key2: value2}  #will now associate key1 with value 1. Functions:  del dictionaryname[key] #deletes specified key and value  dictionaryname.keys() #will return the keys  dictname.values() #returns the values  keyname in dict #returns True if specified key is a key in the dictionary  dictionaryname.items() #returns keys with values Notes:  Dictionaries are unordered container types ( can be made of any other data type)  They map keys to values where keys are basically customized indexes. Can be any data type  Now you can index a value with the assigned key  Ex: x={“potato”: “fries”, “tomato”: “ketchup”} o x[“potato”] #will return “fries” because the index “potato” associated with fries.  You can also reassign keys to a value of any datatype o Ex. x[“potato”] = (1,2) #the “potato” index is now associated with the tuple (1,2)  If you want to add a key/value pair to a dictionary, simply assign the value to the key as if it already exists in the dictionary o Ex. #”key3” does not exist in the dictionary o dict[“key3”]= “value3” o #now it does exist within the dictionary with a value of “value3”  It may be useful to count how many times a character occurs in a word. Use a dictionary as an accumulator to do this. Functions:  for variable or tuple in enumerate (iterable) # gives index numbers to iterables o ex: y=”ABCD” o for a,b in enumerate(y): #assigns the index number to a and the index value to b. alternatively, you could assign one variable to the tuple (index#, y) and print it to get the same result o print (a,b) #will print (0,”A”) (1,”B”) (2,”C”) (3,”D”)  for variable or tuple in zip(iterable,iterable): #allows you to go through 2 iterables at once and returns a tuple. If one iterable is longer than the other, the zip stops once it has iterated through the shortest iterable. o ex: x=[1,2,3,4] y=”ABCD” o for a,b in zip(x,y): #a is assigned to items in x, b is items in y. alternatively, you could assign one variable to the tuple (x,y) and print it to get the same result o print (a,b) # will print (1,”A”) (2,”B”) (3,”C”) (4,”D”)  range(start:end: step) # provides numbers (not a list, but range is its own datatype) starting with the start value, increasing by the step value, and ending with (end – 1).  open(‘filename’,’r or w’) #reads (r) or writes(w) a file (filename). (if ‘r’ or ‘w’ not specified, ‘r’ is default) o with open(‘filename’,’r or w’) as variable: #stores the file in the indicated variable. The subsequent code would need to be indented just like a loop would. Also closes the file without need of the close function o filename.readlines() # reads the lines of a file and creates a list with the items being each of the lines in the file o filename.write(string) # adds the string to the file, but only works If the file is opened with “w”  close(‘filename’) #closes the opened file after use so it does not take up memory Other:  main()# Allows code to be imported or run from the command line as a script o __name__ #name of the module or script that is currently being worked on.  assert Boolean # tests wether the Boolean value is true. Useful fo testing code  import function from library #allows a function from a library to be used without dot notation o import library #allows the entire library to be used, but dot notation must be used  ex: math.pi() #holds the value of the pi function from the math library  Type Casting: Changes the type of the data, but is not permanent (data goes back to original type after the line is read unless stored in a separate variable) o list(“string”or tuple) #will return a list with the characters of the string as its items. Also converts tuples into lists. Does not work with ints o int(float) # returns floats as ints o float(int) # returns ints as floats o str(data type) #returns any data type as a string (brackets/parentheses will be included inside of the string if the data type is a list, tuple, dictionary,etc.) o tuple(“string” or list) #returns the characters of a string or list as a tuple  Slicing: Can be used with any iterable type, except dictionaries (list,strings,tuples,etc.) o Datatypename[start:end: step] #slices the datatype at the start index, ending with the end-1 index and counting by the indicated steps  # #starts a comment. Python interpreter ignores anything on the right side of this in a python line. Allows you to explain what the code does/ make notes for yourself while not affecting the python code  “””this is a docstring””” #use triple quotes to create a docstring. serves the same purpose as a string, put you are able to use multiple lines. Modules # collection of Python specialized functions, variables, and types. These are not a part of Python’s core language, but they are added by importing them  import modulename #imports the indicated module so that its contents can be used o modulename.item in module # ‘.’ is the attribute operator that allows the item in the module to be used  ex: import math  math.pi #returns 3.1415926…  from modulename import moduleitem #allows the module item to be used without using the attribute operator, but ONLY IMPORTS THAT ONE ITEM, NOT THE ENTIRE MODULE o ex: from math import pi o pi #will return 3.1415926….  list of python modules: o math, cmath #provides many math related functions and values o random # o csv # manipulate csv files o sys, os #access operating systems o time, datetime # allow you to parse times o itertools # o logging # o #note, there are downloadable modules that are not included in python Matplotlib.pyplot Module: # plotting library that has an interface that imitates Matlab o useful tip: use an “import as” statement to abbreviate attributes  ex: import matplotlib.pyplot as plt #always import as plt if anything  #plt acts as matplotlib.pyplot attribute and shows the graph Functions of this module:  .show() # shows a graph  .plot(variable representing x axis data,variable representing y axis data,’shape or color’, label= “label title”) #provides axes for the graph with indicated shape or color (‘r.’ will provide red dots as the plot points) and label will give the resulting data points a name and will be indicated on the legend as such  .scatter(x,y, label=“string”, color=‘colorindicator’, marker=‘marker indicator’) #similar to .plot. creates a scatter plot instead of a line graph  .xticks(x,list of strings) # replaces the x axis scale with strings  .yticks(y,list of strings) #replaces the y axis scale with strings  .bar(xlist,ylist,label=string)# makes a bar grap with the y values as the height of the bar and the x values as the coordinates. Use with .xticks to make a bar graph with names.  .legend() #creates a legend for the graph  .xlabel(“string”)#labels x axis  .ylabel(“string”)#labels y axis  .matshow(arrayname) #pyplot function that dislplays a 2d graph of an array, need .show() function to show the result  .title(title here) #gives graph a title  .hist(variable) # creates a histogram for the indicated variable and counts the frequency of how often an item occurs in the list or iterable of integers or floats Create a bar graph by using 2 lists of ints as your x and y variables. Create a chart by having a list of ints as your x variable and a list of strings as your y variable  ex: x=[1,2,3]#WARNING DOES NOT WORK. ASK FRIEND HOW TO DO THIS  y=[“anna” , “bob”, “joe”]  matplotlib.pyplot.plot(x,y) #you can’t do this, the arguments must be list of integers. use plt.yticks() to do what you want this to do.  %matplotlib inline #makes the plot pop up in the browser instead of its own separate window csv module # allows you to manipulate csv files with special functions and data types Functions of this module:  .DictReader(“opened file”,delimeter= “desired delimeter”) # creates a list of dictionaries of the indicated opened file by obtaining keys in the header of the file and matches values to keys by separating by the indicated delimeter (default is a comma). Numpy module # extends python’s numerical capabilities. Designed for more efficient computation and manipulating arrays and matrices #always import as np if anything  np.array(list or (tuple of lists)) # creates an array out of the indicated lists (input more than one list to create a multidimensional array): similar to lists, and can be indexed and be manipulated o arrays have length (you can use len() function) o indexing arrays: index by row first then column  ex a[1][2] will retrieve the item in array a in the 1 row and 2ndcolumn #### question on exam: x=np.array([1]*2) # multiplication duplicates the items in the list x+=1 # adds 1 to each item in the array #x now is array([2,2])- Data types of Numypy:  Booleans  ints (I,16,32,64 bits)  floats (I,16,32,64 bits)  complex (I,16,32,64 bits) # with ints, floats, and complex numbers, you can specify the accuracy of the object. More bits= more accurate, but will take longer to compute. Default is 64 bits  .dtype #  .shape #provides the shape of the array ex. x=np.array (a,dtype=np.float64) x.dtype #returns the datatype of the items in array x  np.arange(start,end, step)# returns an array over a range starting at start ending with end -1 (last one not included) and increasing by step just like the range function for lists  np.linspace(start,end, quantity,dtype=np.float or int numpy type and length) #returns array of evenly spaced values starting at start ending with end (number included) and providing quantity number of points between the starting and ending value with the datatype specified  np.zeros ((tuple)) # provides the specified number of zeroes in an array o ex. x=np.zeros((10,10)) # Will create a ten by ten array of zeroes that are floats  np.ones((tuple)) # works like the zeros() function  np.isclose(float1,float 2) #used to validate Boolean values for floating point numbers. If the 2 indicated values are very close to one another, this function will return True and False otherwise  np.mean(list/tuple)#gives average  np.median(list/tuple)#gives median  np.random #type of numpy functions that generate uniformly distributed randomness in the form of arrays o np.random.rand(tuple) # generates a matrix with dimensions of the tuple indicated. The items in this matrix are pseudorandom numbers (seemingly random numbers) o np.random.randn(tuple) #creates an array sampled from standard normal distribution (a bell curve). More distribution simulaitons are available o np.random.choice (arrayname,number of choices, size= int, replacement=true or false) # generates number of choices random samples from a 1-D array (arrayname) o np.random.shuffle(arrayname)# randomizes the order of a 1-D array, randomizes the order of the rows in a multidimensional array o np.random.randint(start,end) #generates a random int within the range of start to end-1.  Numpy notes:  arrays can be multidimensional  making a 3x2 array (3 rows 2 columns) o a=[[1,2],[3,4],[5,6]] #list of lists o b=np.array(a) # will print a as an array of 3 rows and 2 columns o np.array(1) *3 #will return 3 because 1 is an int o np.array((1,)*3) #wil return (1,1,1) because 1, is a tuple  arrayname[row][column] # index the item in the array at the specified location. Index columns by counting starting with 0 Time module # tells you how long it takes for you code to run. : import time and do your thing. Exceptions: Exceptions Represent computation reaching an exceptional (unexpected or unusual) state o If exception is not addressed or fixed, returns a trace: copy of the lines of code up until where the exception caused the code to fail  try: # allows you to write a contingency plan just in case you run into an exception the subsequent block of code is what python tries to run. If it fails, python goes to the except code  except: # paired with try statements and executes the subsequent block of code if the try code fails o ex: try: o a=[1,2] o print(a[2]) o exception: o print (“oh no!”) #prints oh no because the try code failed. If exception was not here, python would return a trace  raise Exception (“string here”) #allows you to cause an exception and prints the string along with a trace.  WARNING: exception statements will execute any time the code fails EXCEPT when there is a syntax error itertools # python library for manipulating iterators: loop over iterators “succinctly and efficiently” Must import before use  itertools.product(arrayname1,arrayname2) #creates tuples of each item in arrayname1 paired with each of the items in arrayname2 o ex: a=”abcd” o b=”12345” o for x in itertools.product(a,b) o print (x) # will print tuples (“a”,”1”) iterating through 1-5 and doing the same for each letter in a  itertools.combinations(listname, size) #iterates through all subsets of size n with subset items being sorted. ^prints all possible ordered subsets with the size indicated o ex. a=[1,2,3,4] o for x in itertools.combinations(a,3): o print(x) #prints all possible ordered combinations of 3 items for 1,2,3 and 4 (one thing it would print is (1,3,4) >impossible combination (3,1,4) because 1 comes before 3  itertools.permutations(iterablename,size) #returns all possible combinations of size indicated of the items in the iterable. Not restricted by order o ex:  itertools.permutations('ABCD', 2) ­­> AB AC AD  BA BC BD CA CB CD DA DB DC o ^Basically, a more powerful form of combinations() Optimization: # given a function f(x), find x such that f(x) is maximzed/ minimized: goal is to search through the domain for the optimum x Heuristic optimization # technique to trade optimality for speed.  Not guaranteed to find the best solution nor is it guaranteed to be efficient.  Takes a shortcut= take risks.  Finds a “good enough” answer  When using these approaches, it is possible to get stuck at a local optima (or maximum).  The ideal is to find the global optimum # only method that can be used to get this is the brute force method: trying every possible combination (aslo called an exhaustive search)  Random search: method for sampling for heuristic optimization o Randomly sample the domain of a function: might not find the true optimum, but might find one that is good enough Greedy Search: method for sampling for heuristic optimization o Ignore the overall problem o Pick the “best” partial solutions individually one by one o Keep picking until we can’t improve anymore (like ranking apples from tastiest to least tastiest and taking the better ones until you can’t carry anymore) Hill climbing: #improve upon current solution. Used to find the best solution from a random search o Keep track of our “current” solution o Change one elemnet of the solution o If change improves the solution, this is new “current” solution o Repeat until we can’t improve anymore Steepest Ascent Hill climbing o Like hill climbing, but your’e incrementally changing all elements of the solution o Pick the change with the best improvement or steepest slope Elements of modeling application:  Define the problem  Define the code using provided formulas  Calibrate the code by running it and comparing the code to known values #using assert is useful for this  Apply your code and analyze any error  Expand its function General Notes and tips: o write code that is easy to read: o give variables descriptive names o annotate/ describe code with comments # o Use docstrings o Use \ to continue writing your code on different lines. Python will read it as if its on the same line. o Do not use magic number: numbers that are a vital part of the function, but you don’t write down what it does and you did not assign it to a variable. o State Variables # a collection of variables describing the current state of the system o Model pseudocode o set constants #initial state variables, gravity, height, etc. o set state variables = to initial state variables o The more calculations your code runs through, the longer it will take to run o Pseudorandom numbers(PRNG): a program that generates seemingly random numbers starting from an initial input (seed) and the subsequent outputs being generated from the previous calculation Debugging: 1. How do I know it isn’t working? 2. What do I expect it to do? 3. What is my code doing instead? Why? 4. Errors = clues. think about it IMPORTANT NOTES:  WHEN WRITING CODE, TEST EVERY VALUE YOU CALCULATE TO MAKE SURE IT PRINTS OUT WHAT YOU WANT IT TO


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.