Study Guide for Prelim 1
Study Guide for Prelim 1 CS 1110-002
Popular in Intro to Computing using Python
verified elite notetaker
Popular in ComputerScienence
This 12 page Study Guide was uploaded by Eunice on Tuesday March 8, 2016. The Study Guide belongs to CS 1110-002 at Cornell University taught by Lee, Van Loan in Spring 2016. Since its upload, it has received 148 views. For similar materials see Intro to Computing using Python in ComputerScienence at Cornell University.
Reviews for Study Guide for Prelim 1
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: 03/08/16
CS 1110 Spring 2016 Van Loan and Lee Prelim 1 Study Guide (Class and Textbook Notes) Compiled Class Notes Assignment Statement and Types o Variables, Expression, Assignments r and A are variables define variable: a named memory location, like a box, holds a value define = : assignment statement variables are used in an expression o expression: evaluated and then stored under assigned variable o ex. 3.14*r**2 order is important variable must be assigned a value before it is used and evaluated in an expressed Assigning is different from “equal to” Difference between math and python Overwriting works <variable name> = <expression> Evaluate right item and store it in left item Rules of naming variables Name must be digits, uppercase letters, low care letters and _ (underscore) Must begin with a letter or _ Expressions: use parentheses if there is ambiguity o Types Python views numbers as a type int: integer, integer arithmetic is exact float: float arithmetic is usually inexact literals Int: ex. 12 Float: ex. 12.0 Str: ex. abc Ints and floats o Integers v. decimals and python arithmetic Integer division: A/B = Q and R (a remainder) >>> r = x%y r is printed as a remainder Decimal division: A/B = Q (a decimal) Clock arithmetic Float can represent an integer even though it is not an integer type Operations Int: + - * / unary- ** % Float: + - * / unary- ** Str: + o Strings Strings: quoted characters a single character is a string define subscripting: characters in a string can be referenced through their indices (USE BRACKETS) “t is a slice of s” [x:y] will return characters with indexes x to and including y-1 Concatenation: string analog of addition (unlimited) Data is provided often in strings and can be converted into floats/ints writing a code o Comments begin with a “#”, guidelines o Docstrings: three quotation marks “”” o formatting options (not on exams) %f print ‘x=%A.Bf’ %x where A and B are numbers and x is a float it will print x with A number of spaces until x’s decimal point and B number of digits after the decimal point will be displayed %e same as %f except converts to scientific notation %d print ‘x=%Ad’ %x where A is a number and x is a integer prints x with A number of spaces before x (including x’s digits) %s A = ‘string1’ print ‘%s ‘string2’ % A concatenates ‘string1’ and ‘string 2’ o Import functions from modules Conditional execution o If-Else o The punctuation and indentation are essential If something isn’t indented, it’s a new statement/task that will be executed o You do not need variables, you can have expressions If boolean expression: Statements to execute if the expression is True Else: Statements to execute if the expression is False o When comparing two expressions to see if they have exactly the same value, use == = is an assignment == is a comparison o < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (is equal to), != (not equal to) No spaces Alphabetical/string comparison: Comes first in alphabet: < capital letter is < a lower case letter 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij klmnopqrstuvwxyz o If-Elif-Else construction Elif: “else if” An input is evaluated by each condition, until it reaches a comparison that verifies as True Once a condition is evaluated as True, it stops and executes the statement o If boolean expression: o Statements to execute if this expression is True o Elif another Boolean expression: o Statements to execute if this expression is True o Else: o Statements to execute if all above expressions are False len function: N = len(string) Logical operators x y x AND y true true true true false false false true false false false false x y x OR y true true true true false true false true true false false false and: both statements must be true for the overall statement to be true or: at least one of the statements must be true for the overall statement to be true not: o not true = false o not false = true function o m = fct(x,y) fct: name given to a function x, y: both are arguments arguments may be expressions o python functions: max, min, abs, round o when you use a function that doesn’t return a value, it’s void and when the function is assigned to a value, printing that value will print “none” o mechanics of how functions work calling a function is different from defining a function examining fruitful functions (those that return a value) call frame o when a function is called in a program, the process steps through the function body local variables are variables used within a defined function’s environment modules o common: math, string, random, numpy, scipy, timeit, urllib2, PIL (image processing), datetime o dot notation [module].[function]() advantage being that if you are using multiple modules that each have functions with the same name, then dot notation clarifies o “from [module] import [function]”: dot notation no longer required/won’t work “from math import *”: imports all o functions: math.floor, math.ceil, math.round building functions o >>> def function(argument): [header] o >>> body statement o >>> more body statements o >>> return a variable o authors of a function must make available the how-to-use information through docstrings and comments o rule 1 and 2 module starts with authorship comments and an explanation #module name #author(s) names (and netid) #last modified date “””a doctstring: a module to ____””” o rule 3. each function starts with a docstring “specification” short summary that states what the function returns (post condition) longer prose can be include which gives more useful info precondition: conditions that the argument must satisfy if the function is to work procedures o procedures are functions that do not return values, they “do something” functions can call other functions simple graphics: o makewindow first: get a canvass o optional arguments don’t require a certain order, they’re like synonyms o module has data, 13 different colors o showwindow o drawrect must tell the program: the center of rectangle horizontal dimension vertical optional fill color o default is no color width of perimeter color of perimeter highlight rotation angle (theta=degree) o drawdisk must define center radius o drawstar also needs a center and radius o drawlineseg need to define the start and end points can define the color and width o drawtext define: the location of text the string can tell: the color and size o drawTile define the center, the radius, three colors of 3 objects in the tile (x,y,r,c1,c2,c3) color set of three number between 0 and 1, number represent the amount of [red, green, blue] a list of length three methods o 3 string methods count: how many times does string t occur in string s returns an int value find: first occurrence of string t in string s if a -1 is returned then nothing was found otherwise, returns an int value Boolean device: in o s1 in s2 o true: there is an instance o false: there is not replace: in string s replace all string s1 with string s2 note: ‘’ is a null string returns a copy of the string s with the appropriate replacements o note, a copy not a changed original if s1 is not a substring of s then the returned string is just s if there are overlapping substrings then the first found is replaced o xxx, replace xx with o = ox NOTE: strings are immutable o their values cannot be changed o must slice and concatenate in order to apply replace function check slides for example evaluations s.isalnum: all numbers or alphabet s.isalpha: all alphabetical s.isdigit:all numbers o dot notation instead of usual function-call syntax n = count (y,x) [old] n = x.count(y) [dot] formally: nameofstring.nameofmethod(argument1, argument2, …) don’t use “or”; use commas to separate arguments iteration o repeating a script using loops for: for a certain object in another object, do a certain execution “for x in y:” LOOP BODY o iterating through a string vs is a range letters/characters/string: “for c in s”: do thing in loop body number/quantities: “for k in range(n)”: do thing in loop body o counting: a type of summation “for k in range(there, here): print k” “for k in range(there, here, -1): print k” this counts backwards o the while-loop open-ended iteration: do a certain execution until a certain characteristic/event appears “[code that comes before the loop] while [a Boolean expression]: o [the loop body] [code that comes after the loop]” random simulations o random in cs: means no discernable pattern o random Module random.randint(a,b) gives back a random integer between a and b, including a and b renaming a function o “from random import randint as randi” random.uniform(a,b) random floats random.normalvariate(mu,sigma) o short cut x += 1 same as x = x + 1 o repeatability of experiments random.seed reset the algorithmic process and fix the random generation process’s start point o having the same start point means that the same random sequence will be applied and the simulation can be repeated Compiled Textbook Notes (in order of assignment) o 1.1: high level vs. low level language o 1.2 Program: sequence of instructions for the performance of a computation Input: get data from keyboard, file or other device Output: display data or send data to file or device Math: perform basic math operations Conditional execution: check for certain conditions and execute appropriate code Repetition: perform some action repeatedly, usually with some variation o 1.3 Bugs: programming errors Syntax: structure of program and rules of structure, an error will prevent the program from running because it can’t be parsed Semantic error: program will run successfully but action will be incorrect Runtime errors: will appear after program has started to run o Called exceptions: these errors are rare Debugging: finding errors o 1.4 Syntax rules Tokens: basic elements of language (ex. words, numbers, chemical elements) Structure o Parsing: process of understanding structure of sentence Natural vs. formal Ambiguity: formal language statement has exactly one meaning regardless of context Redundancy: formal languages are more concise, less redundant because there’s no ambiguity to clarify Literalness: natural languages use idioms and metaphors o 1.5: Print statement o 1.7 Portability: a property of a program that can run on more than one kind of computer Algorithm: process for solving a category of problems o 2.1 Value: what a program works with Types o String (str): a string of letters enclosed in single quotation marks o Integer (int) o Floating-point (float): numbers with a decimal point o 2.2 Variable: a name that refers to a value Assignment statement: creates new variable and gives them values o 2.3 A variable can include numbers, letters and _ but must begin with a letter If there is a space in a variable name, python assumes two operands and no operator PYTHON 2 KEYWORDS and as assert break class continue def del elif else except exec finally from global if import in is lambda not or pass print raise return try while with yield o 2.4 Operators: special symbols that represent computations + - * / ** Floor division: both of operands are integers, result is an integer (rounds down) Operands: value the operator is applied to o 2.5 Expression: combination of values, variables, and operators Statement: unit of code that the python interpreter can execute (ex. print and assignment) o 2.6: Script vs interactive mode o 2.7: rule of precedence: (math) PEMDAS o 2.8: Concatenation: joining strings by linking end-to-end o 2.9: Comments: notes added to programs to explain in natural language the function of the program (start with “#”) o 2.11: State diagram: graphical representation of a variable set and the values referred to o 8.1 String: sequence of characters Each character is assigned a number starting with 0 Index: expression in brackets that uses character number o Index must be an integer o 8.2: len: built-in function that returns the number of characters in a string (length) o 8.4 Slice: segment of string Empty string: result of using a slice [n:m] where n=m or n>m 5.1 Modulus operator: works on integers, yields remainder from 1 st operand divided by a 2 nd o Symbol: % extract the right-most digit(s) from a number o x%10 (last digit) o x%100 (last two digits) 5.2 Boolean expression: expression either true or false (==) o True and False are type bool; not strings == is a relational operator o Others: x! # x is not equal to y =y x> # x is greater than y y x< # x is less than y y x> # x is greater than or =y equal to y x< # x is less than or equal =y to y 5.3 Three logical operators: and, or, not Technically, operands of logical operators should be Boolean expressions 5.4 Conditional statements: check conditions o Boolean expression after if: the condition If true, then indented statement is executed; if not, nothing happens o Function definition structure: a header followed by an indented body (compound statements) o If you need to have a body with no statements as a place keeper: use pass statement 5.5: if-else A form of the if statement: alternative execution o Two possibilities and condition determines which one is executed o Since the condition is either true or false, only one of the alternatives will be executed Alternatives: branches 5.6: elif More than two branches needed: use a chained conditional o Elif: “else if” 5.7: Nested conditionals 5.11 Raw_input: input from keyboard o Program stops and waits for user to type something; once the user presses return/enter, the program resumes o Raw_input will return what the user typed as a string 3.1 Function: named sequence of statements that performs a computation Functional call: …calling said function argument of the function: expression in the parentheses a function “takes” an argument and “returns” a result (the return value) 3.2: functions int(), float(), str() 3.3: modules o contains predefined functions and variations o to access these use dot notation module.function() 3.5 function definition: specifies the name of a new fct and the sequence to execute when fct is called o def functionname(): 1 o [detail the sequence] 2 1. header 2. body empty parentheses: no argument end function by entering an empty line the value of functionname() is a function object, type is function 3.7 flow of execution: order in which statements are executed o begins at the first statement, one at a time, from top to bottom o follow where the function is called (Detour) which executes the body of the function and then the program continues on 3.8: parameters: inside the function () arguments are assigned variables 3.9: locality: variable inside function and parameters works only in the function 3.10 stack diagram: shows value of each variable and the function each variable belongs to function is represented by a frame o a box, function name next to it, parameters and variables inside it the list of functions in an error is the traceback: what file, what line and what functions in which the error exists 3.11 fruitful functions: fct that yields results (math functions) void functions: fcts that perform an action but don’t return a value (ex. printtwice()) o 6.1 fruitful function “return” statements includes an expression o return from the defined function and use the expression given as a return value in conditional: o the code that appears after a return, flow of execution never reaches it: dead code o if all the conditionals fail to apply then “None” is printed o 6.3: composition: calling one function from within another o 8.3 traversal: select a character, do something, continue while loop (7.3) while a certain condition holds true, repeat script can be used to create a find/search function (8.6) for loop for a certain condition, do an action can be used to create a counter (8.7) o 8.8 method: takes arguments and returns values but with different syntax function(argument) vs. argument.method(parameter) method call: invocation optional arguments method(argument[, optionalargument[, optionalargument2]]) o 8.9 “in”: Boolean operator takes two strings and returns True if the first is a substring of the second o 4.2: repetition o 13.2: random module: pseudorandom o 6.4: Boolean in function o 7.1: multiple assignments assigning a new value to a variable o 7.2: changing the value of a variable initialize update with +1: increment -1: decrement o 7.5: sqrt o 7.6: algorithms o 7.4: break: stopping a loop when this happens, as opposed to keep going until that happens
Are you sure you want to buy this material for
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'