python programming.doc

22 Pages
216 Views
Unlock Document

Department
Electrical Engineering & Computer Science
Course
EECS 12
Professor
Y U Liu
Semester
Spring

Description
Chap 1 • computer o machine for executing a program o hardware • program o detailed step-by-step instructions o software  coding - the art of programing/making software • programing languages o high-level - what humans talk in  translated via compilers and interpreters  compiler  takes source code (program) and translates it to machine code (program that a comp can directly execute)  faster then interpreters, only need code once  interpreter  source codes directly to output  more flexible and portable  python o low-level - what computers talk in  machine language - #'s  assembly language - abbreviations (translated via assemblers)  not portable, hardware dependent o syntax - precise programming language form o semantics - precise programming language meaning • finding what can be computed o algorithm  recipe for victory o analysis  a mathmatical look at algorithms  will the algorithm be intractable (not practical) o experimentation  trail and error • • CPU - central processing unit o brain, where basic operations are carried out o fetch, decode, execute • memory o RAM - random access memory  main memory, gets lost when comp gets shut down o secondary memory  hard drive, CD, ect. • definitions o prompt - >>> o statement - complete command o command shell - interactive environment to interact w/an interpreter o parameters - arguments (stuff,in,here) 3 o module or script - where programs can be written and stored o programming environment - simplifies the process of programing (IDLE) o comments - # not read by python o variable - used when giving a name to a value (x=3) • interpreters o stimulates a computer that understands high-level language o analyzes and executes source code instruction by instruction o source code and interpreter are needed each time the program is run o more flexible then compiler since they can run interactively o more portable (runs on mac, pc) o python is an interpreter • Bit - one binary digit (0 or 1) • Byte - 8 bits • 1KB = 10^3 Bytes • 1Mb = 10^6 Bytes • 1GB = 10^9 Bytes • python stuff • input -> computation -> output • lines that start w/# r called comments • variables o data holders o can be reassigned as much as you want o the names you give them are called identifiers  must begin w/a letter or underscore  case sensitive o NameError happens when a variable w/out a value assigned is used o reserved words - identifiers python permanently has • expressions o fragments of code that produce or calc new data o literals: 2, 5+4 o simple identifiers can be expression • input o gets input from user and stores it as a variable • definite loops o variable for - loop index o range starts w/0 to whatever in sequence o list turns the thing into a list Chap 2/3 • IPO - input, process, output • identifiers o includes varibles o must begin with a letter or _ o case-sensitive o reserved/keywords - already identifiers (python claims them) • expression - produces or calculates new data o literal - used to indicate specific value (32) o strings - textual data ("hi","32") o identifiers can be expressions • operators o + - * / ** % (remainder), // (integer division)  7//3 = 2  3//7 = 0  17//9 = 1  12%11 = 1  11%12 = 11  101//100 = 1  -101/100 = -2 • keyword end o overrides adding an extra line o print('sup', end=' mh') print('yes')  sup mhyes • assignment statement o = • input statement o for a string: = input() o for a value: = eval(input()) • loop - executes a sequence of statements multiple times in succession o loop index - var after for o for odd in [1,3,5]: print(odd*odd)  1 9 25 • range() o a = list(range(3)) print(a)  [0, 1, 2] o a = list(range(0,12,3)) print(a)  [0, 3, 6, 9] • data - info stored and manipulated by comp programs o you can get a data type by typing type() o type(3)  o type(3.0)  • library - module that contains useful definitions o from library import * • bits o each bit has 2 possible values: 0, 1 (on, off) o typical comps have 32 or 64 bits o for a 32 bit int representation,smallest # it can store is -2^31 and largest is 2^31- 1 o numbers that exceed this get turned in scientific notation (kills accuracy a bit) • explicit type conversion o int(4.5)  4 o float(4)  4.0 o round(math.pi, 2)  3.14 memory organization • Bit - one binary digit (0 or 1) • Byte - 8 bits • 1KB = 10^3 Bytes • 1Mb = 10^6 Bytes • 1GB = 10^9 Bytes types of errors • syntax o something is wrong w/ur grammar o caught by interperater o easy to fix • run-time error o ex. divide by 0, program gets stuck o not caught by interperater o not so easy to fix • logic error • o error in design, even if the coding works • stored information - data o int - reserved word for integer o float - reserved word for floating point (fractional parts ex. 2.34) o integer divsion  10//3 = 3 o remainder division  10%3 = 1 Chap 4 graphics • Tkinter - pythons GUI (graphical user interface) module • object - a computational entity that combines data and operations o they kno and can do stuff o its data is stored in instance variables, and its operations are called methods from graphics import * def main(): win = GraphWin("Draw A House", 400,500) #name of window, pixels win.setCoords(0,0,20,20) #coordinates bottom left to top right win.setBackground('red') #sets background red p1base = win.getMouse() p2base = win.getMouse() #gets a mouseclick base = Rectangle(p1base,p2base) base.draw(win) #draws the object in window p3roof = win.getMouse() p3base = Point(p2base.getX(),p1base.getY()) #gets X and Y coordinates of mouseclicks roof = Polygon(p1base, p3roof, p3base) roof.draw(win) center = win.getMouse() window = Circle(Point(center.getX(),center.getY()), 1) window.setFill('blue') #sets fill color to blue window.setOutline('green') #sets outline color to green window.draw(win) text = Text(Point(center.getX(),center.getY()), 'this is text') #centers text on the window text.draw(win) inpt = Entry(Point(2,2),3) #entry point, a spot for a user to put things inpt.setText("0") #sets entry text inpt.draw(win) win.getMouse() ha = eval(inpt.getText()) #lets the program read the txt in the entry box window.move(ha,ha) #moves the circle that many units window2 = window.clone() #clones object window2.move(-2,2) window2.draw(win) win.getMouse() win.close() #closes the program main() • pg 108 starts a list of methods Chap 5 string, lists, and files (dis ex #1-4 prg ex #15, 16) • string operations o def main(): a = 'abcd efg' print(a[3],a[-1],a[4:]) #string indexing. the last is called splicing specifically print(len(a)) #gets length of string for ch in a: print(ch, end=' ') #iteration through characters main()  d g efg 8 a b c d e f g • lists (can be composed of not only numbers, but strings as well) o def main(): myn = [1,2,3,4] print(myn[2]) #gets the n+1 thing in the list myn[2] = 0 #changes the list thing print(myn) main()  3 [1, 2, 0, 4] o lists are mutable, their values can be changed:  x = [1,2,3] x[1:3] = "yes", "no" print(x)  [1, 'yes', 'no'] • Types of codes o ASCII (American Standard Code for Information Interchange)  uses the #'s 0-127 o Unicode  much larger standard, what python uses o getting code in python  ord('a') = 97 #gets the unicode number  chr(97) = 'a' #gets the symbol for the unicode number • encoder program o CB = open('codebook.txt','r') CB = CB.readline() #Read the codebook from the file MT = open("message.txt", "r") MT = MT.readline() #Read the plaintext from the file msg = "" #starts message off with nothing for i in MT.split(): #splits the string into substrings for each space for ch in i: new = CB[(ord(ch)-97)%26] msg = msg+new msg = msg+' ' msg=msg.rstrip() pos=(-3)%len(msg) #Rotates the -3 positions msg = msg[pos:]+msg[:pos] #adds the beginning (-3) outfile = open("encoded_message.txt", "w") #Writes the encoded message into a file called “encoded_message.txt” print(msg, file=outfile) # " " outfile.close() o def main(): instring = '83 110 33' message = '' for ch in instring.split(): #splits the numbers codename = eval(ch) #gets the number message = message+chr(codename) #adds the letter print(message) main()  sn! • list method o squares = [] for x in range(1,10): squares.append(x*x) #adds to the empty list each loop print(squares)  [1, 4, 9, 16, 25, 36, 49, 64, 81] • turning: o strings into values  int(" ")  eval can not have a leading 0, but int can  int('05')  5  eval('05')  error o values into strings  str(500)  '500' • usefullness of turning o day, month1, year = eval(input('enter day, month, and year numbers: ')) #gets 3 inputs at once and stores them date1 = str(month1) + "/" + str(day) + "/" #adds the recently converted strings together month2 = ['jan','feb','mar','apr','may','june','july','aug','sept','oct','nov','dec'] #list of months monthStr = month2[month1-1] date2 = monthStr+' '+str(day)+', '+str(year) print(date1, 'or', date2 + '.') • formating strings o .format()  print('grwar {0:10.2} done'.format(8.345))  grwar 8.3 done  print('grwar {0:0.5f} done'.format(8.345))  grwar 8.34500 done Chap 6 functions • advantages of functions o do not have to write multiple codes o easier to maintain if a change is desired inside the code • part of a program that creates a function - function definition • define functions before main o def happy(): print("Happy Birthday to You.") #defines the function happy def sing(person): happy() #uses the function happy happy() print("Happy Birthday dear", person+".") #adds an extra line, in which the has a changeable variable happy() def main(): sing('Marry') #sings w/changeable variable in the main function  Happy Birthday to You. Happy Birthday to You. Happy Birthday dear Marry. Happy Birthday to You. o def sumdiff(x,y): #gets 2 parameters sum = x+y diff = x-y return sum, diff #returns 2 values def main(): num1,num2 = eval(input("get it")) s,d = sumdiff(num1,num2) print(s, d) main()  get it 55,4 59 51 o def addinterest(balances, rate): for i in range(len(balances)): #figure out this for loop balances[i] = balances[i]*(1+rate) #balance[1] = balance[1]*(rate+1). balance[2] = ...so forth return balances[i] #returns balances 0 - len-1 def main(): amounts = [1000,2200,800,360] rate = .05 addinterest(amounts,rate) print(amounts) main()  [1050.0, 2310.0, 840.0, 378.0] o Chap 7 simple decisions • decision structures- statements that allow a program to execute different sequences of instruction in different cases • != is not equal to • if, elif, else o a,b,c = eval(input("enter 3 coefficents (a,b,c)")) #quadratic formula finder discrim = b*b - 4*a*c if discrim < 0: #if statement. if true this happens (these are called boolean expressions) print("no real roots") elif discrim == 0: #second if statement. if true this happens root = -b/(2*a) print("\ndouble root at", root) else: #if both are false, this happens discroot = math.sqrt(b*b-4*a*c) root1 = (-b+discroot)/(2*a) root2 = (-b-discroot)/(2*a) print("\nsolutions:", root1, root2) • exception handling • o try: except : o try: #the proggram trys to run a,b,c = eval(input("enter 3 coefficents (a,b,c)")) discrim = b*b - 4*a*c discroot = math.sqrt(b*b-4*a*c) root1 = (-b+discroot)/(2*a) root2 = (-b-discroot)/(2*a) print("\nsolutions:", root1, root2) except ValueError as exc0bj: #if something goes wrong it goes through these exceptions if str(excObj)=="math domain error": #one type of value error print("no Real Roots") else: #any other type of value error print("not enough coefficients") except SyntaxError: #this kind of error prints this statement print("not correct form, missing comma?") except: #another error prints this statement print("there is something wrong") • finding the max of so many values o n = eval(input("how many numbers?: ")) #user inputs how many numbers there are max = eval(input("enter a #: ")) #sets the first number user gives us to max for i in range(n-1): #loops through n times x = eval(input("next number: ")) #gets the value of the next number if x>max: #if this is true then: max = x #a new max is set print("largest number is", max) #prints the biggest number  how many numbers?: 4 enter a #: 2 next number: 4 next number: 3 next number: 5 largest number is 5 o or we could just use pythons build in max(x1, x2, x3) function... Chap 8 loop structures and booleans • while - the indefinite or conditional loop (both these functions print the numbers 0-10) o for i in range(11): #our old definite loop print(i) o i = 0 #new
More Less

Related notes for EECS 12

Log In


OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


OR

By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.


Submit