You are on page 1of 395
oe ID: 6689691 ()G)-Pabe 8 Instructor Notes nd about 2 years ago by| (U/FOUO) Instructor notes for COMP 3321 UNCLASSIFIEDHFOR- GFFIGIAL BSE-ONEY (U) So, youre teaching the Python class. What have you gotten yourself into? You should probably take a few moments (or possibly a few days) to reconsider the life choices that have put you in this position, (U) Course Structure (U) As mentioned inthe involution, this course is designed for fexcbilty. When aught in a classroom setting, single lesson or module can be ‘covered ina session that lasts between 45 and 90 minutes, depending on the topics to be covered. The standard way to structure the course is as fulltime, two week block. During the frst week, the ten lessons are covered with moming and aftemioon lectures. During the second week, up to ‘ten modules are covered ina similar manner, as needed or requested by the students in the class. (the class needs are not known, take @ vote), During the fist few days of class, students should choose a project to work on. On the lat day, students should report back onthetr progress and, if possible, demonstrate ther work. Instructors should be available outside of lactures to assist students with exercises and projects. {(U) The two week block isnot the only way of teaching the course. The material could be presented at a more leisurely pace, for instance during a ‘weekly brown bag lunch that continues for several months. Alternatively, f students are already prepared (or wiling to do some ofthe intial lessons. ina selstudy manner), a great deal can be accomplished in a two oF three day workshop. For instance, (all students already have a basic ‘knowledge of Python, they might well start with the lessons on iooling and wiling.masiules anc packages, then move on to cover various modules of interest. Approved for Ri 36 oc ID: 6689691 (U) Instructional Style (U) When teaching mathematics, the common practice ofthe instructor wring solutions on the chalkboard is a moderating method that helps students keep up. Writing on a chalkboard isnot usualy helpful when teaching programming, but the same principle applies; as the instructor, you should adopt practices that help you slow down. We recommend that you have alive, interactive session displayed a the front ofthe room, large ‘enough fo ll the students to soe. This session can either be a terminal session ora Jupyter notebook. The important detallis that in most cases the commands should not be pre-populated; eg. you should not just execute cll from an existing Jupyler notebook. The materials are present to help you prepare, and as a reference for the students as they work on exercises; they are not an acceptable substtue forthe shared experience of teaching and learning. You will make unexpected mistakes as you write code lve In font ofthe lass. Dont worry, relax, and let the students help ‘you-it wil help them eam the principles and figure out how to solve their own problems, This Is not a substitute for proper preparation; too ‘many mistakes and fumbles will cause your students o lone interest nthe course and trust in you (U) Ongoing Development ae (U#FOUE} The developers of this course believe thatthe current materials are sufficiently welldevetpied tobe an effective ad forthe course. However, improvements, extensions, and refinements are aways welcome, To that ert we have attempted to make i easy to contribute to the Drie. Th docmartan bao on te Mack offal COMP 2921 mete, you weno neko charge for our ‘own purposes, fel tree to clone that repository or fork any ‘on the Juptyer Gallery. Please submit @ change request onthe Gallery if you'd like to make a one-off contribution, including new or improved exercises, additions to lessons or modules, or entrely new lessons or ‘modules. Ifyou woul ke to be a collaborator onal ofthe COMP 3321 notebooks, contact the COMP3321 GlobalMe group and ask o be added. (U) A possible icebreaker (U) To got the students interacting with each other as wel as thinking about code at an abstract level, consider the following icebreaker. Instructor becomes human compile to interpret written instructions to get out ofthe room. (U) Phase I~ discussion with whole class (U) Invent a programming language together, one sufcient fr ths task. Clearly explain the task, showing where inthe room the instructor wil begin and how big a steps, (U) Take suggestions from students about what instructions they will want to use. Write each instruction on the board. Be clear that everything ‘written on the paper must come from syntax onthe board, No other syntax allowed, (U) Make sure the instructor and students agree about precisely what each instruction means. AS the instructor, be certain thelist onthe board is. ‘enough for you to solve the problem. Give hints unt i's complete (U) Let the students come up with the syntax. But here are some syntax examples they may come up with + step(n) takes in an integer and causes instructor to taken steps, Doe 6589691 um(d) ~ takes in a number in degrees and caused instructor to tum clockwise that many degrees. Students may abuse this and putin numbers that lead to dizzyness, e.g. tun(1440) + obstacle ~ returns boolean indicating rather an obstacle is directly in font of instructor. Variations for checking tothe left or right may be Sesirable as wel, + If-<> then < > else < > ~ fst blank takes boolean (make sure boolean functions exist), Second blanks take instructions, + while <>: <> ~ takes boolean function and any expression not ~ expression to reverse a boolean any integer (U) Phase It break into teams (U) Teams of 35 students tend to be appropriat (U) Each team produces a piece of paper wih computer instructions forthe human compiler to get out ofthe room. Only allowable syntaxis what is writen on the board. Should take no more than 15 minutes. (U) Phase I~ demonstrations (U) One ata time, the instructor takes a team's solution and follows the instructions iterally and fairy. Does the instructor get out ofthe room? (U) Introductory e-mail (U) Tere area couple things it woud be nice ifthe students could nave done in advance, n pacar having GITLAB accounts and INHERE Agreements. | have the COMP3321 learning facitatorssond te folowing eal to enrolled students (U) Aone (U) You are receiving this e-mail because you are registered for COMP3321 beginning <.>. (U) fatal possible, we could use you do a few setup things in advance to make class go smoothly onthe frst day. Really, two simple things that ill take @ minute of your time and save us hours on the fst day of class. (U) 1) GO iagree and find, read and agree to the INHERE user agreement (U)2)60 gitab. (U) in more deta: (U) 1) The course wil be run-vtaLABBENCH and NBGALLERY. Before using this, you will need to agree,to'the terms of service and| knowledge ths Instuctons can be found ber: noallarsa acid (GO NBGALLERY) by cleking GET A BENCH. We ony TOTS foto theft, uta below. Be careful going fre because LABBENCH modi ea dest wo weeks ar creation 50 Yeu want aes one the fret ay of lags : (U) GO iagree. Search "inhere”. Read the INHERE user agreement and agree toi co eventually acknowledge this agreement. That's what we need Doe ID: 6 {85.0 ota. 2y ana tee one an acount il be eel. Thats al we need bet (Utyouwantto go turer and ue gta he command ine[_——Jtownstctons har snide (U) Tre are several opto presented. Whatever you carga won Ws, (U)3) Optpna. Th lao bt 3'CABBENCH. But some people retro use[_——JoachiThs wl ake goths wrk. nial frwconda oy fekowng bese isbn: ioscan rade 8 Nan 22673 (U) you ave any issues wih he instuctons, please contact he insigor: > a (U) Submitting projects - (Aone mr api onc css [Trt an oer Gagan costo Poney epee mand ft BST SET nm VY. Stes wl aut ace © Ges. an bo ean aSumplan fresh he web epleaton by nee" rand copying and esi ere. The web option owt outa tar Steno te Suse ta aed bt can ee Bun comune a rye UNCLASSIFIEDHFOR-OFFIGIAL USE-ONLY oc ID: 6489692 Python Programming (U#2YO} Course introduction and syllabus for COMP 3321, Python Programming. UNCLASSIFIED//FOR-OFFIGIAL USE-ONLY— (U) History .-in December, 1989, | was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but | had a home computer, and not much else on my hands. | decided to write an interpreter for the new scripting language | had been thinking about lately: a descendent of ABC that would appeal to Unix/C hackers. | chose Python as a working ttle for the project, being ina slightly irreverent mood (and a big fan of Monty Python's Flying Circus) Guido van Rossum, Foreword for Programming Python, 1st Edition. (U) Motivation (U) Python was designed to be easy and inttive without sacrificing power, open source, and suitable for everyday tasks, with quick development times. I makes the layers between programming and problem solvingseem as thin as possible. Its suitable for- ‘+ Opening an interactive session to solve the Dally Piz, + Writing a script that automates a tedious and time-ceinhith Do ID: 6689492, Creating a quick web service or an extensive web application, and + Doing advanced matnematica esearch. (U) Ifyou dont know any programming languages yet, Python isa good place to start. It you already know a diferent language, its easy to pick Python up on the side. Python isnt entirely free o frustration and confusion, but hopefully you can avoid those pars until ong after you get some ‘900d use out of Python, (U) Programming is nota spectator sport! The more you practice programming, the more you will eam in this class, both in breadth and depth. Python practically teaches itsetf-the goal of your instructor is fo guide you to the good parts and help you move just ait bt more quickly than you would otherwise. Happy Programming! Betas reen (U) Objective (U) The goal ofthis cass is to help students accomplish work tasks more easly and robustly by programming in Python. To pass the course, each ‘student must wrte atleast one Python program that has substantial personal ult ors of significant personal interest. When choosing a project, ‘students are encouraged to fit think of work-related tasks. For students who need help geting stared, several suggestions for possible projects ‘are found atthe bottom ofthis page. On the fist day, instructors wil lead a discussion where project ideas are discussed, {(U) This class is designed for students of varying backgrounds and levels of experience, from complete navi to competent programmer. Asking ‘each student to design and implement their own project allows everyone to leam and progress at an individual pace. (U) Logistics (U#F946) This course is designed to be suitable for set1eaming. Even ifno formal offerings are available for your schedule, you may access and work on the modules of his course at anytime. Even if you dont have access toa recent version of Python on a workstation or vital machine, you ‘can access a personalized Jupyter notebook avaliable on | ABBENCH. Foran individual pursuing this self-study option itis recommended to fist ‘over the Python Basics roughiy in order, then select as many ofthe Useful Modules as seem appropriate. You can also use this Jupyter ‘notebook to experiment and wrie solutons to exercises. (U##O4E) One possibilty fora group of potential students who start out with a diferent amounts of programming experience is to use Jupyter as a sel-study tool until everyone has a basic understanding of programming, then folow up with an abbreviated instructor-led course (anywhere fom two days toa week or more, depending on needs). (U) In the Classroom (U) For a two week course: there wll be a morning lecture and an afternoon lecture every day. The moming lecture wil ast between an hour and hinety minutes; the aftemoon lecture wil be somewhat shorter. Ha lecture Is going too fast, please ask questions to slow us down! Its going ‘00 stow feo! fee to work ahead on your own, Please Enter Footer Text. oc ID: 6499692 (Gi#SL0} You wil ether use Python within jronment or within LABBENCH, SSS ews] ‘ut some diferences between the Python 3x and 2x les, Tis Course wil focus on Python ‘Zryou need oF wantTo rn Pyihon oh Linux, probably withing achineShon VM, well work wih you. To the extent possible, we wil write code in platform-agnostc manner and pont out fetes that are unique specif versions of Python. : {(U)Atnough lectures wil ony take up two o three FoUs.each day, encourage you to spend the remainder of yur day programming in Python, either on your own orn groups, butin the classroom f possible. AL least ofe instructor willbe available in the classfoom during normal business hours. i (U) This course is a work in progress; we welcome all suggestions. There afe'mgre Ueful Modules than we can Kispe to cover ina two-week class; instructors wil ake a vote to determine which modules to cover. I there is anbihe topic that you would lke {9 have covered, especialy along the lines of "How would | do x, v oF 2 in Python?" please ask-if there's enough interest; wel covert ina lecture. Weld even be happy to have you contribute tothe course documentation! Tak to an instructor to find out how. (U) Table of Contents (U) Part |: Python Basics (Week 1) + (U) Lesson 01: Introduction: Your First Python Program + (U) Lesson 02: Variables and Functions © (U) Optional: Vasable Exercises © (U) Optional: Function Exercises + (U) Lesson 03: Flow Control © (U) Optional Fw Control Exercises (U) Lesson 04: Container Data Tynes ‘| + (U) Lesson 08: Modules. Namespaces and Packages © (U) Supplement: Modules and Packaoes + (U) Lesson 08: Exceptions, Profling and Testing + (U) Lesson 10: teraors. Generators and Duck Typing © (U) Supplement: Pioeining wih Generalors + (U) Lesson 11: Sting Formatting =“) Part I: Useful Modules (Week 2) + U) EERE Module: Cotectons and tertoois @ (U) Supplement: Functional Programming + (U) Supplement: Recursion Examales una ‘© (U) Supplement: Maninulating Microsoft Office Documents wih win’2com + (U) Module: Threading and Subprocesses + (U#FOweYDstdbutig a Python Package at NSA + (U) Modula: Machine Learning ntoduction (U) Homework + (U)Day1 Homework Please Enter Footer Text... ‘Doe ID: 6689692, * {Uy Day.2Homewors (U) Exercises (with Solutions) (U) Class Projects (U) Glick nore to get to @ notebook containing instructions for password checker and password generator projects. (U) Project Ideas + (U) White a currency conversion script + (U) Write a web application + (U)DoProject Euler problems + (U)Eind Anomalous Acivily onthe BigCorm Network + (U)BSA Encrymtion Module, Par 2 + (U) Pick project rom one of the Safari books below (U) General Resources (U) Python Language Documentation (UHFEYE}NSA Course Materials (©) Dive into Python (U) Exe ython Programming (Head First Python (U)HHion Performance Pytnon (advanced) ()Leaming Python {(U) Leaming Python Programming (videos) + (U)Prooramming Python + (U)2ytnon Crash Course (includes 3 sample projects) + (U)2ytion Piayoround (more sample projects) (U) 2ython Packet Reference (consider geting a print copy) (U) 2ython Programming fr the Absolute Beginner (even more sample projects, games & quizzes) * (U) and More Python Programming forthe Absolute Beginner + (U)Thing Python + (U) Safar Books (General Query) (U) Other + (U)Einal Project Schedule Generator + (U) Justa ite notebook fr randomly generating a schedule for students to present their nal projects for COMPS321, (U#FOUE) The Pyinon coun on NSA Gitkat (U) The Hitchhiker's Guide to Python! (U#FOVO) Pyinon on Wisinio (U) Python on StackOveriow (U) Addtional targeted resources (often excerps from the'sbove)aredinkédn eactriesson and module. ere 86 Doe UNCLASSIFIEDHFOR OFFICIAL USE-ONLY- oe ID; 6689693 Lesson 01: Introduction: Your First Python program a (U) Covers Anaconda installation, the python interpreter, basic data types, running code, and some built-ins. UNCLASSIFIED//FOR-GFRHIGIALUSE-ONEY (U) Welcome To Class! (U) Lets get to know each other. Stand up and wai for instruction, (U) Who has a specie project in mind? (U) Method 1: Anaconda Setup (U) Aternately, flow tis tradecrat hub arte, ios production \radecrafproj.nsa ie. govlentry/29475 (U) We will be using version 4.4.0 ofthe Anaconda Python dstrbution, availabe from Git Software. Anaconda includes many packages for large~ ‘scale data processing, predictive analytics, and scientific computing (U) Installation Instructions ‘Approved for Release by NSA on 12-02-2019, FOIA Case # 108165 es EU) Click onthe lnk above 2.{U) Glick on the “Download Now” button 53. (U) Accep the agreement and click "Next 4.(U) Click Next 5. (U) Download "Anaconda3-4.8.0-Windows-x86_64 exe 6-(U) Open the folder containing the download (pica ths is your “Downloads” folder) 7 (U) Doublecick the Anacondas-4.4.0-Windows-186_64.exe le 8 (U) Click "Nex?" to Start the installer 8. (U) Glick the" Agree” button to accept the icense agreement 10.(U) Choose to install for “Just Me" and cick "Next™ 11, (UHFOUS) Select a destination folder on your U:crive (such as U\prvatelanacondad) 4. (U#EOUO} Cick the "Browse." butlon, Gck on "Computer" and selec the U: drive 2 (UAFOUO} Select "My Documents" and press "OK" [Note: DO NOT Make a folder named anaconda3) '3. (UAFOUE} n the Destination Folder input area add “anacondad" asthe folder name 4. (UMPUE}Clck Next 12.(U) Cick instal to begin the install eave checkboxes a fs) 13 (U) Wait about 30 minutes for the instal complete 5 (U) Running python deceeeeeee? (U) You can run python directly on yourfET Pisskop and immediately interact with it 4. (U) Open a Windows command window (Type “cma” in the Windows Programs search bar) 2 (U) Type “python” inthe command window (U) Running Jupyter (U) Aterately, you can run python in a browser from a web-enabled python called a jupyter notebook, Tit Wc Gory: "or Wis Cass, however, we each ‘Sar up aur own ndiiGual Jupyler web: portal ofan Our Glass novebooks. 4. (U) From the Windows Start menu, search for "upyter 2 (U) Right-click on Jupyter Notebook inthe resulis and select Properties 3. (UHFOUS) in the “Target field, add" uprivat” atthe end (ater "notebook’) [Note: don't forget the space before u:prvate] 4 (U) Chick Apply and then OK 5. (U) Search for jupyter again in the star menu and click on Jupyter Notebook to run it 6. (U) Wait a few moments...This should launch Jupyter in your browser at ili. localhost 8888 (U) Method 2: LABBENCH Setup oc ID: 6589693 (UHFEUSE} Step 1: Access to LABBENCH + (U#FOUO) 90 inoree and read and accept the INHERE User Agreement. (U#FEUO} This s a prerequisite for access to LABBENCH, a VM system where we willbe working. It may take a few hours forthe approval to propagate through the system. (U) Step 2: Visit Jupyter Gallery 41. (UAFOUO} 90 junviee 2 (U) Glick on the Jupyter Gallory logo to get to the Gallery 3. (U) Click on Tour the Gallery for quick demo. 4. (UFOS) To find the course notebooks, either search for “Syllabus” or choose Notebooks > Learning > COMP 3321 and sor by title to find the Syllabus. (U#FOUG} Step 3: Set up Jupyter on LABBENCH (U#FOUO) At the Jupyter Gallery, click “Jupyter on LABBENCH™ for a tutorial on howto get set up. (U) Basic Basics: Data and Operations (U) The most basic data types in Python are: + Numbers © Integer (these are “arbitrary precision"; no need to worry whether i's 92 bits or 64 bits, etc) © Float (using 1) forthe imaginary number) + Stings © No iflerence between single and double quotes © Escape special characters (e.g. quotation marks) © Raw sting r'raw string” prevents need for some escapes, © Thiple-quotes allow mutiple line strings © Unicode u'aert \x26 Ernie’ ctype ‘unicode'> + Booleans: true and False (U) We operate on data using + operators, e.g. mathematical operators +, - ; the Keyword in, and others DeclD: 62 functions, which are operations that ake one or more pieces of data as arguments, ©, ‘ype("heLlo") , Ien("worls") , and + methods, which are atached toa piece of data and called from itusing a. to separate the data from the method, e.g. "Hello World”. sp1ie() , oF *abe’ -upper() (U) Deep in the guts of Python, these are all essentially the same thing, but syntactically and pedagogically it makes sense to separate them, (U) Pisces of basic data can be stored inside containers, including + Late + Dictionaries + Sets ‘but well ntroduce those later. (U) The Interactive Interpreter \with that basic background, let's try some things in your Windows command window. Us\privaterpython Python 3.5.1 [Anacondo 2.5.0 (68-b{t)| (default, Jan 29 2016, 15:01:46) [KSC v.1900 64 bit (ANDSA)] on win32 Type “help”, “copyright”, “credits” or “license” for more inforsation. ‘typet5e7) sype(7-1 - 2.2) as 4 this changed tn pythons aB//s nelle” + * wort nelle * + 20 (U) Executing code in a file eo I: 699603 Open the fle Fiest-progran. (U) Ifyou dont have a favorite editor do this: 41. (U) Go to your Jupytr porta at hit. /localnost 8888!roe 2 (U) Pull down the “New” button menu and choose “Text Fle" 3. (U) Click on the "Untitled! et" name and enter the new fle name as “ist-program py" (or anything ending with .y )n your favorite editor (Iuse enacs , but you can use whatever you want), {(U) Type some Python statements int so {(U) Don't forget to save it (File>Save from Jupyte). (U) Torun it, give the fle name as an argument to Python: ‘Make sure the command window is referencing the same folder as the fle. That is U\prvate for most. Hf your command window isnot referencing U:\pivate, do tis: 1 Enter "U 2. Enter “cd private* U:\privatespython Fist-progran.py (U) Nothing appears to happen, because auto-prnting ofthe output ofa function only happens in the interpreter. Fix it up: print(5e7) print(9r43) printcarsi2) (U) Built-in functions and methods (U) Some functions work on almost any arguments that you supply: ‘+ elp(x): shows interactive help ‘+ dir(x): gives the directory of the object, Le. al the methods available + typa(x) tls you the type of x —a type's almost the same as any other object + Ssinstance(a,0) tel fobject a is an instance of & , which must be a type ; something like type(s) = + print ‘+ hasater(a,b): tells whether a has something by the name ; something like & in din(a) + getatr oc ID: 6559693, sa + snput (U) Constructor functions usually tr to do their best with the argments you give, and retum the appropriate data ofthe requested type: ‘+ str tums numbers (and other things) into their sting representations ‘+ Ant: tuncates float , parses str ings containing a single integer, with optional radix (Le. base), eror on complex + lost: parses strings, qlves oat representation of int , eroF on complex ‘+ complex: takes (real, imag) numeric arguments, or parses a str fora single number (U) Other functions only work with ane or two types of data + Numbers: ‘© Functions: abs, round, float , max, min, pow (modula), chr dimes, ete © Operators: Standard math, bitwise: <<, >>, ‘> Methods: Numeric classes don't have methods + Stings: © Functions: ten, ain, max, ord © Operators: +, * (with a number), 9 © Methods: strip, split, startswith, upper. find (U) Exercises: 1. Make a shopping list of ive things you need at the grocery store. Put each item on its own line in a cel. Remember to use quotes! Use print() so that each of your tems displays (ty it frst without). 2. Your groceries ring up as 9.42, 5 67, 3.25, 13.40, and 7.50 respectively. Use python as a handy calculator to add up these amounts 3. But wait You decide you to buy five of th last tom, Re-calculato your total, 4 Using the 1en() function, determine the number of characters inthe string "blood-oxygenation level dependent functional magnetic resonance imaging" (Fun fact: this string isthe longest entry in WordNet 1 index). 5. Pick your favorite snack. Use the * operator to print 100 copies of i. Modify your code to have them print with spaces between them. 6. Challenge: Run >> IsDivisibleBy7(21) Tne >>> isDivisibleBy7(25) False (U) White a function sspivisibiesy(num, divisor) to check if num is evenly divisible by divisor. >>> eDiveibleBy(35,7) True >>> isDivsibleBy(35,4) False (U)Make a function snoue(wora) that accepts a sting and returns tha >>> shout("bananas") ‘BANANAS? ting in capital letters with an exclamation mark. (U) Make a function introduce) to ask the user forthe name and shout it back to them. Call your function shout to make this happen. >>> What's your name? >>> Bob HIBo8! Dec ID: 6589693 Lesson 2 - Variable Exercises (U) Variable Exercises for COMP3321 Lesson 2 (U) Lesson 2 - Variables Exercises (U) Identity the type of each ofthe folowing variables, and add the type after each variable in a comment. > (U) What vale is in variable my_var at the end ofthese assignments? [Add a comparison after the last statement in the form of my_val = oc ID: 6689683, myvar = 99 yvar saa ry_var = ste(ay_var) myvar “= 2 sy_var = Len(ey_var) myvar *= 6 oc ID: 6589693 Lesson Mase Flow Control peer gy voor e00 orf Ti Ge saat = (U) Python flow control wth conditionals and loops (i, wile, for, range, et). UNCLASSIFIED (U) Introduction (U) you have ever programmed before, you know one of the core building blocks of algorithms is flow contro. It tells your program what to do next based on the stat tis currently in (U) Comparisons (U) First. let's lok at how to compare values. The comparison operators are >, >=, <, <=, I=,and == ..When working with numbers, they do ‘what you think: tum True oF False depending on whether the statement is true oF fale. Doe ID: 6689493 (G)Byinon 2x wilt you try to compare any two objects, no matter how ifferent. The results may not be what you expect. Python 3.x only ‘compares types where a comparison operation has been defined. ‘apple’ > “orange” # cose-sensitive alphabetical ‘apple’ > ‘Orange’ ‘apple’ > (‘orange’] ‘apple’ > (‘orange’) (U) We wi leave more discussion of comparisons for later, including how to inteligently compare objects that you create (U) Exercises 1. Write @ you son function that randomly picks a number from your price ist (9.42, 5.67, 3.25, 12.40, and 7.50) and prints. Tese or False depending on whether the random number is greater than 10. 2 White a function snack check that takes string snack and retums ‘True Or False depending on whether ornotitis your favorite snack (U) Conditional Execution: The if Statement {(U) The i statement is an important and useful tol. basically says, "Ifa condition Is rue, do the requested operations" ‘def even(n): AF (982 == 0): ‘rint(*T an even!*) even(2) even(s) ‘even( hello") # tat wos silly (U) What if we want to be abe to say we are not even? Or the user submitted a bad type? We use else and elif clauses ec ID: 6689693 ef even(n): AF (typen) I= Ant) print("T only talk about integers") alte (0 2 == 0): print(*T an even!") se: print(*T an oat") ceven(2) ceven(3) ceven(‘hel1o") (U) Exercises 1. Re-wnite the snack check to take a sting snack and prints an apporpriate response depending on whether the input is your favorite snack or not 2 Wiite an in_grocery_1ist function that takes in a grocery_sten prints a diferent message depending on whether grocery_iten isin your grocery list. 3. Modify in_grocery. list to testi grocery_tten isa sting. Print a message warring the user fits not 4 Challange: Re-write the you won function fo randomly choose a number from your pies list and print appropriale message depending on whether you won (the number was greater than 10) oF not. Also include the amount of change you willbe receiving in your message. (Recall you are winning the amount change you would have owed... 5. Advanced challonge: Write a function that imports datetine and uses it to determine the current time. This function should print appropriate message based onthe time exif the curent tie is between 0900 and 1000, print the message "Morning Lecture time! (U) Looping Behavior (U) The while Loop (U) The while is used for repeated operations that continue as long as an expression is tue. (U) The famous infinite loop: while (2 +2 == 4): prine(“forever") (U) Armistake that may ead to an infinite lop: ac ID: 6649693 ino wtde (1 <= 20): print(i) (U) The below is probably a more sensible thing to type. 1-0 wotte (1 rine 1) ed 2): (U) break and continue (U) For more contro, we can use break and continue (they work just a in C). The break command will break out ofthe ‘smallest while oF for loop: tee wetle(trve): ded int (i) reel ‘break 22) (U) The continue command wid halt the current iteration ofthe loop and continue tothe next value iso wide(trve): tea Af (== 10): eint("T an 101") continue print (i) AF (1 => 20): ‘break oe ID: 6559693 (U) The else clause (U) You can also have an else statement atthe end ofa loop. It will be run only if the loop completes normally, that is, when the conditional ‘expression results in False .A break wil skip it. i-0 nite (1 <2): print) ted aise: print("This executes after the condition becones false.") print("Oone!") wntte (4 <2): print) Sf True: ‘break tea ease: Print("This won't print because the loop was exited early.) prine¢"Done!") (U) Exercises Hint you will not need continue oF break for these exercises. 1. Previously we printed out many copies ofa string using the * operator, Use a whe Toop to printout 10 copies of your favorite snack. Each ‘copy can be on it's own line, tha’ fe. 2 Mocand match! Write @ white loop that uses the to print multiple copies of your favorite snack per line. Print out 10 lines with the number ‘of copes per line corresponding tothe line number (your fist line wil have one copy and your last ne will have 10). 3. Challenge: Write a white loop that prints 100 copies of your favorite snack on one single (wrapped) ine. Hint use = (U) The for loop (U) The for loops probably the most used contol low element asi has the most functionality. It basically says, “forthe following expict items, {do something,” We are going to use the listtype here, More interesting properties of tis type wil flow in another lesson. oe ID: 6589688, for 4 im [2,2,344,55'3" print 1) (U) The variable 4 "becomes" each value ofthe ist and then the folowing code is executed for An (2,243,455, °8°,"b°,"e") print(s, type(s) for € Sn “ovat print c) (U) Exercises 1. Wite a for loop that pnts out each character inthe sting "blood oxygenation lave dependent functonal magnetic resonance imaging” {Fun fact ts ting i the lengest ety in WordNet Index). 2 Te your erocor a of ve ems (or cote ene), Writ opt cto the message "Nott sl, buy.“ and then tho grocery em. 3 Write @ for loop that prints outa numbered Ist of your grocery items, 4. Clearly your favorite snack is more important than the other items on your list. Modify your for loop from Exercise 310 use break sto printing once you have found your favorite snack in your list. Question: Could you have achieved the same result without using a break ? Bonus: if your snack isnt inthe lst, have your code print a warning at the end. 5 Challenge: use the string method split to write a. for loop tha pints aut each word inthe string "blood-oxygenation level dependent functional magnetic resonance imaging” Hint: run help(str- 18's just on object! for 4 in range( 10020): (Ln 2 = 0): print 1) b= range(2, 1090000, 100) » be) on be otal (U) Exercises oF se cane to write a for loop to printout a numbered grocery list. 2 Use enumerate to print outa numbered grocery Ist. Youve now done this three ways. What are some pros and cons to each technique’? ‘There are often several different ways to get the same output! However, usually one is more elegant than the other. 3.Use range 10 wile @ for loop that prints out 10 copies of your favorite snack. How does this compare to useing a while loop? ‘4. Challenge: White a "Guess my number” game that generates a random number and gives your user a fixed number of guesses Use input to get the user's guesses. Think about wat loop type you might use and how you might provide feedback based on the user's uesses. Hint: what type does. input return? You might need fo conver this to a more useful type... However, now what happens if your User inputs something that srt a number? UNCLASSIFIED oe ID: 6689653 Lesson 3 - Flow Control Exercises (U) Flow Control Exercises for COMP3321 Lesson 3 (U) Lesson 3 - Flow Control Exercises (U) Change the loop below so that i prints numbers from 1 to 10. for & An range(s) print (1) (U) Using a for loop and enumerate, write a function getindex(string, character) to recreate the string method .index “skyscraper” index(°c") etindex( “skyscraper, "c") ) Using the shout function from the fist set of basic exercises, wite a shout_words(sentence) function that takes a sting argument and "shouts* f2ach word on its own ne. shout_words("Everybody 1ikes bananas”) # eveRve00"! sans! Do ID: 659603 (G)Whte an exeract_longer(ength, sentence function that takes a sentence and word length, then retums alist ofthe sentence's words that ‘exceed the given length. I no words match the length, return False. extract_longer(S, “Try not to interrupt the speaker.”) # ["interrupt', 'Speoker."] lextract_longer(7, “Sorry about the mess.*) false Doe ID: 6589693 Lesson 04: Container Data Types a] ss . | oo (U) Lesson 04: Container Data Types UNCLASSIFIED (U) Introduction (U) Now that we've worked with stings and numbers, we tum out attention to the next logical thing: data containers that allow us to buld up ‘complicated structures. There are diferent ways of puting data into containers, depending on what we need to do with, and Python has several builtin containers to support the most common use cases. Python's builtin container types include: 4. ust 2 wole 3 atet 4 set 5. frozenset (U)Ofthese, tuple and frozenset are immutable, which means that they can not be changed aftr they are created, whether that's by addition, removal, or Some other means. Numbers and stings are also immutable, which should make the following statement more sensible: the variable that names an immutable object can be reassigned, but the immutable object itself cart be changed. (U) To create an instance of any container, we cal ts name as a function (sometimes known as a constructor. With no arguments, we get an empty Instance, which isnt very useful for immutable types. Shortcuts for creating non-emply List 6, tuple 6, dict s, and even set s willbe covered in the folowing sections. ust() oo ID: 6689693 act) tuple() set) (U) Many bulvin functions and even some operators work with container types, where it makes sense. Later on weil see the behind:-the-scenes. "mechanism that makes this work; for now, well enumerate how this works as pat of the discussion of each separate type. (U) Lists (U)A ist is an ordered sequence of zero or more objects, which are often of cifferent types. I is commonly created by putting square brackets. [ } around a comma-separated isto is iia values: ‘spam’, “eggs, 5, 3.2, [100, 200, 300]] fruit = ['Apple’, ‘Orange’, "Pear, ‘Line (U) Values can be added to or removed from the lst in efferent ways: frult.append( Banana") frutt-insert(3, “eherry") frutt-append({ "Kiet", “watermeton’]) fruttcextend({* Cherry's Banana") fruit renove( Banana") ruse ‘rute-por() ‘rute-pop(2) Frutt (U) THe + operator works tke the extend method, except that it retums a new list a frust oc ID: 689693 Feutt (U) Other operators and methods tell how long a sis, whether an element is inthe Ist, andi so, where or how often itis found. ren(Frutt) fruit. append(‘Apple") ‘apple’ An frutt “Cranbercy’ not in fruse srutt.count( Apple") frutt.index<"Apple") _# Careful--con cause an error fruit.index(apple", 1) (U) List Comprehension (U) Great effort has been to make lists easy to work with. One of the most common uses of als is to iterate over its elements with a for loop, storing ofthe results ofeach iteration in a new ist. Pytion removes the repetitive boilerplate code from this type of procedure with list ‘comprehensions. They're best learned by example: [3 for $ sn range(s0)) [3002 for An range(29)] Ua, a2, for 4 in range(0)) (1a, a2, 1099) for 4 am range(ie) #4 x 2]. # conditionalst [{ej for 4 tn “abede"] for j in ‘ay2"] ——# nesting! (U) Sorting and Reordering oc ID: 6589693 {8} Soting is another extremely common operation on lists. Wall covert in greater detail later, but here we cover the most basic builtin ways of sorting. The sorted function works on more than just List, but aways retums a new ist wih the same contents asthe orginal in sorted order. ‘There's also. sort method on Lists that performs an in-place sot. frult.renove({'Kiwi’, ‘Watermelon']) # can’t compare List with str sorted fruit = sorted(fruit) sorted fruit == fruit Frutt.sore() sorted fruit —~ fruit (U) Reversing the order ofa lists similar, with abuit-in reversed function and an in-place reverse method for ist s. The reversed function retums an iterator, which must be converted back into a list expbcily To sor something in reverse, you could combine the reversed and the sorted methods, but you should use the optional reverse argument on the sorted and sort functions. fruit = List(reversed¢Fruit)) fruit reverse() rfruit == frust sorted(r_frutt, reverse-True) (U) Tuples (U)Much tke a 14st, tuple is an ordered sequence of zero or more objects of any ype. They can be constructed by puting a comma- separated list of tems inside parentheses ( ) , or even by assigning a comma-separated list o a variable with no delimiters at al. Parentheses are heavily overloaded-they also indicate function calls and mathematical order of operations-so defning @ one-element tuple i tricky: the one element must be followed by a comma. Because @ tuple is immutable, it won't have any ofthe methods that change lists, ke append oF sort 2 (3, 2, “first and second") rena sorted(a) a index(2) ‘count (2)

You might also like