COMPUTER PRGRMNG I
COMPUTER PRGRMNG I CSE 142
Popular in Course
Popular in Computer Science and Engineering
This 43 page Class Notes was uploaded by Dr. Jakob Kulas on Wednesday September 9, 2015. The Class Notes belongs to CSE 142 at University of Washington taught by Martin Stepp in Fall. Since its upload, it has received 27 views. For similar materials see /class/192493/cse-142-university-of-washington in Computer Science and Engineering at University of Washington.
Reviews for COMPUTER PRGRMNG I
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 09/09/15
i3 pgthonw Introduction to Programming with Python Marty Stepp steppcswashingtonedu University of Washington p r w their WU Except mere otherwise muted this Wcrk is censed under WWW 0 Programming languages and Python 0 Basic programs and numeric data Control statements 0 Text processing What39s next CSE 142 at UW a pgthonm Languages 1954 0 Some influential ones 1958 FORTRAN 0 science engineering 1 COBOL 12 0 business data 1 LISP 111 o logic and AI 1980 1983 1985 o a simple language 198739 1988 1994 2002 fl i3 pgthonl Python 1 0 Created in 1991 by Guido van Rossum now at Google Named for Monty Python 0 Useful as a scripting language script A program meant for use in smallmedium projects 0 Used by Google Yahoo Youtube Many Linux distributions Games and apps eg Eve Online i3 puthonw Installing Python Mac OS X 0 Python is already installed 0 Open a terminal and run python or run Idle from Finder Windows 0 Download Python from httpwwwpvthonorq 0 Install Python 0 Run Idle from the Start Menu Note For step by step installation instructions see the course web site i2 puthonw Linux 0 Chances are you already have Python installed To check run python from the terminal 0 If not install from your distribution39s package system Interpreted Languages 0 interpreted Not compiled like many other languages Java C C Code is written and then directly executed by an interpreter Type commands into interpreter and see immediate results r The Python Interpreter o Allows you to type commands oneatatime and see results 0 A great way to explore Python39s syntax elem le Emit he erug Qp ons windows Help Python 243 69 Mar 29 2006 173534 MSG v131o 32 bit Inte1 on win32 Type quotcopyrightquot quotcreditsquot or quotlicensequot for more information 39Iri k k39k39k339k39k k k k39ki k k39k ki ki39k39ki39i39k39ki39k 39atat39k39k39kii39k39ki ki Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer39s internal loopback interface This connection is not visible on any external interface and no data is sent to or received from the Internet kkkkkkkkk kkkIrkkkk IDLE 113 gtgtgt print quotHello therequot Hello there gtgtgt print quotHow are youquot How are you gtgtgt Ln 16 Del 4 a pgthonl i3 pgthon Basic Programs and Numeric Data The print Statement o A Python program39s code is just written directly into a file print quottextquot print a blank line print quotHello worldquot swallowspy l 2 3 4 print quotHello worldquot print print quotSuppose two swallows carry it togetherquot print quotAfrican or European swallowquot Pg pgthonm o Syntax comment text one line swallow52py 1 Suzy Student CSE 142 Fall 2097 This program prints important messages print quotHello worldquot print blank line print quotSuppose two swallows quotcarryquot it together quot print 39African or quotEuropeanquot swallows ONLHIbWN go pgthonm Expressions 0 expression A value or operations to compute a value Example 1 4 3 o Arithmetic operators add subtractnegate multiply divide exponentiate modulus aka remainder o precedence Order in which operations are computed have a higher precedence than l34 i513 l34iSl6 an pgthonl Integer division 0 When we divide integers with the quotient is an integer 3 52 4 14 27 1425 2 135 2 75 g4 21 035 5 E 7 084 10 E 8 o The operator computes a remainder from integer division 3 43 4 14 5 218 12 20 7 T8 ii 3 a pgthonm Variables variable A named piece of memory that stores a value Syntax name expression Examples x 5 gpa 314 X gpa 314 A variable can be used in expressions x 4 is 9 13 o This program39s code is redundant print print print print print print print print ea pgthonm Improve it with variables quotSubtotalzquot 38 40 30 quotTaxquot 38 40 30 09 quotTipquot 38 40 30 15 quotTotalquot 38 40 30 38 40 30 15 38 40 30 09 Data Types 0 type A category or set of data values Constrains the operations that can be performed on the data Examples integer real number text string 0 Python is relaxed about types A variable39s type does not need to be declared A variable can change types as a program is running Value Python type 42 int 314 float quotnilquot str i2 puthonl Parameters o parameter A value supplied to a command as you run it Syntax command value command value value value 0 Example print sqrt25 print sqrt15 10 10 6 X 5 print sqrtx sqrtl6 a pgthonl Math commands Function name Description Constant Description abs value absolute value e 27182818 ceil value rounds up pi 31415926 cos value cosine in radians floor value rounds down loglO value logarithm base 10 max value1 value2 larger of two values min value1 value2 smaller of two values round value nearest whole number sin value sine in radians sqrt value square root c To use these commands place this line atop your program from math import go pgthonl input input Reads a number from the user39s keyboard You can store the result of input into a variable Example age inputquotHow old are you quot print quotYour age isquot age print quotYou havequot 65 age quotyears until retirementquot Output How old are you 53 Your age is 53 You have 12 years until retirement 0 Exercise Modify the restaurant program to ask the user how much of a tip to leave an puthonl 18 e pgthon Control Statements if statement Executes a set of commands only if a certain condition is True Otherwise the commands are skipped Syntax if condition statements Example gpa inputquotWhat is your GPA if gpa gt 20 print quotYour application is acceptedquot pgthonm 20 if else statement Executes one set of statements if a certain condition is True and a second set if it is False Syntax if condition statements else statements Example gpa inputquotWhat is your GPA quot if gpa gt 20 print quotWelcome to Mars Universityquot else print quotYour application is deniedquot 0 Multiple conditions can be chained with elif an pgthon 21 Operator Meaning Example Result equab l 1 2 True does not equal 32 1 25 True lt less than 10 lt 5 False gt greaterthan 10 gt 5 True lt lessthan orequal to 126 lt 100 False gt greaterthan or equal to 5 0 gt 5 0 True Logical expressions can be combined using logcal operators Operator Example Result and 9 1 6 and 2 lt 3 True or 2 or 1 lt 5 True not not 7 gt 0 False go pgthonw forIOOpS for name in rangeStal t end Statements for name in rangestart end step statements Repeats for values stalt inclusive to end exclusive gtgtgt for i in range2 6 print i 2 3 4 5 gtgtgt for i in range15 O 5 print i quotsquared isquot i i 15 squared is 225 10 squared is 100 5 squared is 25 a pgthonm 23 Cumulative loops 0 Some loops incrementally compute a value sometimes called a cumulative loop sum 0 for i in rangel ll sum sum i i print quotsum of first 10 squares isquot sum Output sum of first 10 squares is 385 3 pgthonm M 0 Write a program that reads a student39s homework scores as input and computes the student39s homework percentage This program computes your average homework grade How many assignments were there i Assignment 1 Points earned l3 Points possible lg Assignment 2 Points earned l2 Points possible g2 Assignment 3 Points earned 3 Points possible E Your total score 26 4O 65 an pgthonm 25 while while loop Executes as long as a condition is True good for inde nite 00p5repeat an unknown number of times 0 Syntax while condition statements 0 Example number 1 while number lt 200 print number number number 2 Output 4 8 16 32 64 128 Q puthonm 26 Random numbers from random import randint min max Produces a random value between min and max inclusive Example coinflip randintl 2 if coinflip 2 print quotHeadsquot else print quotTailsquot 27 i3 pgthonl 0 Write a program that plays a guessing game with the user Let39s play a game Try to guess my number from l lOO Your guess 52 Too low Your guess g Too high Your guess g Too high Your guess 1 Too low Your guess 7 Too low Your guess 6 Too high Your guess El You got it right in 7 guesses a pgthonm 28 e pgthon Text Processing 0 string A sequence of text characters in a program Strings start and end with quote quot or apostrophe 39 characters quothelloquot quotThis is a stringquot quotThis too is a string It can be very longquot 0 A string can represent special characters with a backslash quot quotation mark character t tab character backslash character quotBob said quotHelloquot to Susanquot an pgthonl 30 0 Characters in a string are numbered with indexes name quotP Diddyquot index 0 1 character P o Accessing an individual character from a string variable index print name Output P Diddy starts with P can pgthonm quotstarts withquot 31 String properties len string number of characters in a string including spaces 0 str lower string lowercase version of a string 0 str upper string uppercase version of a string 0 Example name quotMartin Douglas Steppquot bigname struppername print bigname quothasquot 1enbigname quotCharactersquot Output MARTIN DOUGLAS STEPP has 20 characters can pgthonl 32 rawinput rawinput Reads a string of text from the user39s keyboard Example name rawinputquotHowdy What39s yer name quot print name quot what a silly namequot Output Howdy What39s yer name Paris Hilton Paris Hilton what a silly name a pgthonm 33 Text processing 1 0 text processing Examining editing formatting text Often uses loops that examine characters one by one o A for loop can examine each character in a string in order Example for c in quotbooyahquot print 0 Output 2 pgthonm 34 Strings and numbers I 0 0rd text Converts a string into a number Example ordquotaquot is 97 ordquotbquot is 98 Characters use standard mappings such as ASCffand Unicode chr number Converts a number into a string Example chr99 is quotcquot a pgthonm 35 0 Write a program that quotencryptsquot a secret message by shifting the letters of the message by 1 eg quotAttackquot when rotated by 1 becomes quotbuubdlquot i3 pgthonm 36 e pgthon What39s Next Further programming I o What do students learn next Arrays data structures Objects and objectoriented programming Algorithms searching sorting recursion etc Graphical user interfaces drawing eventdriven programming a pgthonl 38 CSE 142 Homework 39 ume e gdlt gearch yiew Ian 0 Our homeworks process Interesting data and text 1 l l 3 l l 4 l I WINDOWSsvstem32cmdexe 5 I I what month day and year were you 39 You were born on 1934919 which 7 1 It win be your birthday in 211 da E 39V1 You are 26087 days old 39 quot lVVVVVV nue I WWW iv 1 s TextPad CDocuments and Settingsstepp m V f 1 Q Efe Edit Search yiew Iools Macros Qan gure ind ii I V 1 13 1 Ehmqpeogr amallowsiyeuAteuseaxs n 14 I1 2 data from the Social Security A 15 l1 3 to see how popular a particular H 7 39V1 A 1 1 Since 1900 Name cure for cancer protein H E VH 5 Nucleotides ATGCCACTATGGTAG mag lVV1 E Name Jordan Nucleotide counts 4 3 4 4 g Axxxxxx 7 4 H 64 39 A A 2 a 2 l1 1 Codons ATG CCA CTA TGG TAG WWW H StatlSthS on Encodes a protein yes SEE NH 139 1900 0 ge39lgg 1 1910 850 Name captain picard hair growth protein ll l 11 1920 550 Nucleotides ATGCCAACATGGATGCCCGATATGGATTGA 7 15 1091quot 39711 3 Nucleotide counts 9 6 3 7 1 c3 1 quoti quotw I lll Codons ATG CCA ACA TGG ATG ccc SAT h Encodes a protein yes H 7H a C Mama hnnng nrnfpi n 39 M i WT w Robot Love F 117 Nighthawk Critter simulation 0 Students write several small classes to represent animals in a simulation world 0 Each student writes a custom quotHuskyquot animal with their choice of behavior 0 The best huskies compete in a tournament for prizes 02 pgthonm O O quot CSE 142 Critter Safari 41 Facebook integration b Weimam In Eile Edit ew History cokmarks Iools elp aunt m 5939 mgm Pro le edit Friends v networks v Inbox v facebook Report Bug Q Home 3 3 MW Home E Submit EniT r IE Vote 4 Admin Search v CSE142 HW2 Contest H tegt Hm Applications 6th r mm Contest Info 139 1 a GE 3942 contests i Name Agc Art Contest 39 more Ciusing Date Saturday January 26 2008 at 4pm 39 on entries nG ia39l Top 10 Ennis These are the mp 10 entries so far Votes are Indicated by the number in parentheses after the name 39 39urvs Submit an army and mew and we39re on the SmeiSSI Funny Complex quot ir i ax 5112 Ame use an F2tm39r Rubik39s Cube Mailog By Christopher Monopoty in Seame 1 33922 9 21 Gateley 45 size Tesla Edison WaiMart Microsoft and the War x Ike Da39 2 By Uland an 18 By Uland Lau 16 reveals It all live Sumacan full size Full size Black Hm HIISkV 3 By Kristina Nguyen By Cameron Rahrnan 16 14 full me Full size Blinky Mario 4 By Katherine Fan 16 By Don Nguyen 13 fun JIl size Full SIZE SIZE Super Bowl 42 thre 5 E LOVE Husky Pride In 9 pg Dre 42 0 Python for math teachers httpshowmedocomvideosseriesid101 0 Physics and 3D in Python httpshowmedocomvideosseriesnamepythonThompsonVPythonSeries o Handbook of the Physics Computing Course Python httpwwwteachingphysicsoxacukcomputinghandbookPythonhandbookPythonhtml o Biopython Python tools for biology httpbiopythonorgwikiMainPage 0 Python course in Bioinformatics httpwwwpasteurfrrechercheunitessisformationpythonindexhtml 0 pgthonw 43