Concepts of Computing
Concepts of Computing ECS 010
Popular in Course
Popular in Engineering Computer Science
This 27 page Class Notes was uploaded by Ashleigh Dare on Tuesday September 8, 2015. The Class Notes belongs to ECS 010 at University of California - Davis taught by Annamaria Amenta in Fall. Since its upload, it has received 17 views. For similar materials see /class/187776/ecs-010-university-of-california-davis in Engineering Computer Science at University of California - Davis.
Reviews for Concepts of Computing
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: 09/08/15
ECS 10 HO 11102008 Announcements I Program 5 due st l0pm I Next midterm Mon Nov I7 I Midterm is open book open notes Bring sample programs from class your programs etc I Bring a Scantron Removing Empty Lines I Sometimes input files include annoying empty lines I An empty line consists of a singe newline nquot character I Let39s write a program that removes empty lines from any file I Let user enter name of file then open it Crashes if File Name Wrong I The program has no way of checking whether the user typed the name of a real file except by trying to open it I But we never want to write programs that crash I Similar to problem we had with getting numbers from the user if they gave us a string that could not be converted then the program would crash Exceptions I Python mechanism for handling user input that might crash the program try inFile openinFileName quotrquot except Gets here if we cannot open the file print quotCannot find filequotinFileName inFile None Exceptions try Command that might cause a crash except Executes this block if a crash would have happened 11102008 Converting Strings popStr rawinput Enter the population t ry pop floatpopStr Try conversion exce t Conversion failed print Not a number pop None if pop None Put rest of program here When to Use Exceptions I Use exceptions to handle input from the user or sometimes from files which you cannot control any other way I We have seen the most common scenarios file names and converting userinput strings to numbers Otherwise exceptions should be rare I Most crashes are because there is a something wrong with your program Fix the bug don39t put it inside an exception Back to Removing Blank Lines inStr None Empty string means end of file while inStr quot inStr inFilereadline Read next line print inStr Lines have newline on end I A typical loop that reads a file one line at a time I How do we recognize blank lines when we get to them Whitespace I Spaces look blank I Tabs look blank 39tn39 tn I Both of these look like a blank line I Generically called whitespace I inStrsplit splits on whitespace New String Method gtgtgt s tn39 gtgtgt t sstrip gtgtgt t gtgtgt s 39 tn39 gtgtgt I Strip method removes spaces tabs newlines rom beginning and end of strIng Leaves Whitespace Inside s quotnnnCats quot I sstrip0 is Cats s quotCatsnnnCatsquot I sstrip0 is quotCatsnnnCatsquot In Our Program 11102008 Strip out leading and trailing whitespace testStr inStrstrip If nothing is left don39t print the line if testStr quot print inStr Writing the Output File outFilewrite inStr I Write out only the nonblank lines I Can open any file for writing so program won39t crash if it does not exist ECS 10 11132008 Announcements I Assignment due tonight I Many Eyes had a bug on their Web page US counties had disappeared We sent a bug report and now it39s back I Also bug on my Web page that was not showing the lecture notes with some version of Explorer is xed I Midterm on Monday Bring a Scantron 2000 0 3 Exceptions popStr rawinput Enter the population ry pop floatpopStr Try conversion except Conversion failed print Not a number pop None if pop None Put rest of program here helperpy I This is how helperpy worked I Recall specifically if helperisFloatpopStr pop oatpopStr else print Not a number I The expression helperisFloatpopStr is a Boolean True if conversion will work Functions I Today we consider how to put this bit of code into a function that we can include in a module I Any program we write with functions could have been written without them No new magic I Makes it easy to pass code around extend the language I Also makes for neater programs Parts of a Function I We have used lots of functions Example x int 5366 takes the oat 5366 and computes the integer 53 value of int5366 is 53 variable x gets 53 I Function quotparts of speechquot I Float 5366 is the argument I Int 53 is the return value 11132008 De ning functions def isFloats I Begin de ning function with def I Parameters go inside parenthesis eg 5 I Parameters are variable to hold values of arguments inside the function I Might have no parameters I Might have lots of parameters I Colon Arguments and Parameters I When I de ned isFloat I had no idea what you were going to call the variable containing the input string when you called helperisFloat I But I needed a variable to put that data the input string into I My variable s is the parameter I The argument is the variable in your program that holds the input data Return Value return True I Functions usually produce an output data va ue I return is a Python command only used in functions I The data value after return is the output data value produced by the function I We say this value is returned39 by the function Let s make a new function I Remove commas from a string I We39ll just put it into helper def noCommas s sreplace3939 quot return 5 I It is OK to change the parameter I It is OK to return the parameter From the outside I Function arguments don39t change After this reply rawinput Enter interest rate rate floatreply I reply is still a string the function oatO did nothing to it I rate is a float if there was no error I Functions we define ourselves are the same the arguments stay the same even if the parameters change in the function Functions in Modules I Need to import the module before you can use the functions in it I Function isFloat in module helper is called helperisFloat I You can shorten the prefix import helper as h if hisFloatinStr Functions in Program I You can also define functions in the same file as the program that uses them I Put function definitions at the top of the file right after the imports Functions must be defined before they can be used I The code in a function is not run until the function is called whether it is in a separate module or in the file with the program 11132008 0n the inside I What happens in functions stays in functions I Changing parameters does not change arguments def addonex return x age 5 next addone a print quotI amquotagequotand soon lwill bequotnext ECSlO 1017 Midterm I Midterm 1 is Monday 20 in class Bring a Seantron 2000 form 15717 multiple choice questions 7 65 pts Short 8 lines program 7 35 pts I Open book open notes Bring all the notes you want I I expect a doctor s note or equivalent if you have to miss it I st Oct 22 is the drop deadline Programming Problem Enter ihitiei masn grams on Enter yearly decay percent nanny EU ifte e u n gram rete in in sn 5 yea i th after year 2 the u aw aft yea 2 the aft r ear 4 the after year 5 the after year 5 the after year 7 the i Y ar needed ta drop halo 1 of initiei meee 7 Please use comments 3 panicular deeme mpll and olleuts Approach I First understand what the prograrn is supposed to do I Here the prograrn is supposed to 1 jet user input 7 initial mass rate or decay 2 Reduce mass by rate of decay percent 3 Unitl mass is reduced to lt 1 of its initial mass I Heart of the program will be awhile loop I Start in the middle on scratch paper While loop I The prograrn will require awhile loop You really have to understand how it works While Boolean is True lb do block own 066 569 I The block under the while line is repeated until the Boolean test in the while line becomes False Choose variables I initialMass 7 The mass the user inputs at the beginning Float I mass 7 The mass that decreases every year Float I rate 7 The percent decay every year Float I year 7 The number of years so far Integer Block under the While while mass mass massrate1000 year year 1 print After year39year Drint The mass is39 mass l Xhat should the Boolean condition in the while statement be The Boolean condition while mass gt initialMass001 mass mass massrate1000 year year 1 print After year39year Drint The mass is39 mass I What Values should all the Variables have before the loop starts Getting user input Beginning values for other variables reply rawinput Enter initial mass gramsquot initialMass floatreply reply rawinput Enter yearly decay rate in percent rate floatreply l Does not say that input has to be checked to avoid crashes that would be optional mass initialMass year 0 while mass gt initialMass10039 mass mass mass rate 100 year year1 print After yearquotyear print the mass isquotmass After the loop print Years needed to drop below 1 of initial mass isquotyear l Comments Comments Comments I lfyou make mistakes in the code but the comments show what you were trying to do you might get partial credit Variables and assignment l Variable on left I Expression something which is or computes a data item on the right l Uses old Value of x on the right to compute new Value of x which is stored in Variable x on left Boolean expressions Complicated Booleans l Either have Value True or False capitalized I if not repl 1 or reply p or reply s I l True when reply is NOT 1 p or s I An expression that has Value either True or False Use it in an if or a while statement while x if reply R and reply D I Always False so the block under ifnever done 039 if reply I R and reply I D l True when reply is not R or D x randomrandrange Z or question or question The lines The lines x 0 x 0 X X a Will result in x containing the Value 0 a Will result in x containing the Value 0 b Will result in x containing the Value 1 b Will result in x containing the Value 1 c Will result in x containing the Value False c Will result in x containing the Value False d Will cause an error d Will cause an error Example ifelifelse question Example ifelifelse question The following lines The following lines import random import random points 0 points 0 x randomrandrange f x randomrandrange f ifx T 0 a Will print one of ifx T 03 a Will print one of P1111t IOCk rock paper scissors P1111t IOCk rock paper scissors clif X lt 1 b Might print both rock euf X lt 1 b Might print both rock P11m Papa and paper print paper n l per 5155 c Will never print rock 5155 c Will never print rock print scissors d Might quotm prim print scissors d Might not print anyt ing 39 anyt ing randomrandrange Prepare for ifelifelse question I It s in the book and 1015 lecture Test it out in I Review lecture notes from 1015 and rpspy IDLE program randomrangrange10 I Read pages 61764 in book and try out all examples in IDLE I Produces a random number between 0 and 9 I Progrmmmg exemlse I Write a program that gets a random number between 1 and 4 prints it oug and then correctly identi es it with the sentence It is four It is three It is two or It is one using ifeelifeelife else Example question Example question Question 2 The line Question 2 The line print 165 print 16 1 A prints out True B prints out False B prints out False C causes an error C causes an error D prints out 3 D prints out 3 E prints out 1 E prints out 1 Example question Example question Quullmt 7 mm inc my mom 1mm Qumim 7 lmr lncn rim pingmul iiiut u i x H pnnr 39n ur gm it N n p lu gxettlsz n rm hair rm 3 tuy M m 1at in M n yrum to buyinm mi 37 to Mt umml 3 m nMium browse u 11 NOV mum watt391 a ii iii mum mst lit mmm I Common errors I Use a Variable before you put something in it Causes the program to crash I Value of an expression is not put into a Variable oatreply balance balancerate 7 payment I Does not cause an error but the Value of all Variables remains the same ECS 10 Sept 26 Introductions l Prof N1na Amenta Kefeng Tan Kelcey Chan Vishal Abuja A rst programming class I For people wth no prograrnmlng expenence I Learn the computer language Python I Write 51X programs Why learn to program I Understand computers I Computers are used in almost every career I The programs you have are never exactly what you want Example I UCD Student Health Center Director l UCD Medical Center Hospital medical record or extenmon of current system I Which to choosegt I How to connect themgt By the end of this course you will be better able to make IT decisions like this Another Example I County manager trying to decide whether to build a new fire station I Log books from fire houses in two different formats I Need to get them both into Excel by the end of this course you can handle problems like this yourself How does programming help I You can handle little problems yourself I You know when you hire someone how big a job it is I You have some idea of what is possible I A good programmer has lots ofjob options you ll need more than this one class though It teaches you to think I The computer is a logic machine I It does exactly what you tell it to l Your job is figuring out what to tell it I Learning the language is the easy part learning to give exact directions is the hard part I Imagine telling a Martian how to tie their oes Why Python l Great for interfacing one program to another I Free I Used in industry 7 Google ILM NASA l Easy to get started with l Lots of modules plugins addeons that do things like sound editing computational biology Web database access Other options I ECS 15 7More conceptual overview Understanding how computers and the internet worl a little programming I ECS 30 7 More intensive class for those with some programming experience Basic Learn C Required for CS and CSE majors Course Structure l Six programs 7 31 of grade I Tentative breakdown I hello 7 1 l battleground states 7 6 I mortgage 7 6 lme drawing 7 6 I data 600 graphing e 6 l FlRST PROGRM DUE 10PM XDS OCT 1 Exams l Two midterms 7 20 each l1020 and1119 l lfyou miss the midterm either I Give me a note from Student Health Get permission at least one week ahead of time I Final 7 29 l Dec 8 80071000 AM in this room I DO NOT leave campus before this final I All exams open book open notes Keeping Up I Very fastuntil first midterm I If you keep up for the first month you will be me I If you don t you will be in trouble Weekly activities I Lecture 7 3 hours I lfyou have a laptop maybe try typing along I Discussion section 7 1 hour I Bnnglaptops l Lab hours 7 10 hours optional I For help wrth programs I Of ce hours 7 1 hour optional I Administrative things lw1ll not help you With your program during of ce hours Lab Hours I We have open lab hours in the 2020 SLB a computer classroom M 122 Kefeng Tan 1 111 micey Chan W 111 Kefeng Tan Kelcey Chan R 13 Vishal Ahuia F 35 Vishal Ahuia l Sometimes in use by other classes I Python also in 75 Hutchinson an Open Access Lab and 1131 Meyers for ECS15 Map Fla sh drive I lfyou work in the computer e1assnoohns you I ECS 10 geography in shouldbnng a ash dnve 1 quot t 8 o 3 W3 Professional Conduct Getting started I 1am expecting professional adu1t behavior I First assignment due evening odes 101 I Politeness I Get on a computer and startWeb browser I No eating in class I Find first assignment on course Web Site I No phone calls I quotBoeineeeietteiquot emails can get there from myUCDavls I Honesty I Startusmg Python I Write and understand every 1ine of every piogiam I No cubandepaste I No 1oohing at otheipeopie e piogiame while typing Install Python on your computer What to do this weekend I Lmkto Python download page and directions I Look at the rst assignment on the Web page on course Web me I Install Python on you computer OR go to the I We can help during lab hours ifyou have a lab and log on and try starting Python 2 top I Get the book and read the rst 11 page while sitting in front ofa computer and typing along Announcm ents I No sections met this week I Lab hours and sections starting Monday I I will be at Tu 11am lab hour I My of ce hour is X 2pm Administrative issues only ECS 10 lll4 11142008 Announcements I MIDTERM Mon Nov I7 I Open book open notes Bring sample programs from class your programs etc I Bring a Scantron 2000 I On myUCDavis solutions to Prog 4 programming problem on sample midterm Topics I Lists indexing concatenation of lists I range and len functions I for loops on lists and strings I Files I String methods split replace strip I Dictionaries I Exceptions I Formatting floating point output Midterm 1 Topics choosing True while choosing a rawinput Enter h or t 39 choosing not a h39 or a t39 print You chose39a I choosing is a Boolean variable I while loop runs so long as choosing is True I Gets set to False if a h or a t List Indexing import random suits 39Hearts39 39Clubs39 39Spades39 39Diamonds39 faces 39J39 39Q39 39K39 i randomrandrange4 num randomrandrangel 3 if num lt l0 print 39My card is the39num l 39of39suitsi e se print 39My card is the39facesnuml l39of39suitsi Example Question The program dogList Collie Beagle39 Dachshund39 print dogList3 will print a Collie39 b Beagle39 c Dachshund39 d crashes Concatenating Lists digits fori in range l0 digits digits stri print digits I digits begins as the empty list I Function rangelO has the value 0 l 289 it produces a list I Function stri converts integer i to a string I We have to concatenate two lists so stri Example Question This program has a missing line dogList Collie fori in rangelendoglet print dogListi The program prints 3 C ie b dogList Beagle Beagle c dogList2 Beagle The missing line should be d dogListdogListBeage For Loop on a String line 39 l0456897456539 digits 02l 2 3 4 5 6 numStr quot 7 29 tor char In line if char in digits numStr numStrchar num intnumStr print num For Loops for char in line I Since line is a string the variable char will be each character in the string in turn for word in wordList I If wordList is a list of strings the variable word will be each string in the list in turn fori in rangelena I Whether a is a list or a string iwill be the integers from 0 through lenal in turn String Methods I string stringstripO I Removes leading and trailing whitespace I words stringsplit t I Returns list of substrings I change changereplace I Replaces all copies of one substring with another String Processing string Nov 2tNASDAQt 263493t063n39 string stringstrip words stringsplit t change words lenwords l if change0 direction up39 change changereplace 39 else direction down39 change changereplace print NASDAQ direction by change dogList dogList39Beagle dogListdogList Beagle39 Files inFile open myFiletxt39 r39 giftStr inFilereadline while giftStr quot print Read line 39 giftStr giftStr inFilereadline inFllecloseO I Files are read from beginning to end no going backwards I readline method returns next line I readline returns empty string at end of file 11142008 Alternative File Loop inFile open myFiletxt39 r39 giftStr None while giftStr quot giftStr inFilereadline print Read line 39 giftStr inFllecloseO I The value None lets you de ne the variable giftStr without putting anything into it I Keeps Boolean in while from crashing first time through Writing Files myFile open39toExceltsv39 39w39 fori in rangel0 oatNum floati myFilewrite39item39stri39t2fn39floatNum myFileclose I Open file to write with w39 I write method has one string argument Formatting Strings 39t2fn39floatN um I operator has string on the left number on the right I Formatting string on the left contains special formatting sequences that get replaced by the num er I 2f writes the number with two decimal places Dictionaries giftDict giftDict39Lion39 39Courage39 giftDict39Tin Man39 39a Heart39 giftDict39Scarecrow39 39Brains39 character rawinput39Character name 39 if character in giftDict gift giftDictcharacter print 39The gift of the39character39is39gift3939 Key Value Pairs 39Lion39 39Courage39 39Scarecrow39 39Brains39 39Tin Man39 39a Heart39 I Keys on left of colon values on right I Keys are like indices values are the data stored by indices ECS 10 05 10152008 Announcements I Midterm Mon Oct 20 I Bring any books or notes you want I Bring a Scantron 2000 buy at bookstore I Bring a pencil I Know what section you are in lS I Study Stopping the program I Instead of looping on bad input just stop I The best way in Python use an if statement I Introduce a sentry variable to keep track of whether we got good input or not Sentry variable goodlnput True print 39Enter your height39 reply rawinput39Feet 39 if helperislntreply else oodlnut False Using the sentry I goodlnput is a Boolean variable only do calculation if it is True if goodlnput inches feetl2 inches bmi pounds703 inchesinches Rock paper scissors I Play the game with your neighbor I Example of a program structured like this tie True while tie if Somebody win ECS 10 00 Announcements I First midterm aweek from today in class I Open book open notes I No computers no calculators I Bring a Scantron 2000 form available in bookstore I We will also ask you to write a short program I Last year39s midterm and program on Web site Interest Compounded Monthly I Costs you more than interest compounded annually Program Crash I Python stops and refuses to run your program any more because it contains an error I Nasty red error messages I Your goal as a programmer is for your programs never to crash I Windows crashes sometimes IDLE crashes sometime So annoying Bad programming Why is this program crashing I It tells us the line monthlyRate annualRate l 20 I It tells us what it doesn39t like unsupported operand types for 39str39 and 39float I Function rawinput returns a string I Cannot divide a string by 20 Converting strings to numbers I Use Python functions I into I float I Examples x int 26quot x now contains the integer y float 75quot y now contains the float 75 Still crashes I The input to float has to be a string that represents a float I The input to into has to be a string that represents an integer float 2366quot does not crash float cowquot crashes int 345quot crashes I We39ll solve this with a new function Operators and Functions I Some operators X 67 X 80 l 344 print Molly 3939 if X lt 20 and X gt IO I Some functions reply I39awinput Enter weight weight intreply How to x I We can39t control what the user enters I Need to check user39s input before we do anything with it that might cause a crash I Python doesn39t have a function to checks whether a string can be converted to a float or to an int I There is a way to do this but we haven39t learned the right parts of Python yet A helpful module I You need a checking function I We39ll give you a checking function I We put it in a module that you can import I A module is a file that extends Python a plug in an addon I Anybody can write a module I Ability to extend the language makes it really useful Helper py I Our module will be called helper I It s in the file helperpy I You need to have this file in the same folder as your program so that Python can find it I To get access at top of program file Import helper Two functions in helper I helperisFloatO helperislnt I Both take a string as input I Both return a Boolean value as output isFloat 92quot is True helperisFloat l2 True helperisFloat threequot False Looping for input I The program is not crashing I It tells the user what is wrong and asks again for input Parts of program I Getting input I Doing computation while loop I Writing output Prettier Output I You can ask Python to cut off extra decimal places 2f totallnterest I First part says output will be a string with two digits after decimal place made out of a float I operator connects format and oating point data 1252008 ECS 10 l205 Announcements I Final is Mon Dec 8 8l0 AM I Open book open notes Bring sample programs from class your programs etc I Bring a Scantron 2000 and a pencil Materials for Study I On class Web page example final with three programming problems Try doing them first on paper then on the computer I Lecture slides inclass programs See especially midterm review sessions I On myUCDavis Midterm 2 solutions solutions to program 4 and 5 soon 6 I Read the book and work through its examples if you haven39t yet Topics I Everything from Midterm l I Boolean variable and expressions I int oat str I iverything irom Midterm z I string methods I for loops I dictionaries I Files I Functions Boolean Variables x 5 a xgt2 b xlt4 print not a or not b IWhat does this program do Boolean Variables x 5 a xgt2 b xlt4 print not a or not b IThe value of a is True IThe value of b False IThe value of not b is not False is True ISo the program prints True Dictionaries D frequency ofletters in English Duen I Dutn 2 Duan 3 for i in range3 print Dil I What does this program do 1252008 Dictionaries D frequency ofletters in English Duen I Dutn 2 Duan 3 for i in range3 print Di I I It crashes because Dl does not exist I Keys here are letters not integers I How could you do this correctly When to use a List D frequency ofletters in English DD Mequot fori in rangel4 print D I Better to use a list since we want to access the data using a small range of integer indices in order Dictionaries key rawinput Choose a letter if key in D print Dkey I Use this construct if you can39t be sure the key is in the dictionary I Keys are letters not integers I Indexing with a nonkey causes a crash Dictionaries D letters abcdefg fori in rangelenletters Dlettersi i print D c I What does this program do Dictionaries D letters abcdefg fori in rangelenletters Dlettersi i print D c I Letters are keys values are ints I rangelenletters is 0l23456 I D a 0 D b I Prints 2 Lists of Lists 1252008 for i in range3 L L i i Lists of Lists I What is L after these lines L for i in range3 LL i i I i il is a list of integers with length 2 I l i is a list of lists with length l I L is 0 I 2 2 3 I L is a list of integers and lists with length 3 Sentry Variable import random rolling True while rolling dice randomrandrange6 if dice 6 rolling False I What does this program do Sentry Variable import random rolling True while rolling dice randomrandrange6 if dice 6 rolling False the program Is 0 n I While loop will not end until sentry variable becomes false I Sadly dice is always in the range 05 I Boolean variable used to keep track of what g Functions def cleanStrings out sreplace inStr 34308 cleanStringinStr x intout Functions I What does this program do def cleanStrings out sreplace inStr 34308 cleanStringinStr x intout I Crashes I The local variable out is still undefined in the main program 1252008 Functions def cleanStrings s sreplace inStr 34308 cleanStringinStr x intinStr I How about this one Functions def cleanStrings s sreplace inStr 34308 cleanStringinStr x intinStr I Also crashes Functions don39t change their arguments inStr is defined but cannot be converted I How do you write this program correctly Functions def cleanStrings s sreplace return 5 inStr 34308 newStr cleanStringinStr x intnewStr I Information is sent back to the main program by with the return value I In the main pro ram it has to be assigned to a variable new5t5 Files inFile open myFiletxt r39 G giftStr inFilereadline while giftStr giftStr giftStrI G giftSt I39 giftStr inFilereadline0 I What does this code do Files inFile open myFiletxt r G giftStr inFilereadline0 while gi c tr 1 quot giftStr giftStr I G giftStr giftStr inFilereadline0 I Typical filereading while loop I File line is quot after end of file I Every line ends with a n39 newline character I G ends up being a list containing the last string in the file without newline Files inFile openquotmyFiletx quotquotrquot G giftStr inFilereadline while giftStr quotquot giftStr inFilereadline0 I In this version G becomes a list of strings all without newlines I Another way to remove newlines
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'