Lecture Notes: CS 2370: Intro Programming Lecture Notes - Student Version
|
|
- Brandon Joseph
- 5 years ago
- Views:
Transcription
1 Lecture Notes: CS 2370: Intro Programming Lecture Notes - Student Version Kyle Burke January 10, 2018 Contents 0 Course Intro The Course s Textbook Under Construction The Way of the Program Python What is a Program? What is Debugging? Natural and Formal Languages Variables, Expressions and Statements Values and Types Variables Variable Names and Keywords Statements Operators and Operands Expressions Order of Operations String Operators Comments Functions Function Calls Type Conversion Functions Math Functions Composition Created with lecturenotes.sty, which is available at: lecturenoteslatexstyle.php (or, GitHub: Many or most of the answers to questions are hidden so that some of class will still be a challenge for students. 1
2 CONTENTS CONTENTS 3.5 Adding new Functions Definitions and Uses Flow of Execution Parameters and Arguments Variable Locality Stack Diagrams Fruitful and Void Functions Why Functions? Repetition and Turtles TurtleWorld Simple Repetition Exercises Encapsulation Generalization Interface Design Refactoring Docstrings Development Plan Conditionals and Recursion The Modulus Operator Boolean Expressions Logical Operators Conditional Execution Alternative Execution Nested Conditionals Chained Conditionals Recursion Recursive Stack Diagrams Infinite Recursion Keyboard Input Fruitful Functions Return Values Incremental Development Composition Boolean Functions Fruitful Recursion Leap of Faith Example: Fibonacci Checking Types and Guardians
3 CONTENTS CONTENTS 7 Iteration Multiple Assignment Updating Variables while break Square Roots Algorithms Debugging Strings Strings as Sequences len Traversing with for String Slices Strings are Immutable String Searching Counting String Methods in String Comparisons Files and Words Reading a File Exercises Searching Lists Lists are Sequences Lists are Mutable Traversing a List List Operations List Slices List Methods Map, Filter, and Reduce Deleting Elements Lists and Strings Objects and Values Aliasing List Arguments Dictionaries Tuples Case Study: Data Structure Selection 162
4 CONTENTS CONTENTS 14 Files Classes and Objects User-Defined Types Attributes Rectangles Instances as Return Values Objects are Mutable Classes and Functions Pure Functions Modifiers Prototyping versus Planning Classes and Objects Object Oriented Features Printing Objects (Methods!) Another Example (Increment) A More Complicated Example (is after) The init Method The str Method Inheritance Card Objects Class Attributes Comparing Cards Decks Printing the Deck Add, remove, shuffle, and sort Inheritance Class Diagrams Additional Hand Operations
5 0 Course Intro 1 THE WAY OF THE PROGRAM 0.1 The Course s Textbook The text for this class is Dr. Allen Downey s Think Python: How to Think like a Computer Scientist. The second edition of the book just came out and is available at http: //greenteapress.com/wp/think-python-2e/ 1. These notes do not cover all parts of the textbook; I skip parts that I don t get to address during the semester, though I do cover some of the topics in more depth (or just provide additional examples and in-class exercises). 0.2 Under Construction These notes are adapted from teaching using Python 2. Currently many of the examples are in Python 2, but I m working on changing them over to Python 3. There s still much to be done in these notes. Here s a list of tasks that are in progress. Translate the examples/questions from Python 2 to Python 3. The biggest recurring change here is that in Python 3, print is a function instead of just a special command. Adapt to the other changes in the second edition of Think Python. Add more Bonus Challenge problems throughout the notes so that there s (nearly) always something for students to be working on. Make sure the section numbers in here line up with the sections in the Cover Syllabus and Expectations 1 The Way of the Program Welcome to Introduction to Programming! In this class, you are going to learn to write programs! Exciting! More goals: Learn an approach to problem solving, including: stating problems clearly creatively devising solutions clearly expressing solutions 1 PDF (free and legal) available at
6 1.1 Python 1 THE WAY OF THE PROGRAM Learn to think Algorithmically. What s a good way to complete this task? Learn to write computer programs. Sounds tricky, but we re going to do it! 1.1 Python We are going to learn Python, a high-level programming language (like C++ or Java). Def: Low-Level Language A low-level language is something written so the hardware can read it. Examples: machine code or assembly language. Why aren t we learning a low-level language? How does a computer run a program? This slows down processing time a bit, but greatly speeds up the programming time. Two flavors of high-level languages: Interpreted: Source Code Interpreter Output
7 1.1 Python 1 THE WAY OF THE PROGRAM Compiled: Source Code Compiler TODO: draw picture Say something about each! Executable Program Executor Output Which of the two is Python? Why use a compiled language? Two modes for running Python code: Interactive Mode: Chat with Interpreter. chevron {}}{ >>> >>> Script Mode: Store Programs in a.py file. When might you want to use each mode?
8 1.2 What is a Program? 1 THE WAY OF THE PROGRAM 1.2 What is a Program? What is a program? Common types of instructions: Input Output Math Conditional Execution Repetition Every program you ve ever seen is built from these pieces! I will teach you to do this! Since instructions need to be unambiguous, code must be precise and clean. Errors that humans could resolve, computers have a hard time with. 1.3 What is Debugging? Debugging! Bugs : Rear Admiral Grace Hopper. Def: Debugging Debugging: tracking down errors and fixing them. Aside from Termintator-like scenarios, this is the biggest thing people complain about with computers. Three types of errors: Syntax Error. Syntax are rules about structure. Example: >>> 2 + ) 2. Try it out! Like English grammatical errors. Python checks first; one syntax error prevents WHOLE program from running. You ll make lots of these in the beginning, but will get better.
9 1.3 What is Debugging? 1 THE WAY OF THE PROGRAM Runtime Errors. Exceptions. Happen while program is running. Semantic Errors. Program runs and doesn t notice a problem, but it doesn t do what you wanted. Example: Want to print Monkey!, but type: print( Donkey! ). (Have students try this out. How do you know if you have errors in your code? Debugging is hard, but is a useful skill! Even outside of programming! Like forensics: need to find culprit. Error messages give you clues. Debugging is an experimental science: Have an idea about what went wrong. Try to fix it. Run it again to see whether that worked. If not, maybe you need a new idea! The book discusses debugging issues at the end of each chapter. Look there if you re having trouble! Good idea: Purposefully make some mistakes! Learn what happens and become unafraid of errors! Let s do some of that now. Let s try causing some different types of exceptions. Give me a line of code that causes a TypeError. 3 + "3" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: int and str >>>
10 1.3 What is Debugging? 1 THE WAY OF THE PROGRAM Let s talk quickly about the info Python gave us back from this error. Why does it say line 1? The error happened in the first line of the code. If we have a longer program in a script, this could be in a line other than 1. What is Python telling us in the last line of the error message? TypeError: means it was trying to do something, but it couldn t because the types of the values weren t correct. Message (last line): It s saying that it doesn t know how to add an int to a str. You can cause an exception that you create to occur. How does that work? Do something like this: >>> raise Exception("I don t know what I m doing!") Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception: I don t know what I m doing! >>>
11 1.4 Natural and Formal Languages 1 THE WAY OF THE PROGRAM Natural and Formal Languages Def: Natural Languages Natural Languages are those people speak or use to converse with other people. These are designed by people, but come about naturally. Def: Formal Languages Formal Languages are designed by people for a specific purpose, like programming languages. What are other types of formal languages? Formal languages are very strict about syntax. What are examples of syntactically incorrect mathematical and chemical statements, but which use correct words and characters? 2 Source:
12 1.4 Natural and Formal Languages 1 THE WAY OF THE PROGRAM Def: Tokens Tokens are basic elements of a language. For example: words, numbers, chemical elements Def: Structure Structure is rules for arrangement of the language s Tokens. Pulling apart statements to analyze structure and tokens is called parsing. We do this unconsciously in English! Three properties of languages: Ambiguousness Literalness Redundant Which of these is: more ambiguous? more literal? more redundant? Informal Formal: Poetry Prose Programs Reading Code is Hard! Why?
13 2 VARIABLES, EXPRESSIONS AND STATEMENTS You will learn to deal with all of these things! You will both READ and WRITE code well! Debugging: you will get frustrated. People often respond to computers as though they were people! Errors are Rude! They will not always be clear! Computer is good at speed, not good at empathy! Sleep on it if you have to! Take a walk. Change the music you re listening to. Switching your environment can often help you change the way you re thinking. 2 Variables, Expressions and Statements 2.1 Values and Types Def: Values Values are basic data used by a program. >>> That uses the values 1 and 2. In lab, used value: Hello, World! There are different value types: 1,2: integers Hello, World! : string. string of letters. Strings are always in quotes! Sometimes you need double-quotes in strings >>> That s all folks! Syntax Error! >>> "That s all folks!" Python can identify types for you! >>> type( Hello, World! ) <class str > >>> type(42) <class int >
14 2.1 Values and Types 2 VARIABLES, EXPRESSIONS AND STATEMENTS What s going to happen here? >>> type(3.25) float means Floating-Point. That means it s a number with a fractional part. What s going to happen here? >>> type( 3.25 ) Why? >>> print(42) 42 >>> print( 42 ) 42 >>> print(1,000,000) 1 0 0
15 2.2 Variables 2 VARIABLES, EXPRESSIONS AND STATEMENTS What happened there? What kind of error did I get? >>> type(1,000,000) Traceback... What happened there? What kind of error did I get? 2.2 Variables Def: A variable is named storage for a value. Create variables with assignment statements: >>> message = I love variables! >>> number = 42 >>> pi =
16 2.3 Variable Names 2 and VARIABLES, Keywords EXPRESSIONS AND STATEMENTS Add and describe: state diagram! What will happen when I try:? >>> print(message) What about:? type (pi) 2.3 Variable Names and Keywords Variable Names must be: Legal. Illegal things include: >>> 3age = 84 SyntaxError: invalid syntax. Variable names must begin with a letter! >>> phone@home = is an illegal character! >>> important variable = 42 No spaces! Use snake case! >>> important variable = 42
17 2.4 Statements 2 VARIABLES, EXPRESSIONS AND STATEMENTS >>> import = cupcakes import is a keyword: full list in the book. Meaningful! Variable names should describe the purpose or role of the variables. Which of the following variable names is best? number = 5 number of tigers = 5 number of tigers at zoo = 5 A common convention is to drop the ber of part, so you could name your variable num tigers at zoo and that s completely fine. 2.4 Statements 2.5 Operators and Operands We can use operators with values and variables. Math operators include: +, -, *, /, **.
18 2.5 Operators and2 Operands VARIABLES, EXPRESSIONS AND STATEMENTS >>> >>> 3**2 9 >>> number-3 39 >>> 1/2 0 >>> 1.0/2.5 >>> 1.0 // >>> What s going on with these last two? The // operator divides and removes any remainders. The last one is the closest number Python can recognize near.3.
19 2.6 Expressions 2 VARIABLES, EXPRESSIONS AND STATEMENTS Expressions These are all expressions: combinations of values, variables and operators. (2*7)*(1+2) In interactive mode, after typing in an expression, interpreter evaluates and displays. Script mode: no automatic displaying. Alone, an expression doesn t do anything. 3 Source:
20 2.7 Order of Operations 2 VARIABLES, EXPRESSIONS AND STATEMENTS 2.7 Order of Operations Without trying them out, what is the result of each of these? (Write them on the board.) 2**2*2 (2**2)*2 2**(2*2) 5/ *1+1**1 1*(1+1)**1 I always use parameters to make things clear! 2.8 String Operators Some of these work on strings too!
21 2.9 Comments 2 VARIABLES, EXPRESSIONS AND STATEMENTS >>> last name = Stickney >>> print( 2 + last name) 2 Stickney >>> print(3* Monkey ) MonkeyMonkeyMonkey String adding is known as concatenation. Sometimes you want to print strings and non-strings in the same line. print can do this! (In script) number of squirrels = 5 print I have, number of squirrels, squirrels, isn t that nice? What happens when you run this? What if I change the 5 to a 75 and rerun it? 2.9 Comments Code can be tough to read! Expressions are complex Whole sections can be complex Solution: Comments!
22 2.9 Comments 2 VARIABLES, EXPRESSIONS AND STATEMENTS Def: Comment A comment is a note to yourself and other programmers, but not to Python. In script: #compute the circumference of the circle circumference = 2 * radius * pi Or it can be on the same line: area = pi * radius**2 #area of a circle # symbol tells the interpreter to ignore the rest of the line. For humans, but not machines! What is wrong with these? monkey = 16 #assign monkey to 16 monkey = 16 #monkey is driving time to Indianapolis in hours What would be better? TRADEOFF! Variable names vs. comments longer variable names: easier to understand the role shorter names: expressions are easier to visually parse In general, I err towards longer names 4. 4 Excellent list of useless comments here: the-least-useful-comments-ever/
23 3 Functions 3 FUNCTIONS Def: Function In programming, a function is kind of like a subprogram: Like a program, it also a sequence of instructions...but, has a name like a variable 3.1 Function Calls You can use or call functions inside a program once they re defined. >>> type(42) <type int > Let s dissect this: function name parens {}}{{}}{ >>> type ( 42 ) }{{} argument <type int > }{{} return value or result Say: function takes argument and returns the result. 3.2 Type Conversion Functions Some other functions are already defined in Python. For example: Type Conversions! Sometimes you want to convert a variable from one type to another. >>> int(3.0) 3 >>> int( ) 2 >>> int(42.7) 42 How would you describe what the int conversion function does to floating-point values?
24 3.2 Type Conversion Functions 3 FUNCTIONS Test-Focus: What could we do to test this in a new way? >>> int(-3.45) -3 What do you think it does now?
25 3.2 Type Conversion Functions 3 FUNCTIONS For each of these, guess at what you think the value is that s returned, then try it out: >>> float(3) >>> float(42.7) >>> str(32) >>> str(32.0)
26 3.3 Math Functions 3 FUNCTIONS Do the same for these: >>> int("34") >>> float("34.0") >>> int("34.0") >>> float("34") What will happen with the call int( monkey )? 3.3 Math Functions Also, you might want to use some popular math functions: logarithms, trig, square root. They exist in math module. Def: module A module is a collection of pre-defined variables and functions.
27 3.3 Math Functions 3 FUNCTIONS Loading the module is easy! >>> import math Just like a variable, this is cleared when we restart interactive mode by running a script. If you use math in your script, put import math at the top. >>> math.pi This is the closest number to pi that Python can represent, stored in the variable math.pi. Many useful math functions! Say we want to find the sine of 1.5 (radians). >>> math.sin(1.5) dot notation math }{{} sin(1.5) }{{} package name variable or function call We can use variables as the arguments! >>> radians = 1.5 >>> math.sin(radians) math.sin expects the argument to be in radians. What if I have the number of degrees instead? Help me fill in the following code! (In script) import math degrees = 200 radians =... print(math.sin(radians))
28 3.4 Composition 3 FUNCTIONS This should print: How hard is it to change this script to try it with a different number of degrees? 3.4 Composition You can also use expressions inside arguments! In interactive mode, how do I compute this: ? You can also use function calls inside other expressions! What about 3 6? If I wasn t sure that my solution was correct, I could check in two lines: >>> x = math.sqrt(3) >>> x/6...
29 3.5 Adding new Functions 3 FUNCTIONS ( What about: sin ) 1? >>> x = 1.5**2 >>> y = x / 2 >>> z = math.sin(y) >>> z What about: cos ( 1.21 )? Composition! You can have multiple levels of composition! We saw the issue with trying to convert "34.0" into an int. However, int(34.0) isn t a problem. How could we use this to get around the first problem? 3.5 Adding new Functions What if no function does what you want?
30 3.5 Adding new Functions 3 FUNCTIONS (In script!) def printfavoriteword(): print( monkey ) Let s look more closely! Break down: keyword space function name parens {}}{{}}{{}}{{}}{ colon {}}{ def printfavoriteword () : }{{} header body {}}{}{{} print( monkey ) indent Although you can define functions in interactive mode, it s better to use script mode! >>> printfavoriteword() monkey A function body can have multiple lines! (In script!) def printfavoritewords(): print( monkey ) print( bonus ) print( awesome ) Run the script, then: >>> printfavoritewords() monkey bonus awesome What happens if you define printfavoriteword twice? (Add to bottom of script) def printfavoriteword(): print( awesome )
31 3.5 Adding new Functions 3 FUNCTIONS Which word will be printed when I call printfavoriteword? Delete the second definition from the script. How could you write the function, printkylesfavoritewordtwice that printed out my favorite word twice? >>> printkylesfavoritewordtwice() monkey monkey When I wake up tomorrow, what if I change what my favorite word is? I change printfavoriteword but not the others! Can I change printfavoritewords so that this isn t a problem? >>> printkylesfavoritewordtwice() monkey monkey Another form of function composition!
32 3.6 Definitions and Uses 3 FUNCTIONS 3.6 Definitions and Uses (I skip this section in class.) 3.7 Flow of Execution Let s look at how this works! Flow or Thread of Execution! Demonstrate flow, first on printfavoriteword, then from printkylesfavoriteword Function calls are like detours. When you are reading a program, be sure to follow the flow. At a function call, read through the call before continuing. 3.8 Parameters and Arguments So far, we haven t shown how to use arguments! math.sqrt( argument {}}{ 25 ) Load the chapter3 code! For exmaple, maybe I want a function that greets a friend: (Interactive) >>> greet( Bob ) Hi, Bob! >>> greet( LuAnn ) Hi, LuAnn! Solution: Parameters! (We ll work on defining greet in a little bit; hold on.) Def: Parameters Parameters are variables that are assigned to the arguments of a function. (On board) def printtwice(message): print(message) print(message)
33 3.9 Variable Locality 3 FUNCTIONS What will happen when we do this? >>> printtwice( spam ) Try it out! Write the function in script mode and then call it in interactive mode! What does the following function call do? >>> printtwice( Spam * 4) Follow Up! What is the value of message inside the function? What about the following? myname = Kyle greet(myname) 3.9 Variable Locality Note: parameters are local! They do not persist outside of the function!
34 3.9 Variable Locality 3 FUNCTIONS >>> message Error! A common error with parameters is to redefine the variable! def printtwice(message): message = spam print(message) print(message) Now printtwice only works with spam! >>> printtwice( spam ) spam >>> printtwice( spamalot ) spam This is common! Don t redefine your parameters! >>> greet( Bananaman ) Hi, Bananaman! >>> brag about( Elman Bashar ) Wow, Elman Bashar is definitely the coolest person I know. They are just so awesome! >>> How can we write the greet function? Header: def greet(name): Bonus Challenge: brag about Problem here?
35 3.9 Variable Locality 3 FUNCTIONS How can we fix this? Hint: use string concatenation. What if name is not a string? >>> greet(5) Error! How can we fix this? Hint: use type conversion! Try out the following cases >>> name = Kyle >>> greet(name) Hi, Kyle! >>> greet( name ) Hi, name! >>> greet(name) Error!
36 3.9 Variable Locality 3 FUNCTIONS >>> greet whole name( Kyle, Burke ) Hi, Kyle Burke! >>> greet whole name( Ash, Ketchum ) Hi, Ash Ketchum! >>> super brag about( Elman, Bashar ) Wow, Elman Bashar is definitely the coolest person I know. They are just so awesome! Elman can jump through hoops of fire and once bested a Siberian Horsetiger in a game of Chessboxing! How can I write the body of the greet whole name? Header: def greetwholename(first name, last name): Bonus Challenge: super brag about. Or, could create a new variable inside the body. def greet whole name(first name, last name): whole name = str(first name) + " " + str(last name) print( Hi, + whole name +! ) Did I make a mistake by not putting str(whole name) in that last line?
37 3.9 Variable Locality 3 FUNCTIONS Which one do I like better? Can we do even better? Which function body does the last line of the last greet whole name look like? Could we replace with a call to greet? Why is this considered better? Actually a big part of Software Design. When I change code, try to change it in fewest places possible. Good code allows for this!
38 3.10 Stack Diagrams 3 FUNCTIONS >>> first name = MC >>> greet whole name(first name, Frontalot ) Hi, MC Frontalot! >>> print(first name) MC >>> print(whole name) Error! Why did I get that error? Why not with first name? >>> greet whole name( Mr., first name) Hi, Mr. MC! 3.10 Stack Diagrams Things can get confusing! Sometimes we need to keep track of variable locality. Use a stack diagram! Do stack diagram for the last code example. main One more for greet( Steve ). Your turn! (script) def concatenate twice(message one, message two): full message = message one + message two print twice(full message)
39 3.11 Fruitful and Void Functions 3 FUNCTIONS What do the stack diagrams look like for this call? >>> spanish = Hasta la vista, >>> english = baby. >>> concatenate twice(spanish, english) Try it out and check with your neighbors! Stack diagrams very helpful for figuring out what went wrong! Use them on projects! 3.11 Fruitful and Void Functions There s still something different about the math functions we used! >>> math.sqrt(16) 4.0 >>> math.sqrt(math.sqrt(16)) 2.0 What s different? Def: Fruitful and Void Fruitful functions return a value. Void functions do not (they actually return None). I could write that last part as: >>> x = math.sqrt(16) >>> math.sqrt(x) 2 I wanna do that too! So far: we can t! Try: >>> greeting = greet( Hercule ) Hi, Hercule! >>> print(greeting) None
40 3.12 Why Functions? 4 REPETITION AND TURTLES None is a special value: represents no actual, usable value (nothing was assigned). It even has it s own type! >>> type(none) <type NoneType > Def: void The functions we ve written are void, which means they have no return value. We will write fruitful functions soon... in chapter Why Functions? Why do we want to write functions anyways? 4 Repetition and Turtles In programming, there is lots of repetition! For example, we might want a function that greets multiple times!
41 4.1 TurtleWorld 4 REPETITION AND TURTLES >>> greet n times( Steve, 5) Hi, Steve! Hi, Steve! Hi, Steve! Hi, Steve! Hi, Steve! >>> greet n times( Michaelangelo, 3) Hi, Michaelangelo! Hi, Michaelangelo! Hi, Michaelangelo! 4.1 TurtleWorld In the next lab, you will steer a turtle! Turtles like to draw! You will need to copy and paste the following lines from the syllabus: (In script) import sys sys.path.append( \\Computer Science\\PythonPackages\\swampy.1.1 ) from TurtleWorld import * WARNING: do not name your script TurtleWorld.py Now I can create a Turtle and get it to do stuff! Notice: some PascalCase coming up used for class names. Classes are more complicated types. >>> world = TurtleWorld() >>> bob = Turtle() >>> fd(bob, 100) >>> rt(bob) >>> fd(bob, 100)
42 4.2 Simple Repetition 4 REPETITION AND TURTLES What would it take to draw a square with side length 50 and end up facing the same way we started? 4.2 Simple Repetition Lots of repetition! Same thing four times! Let s simplify with for! >>> for i in range(3): print( Monkey ) Monkey Monkey Monkey How can we use this to condense the square-drawing program?
43 4.2 Simple Repetition 4 REPETITION AND TURTLES Break down: keyword space number of iterations {}}{{}}{{}}{ colon {}}{ for i in range(4) : }{{} header body {}}{ fd(bob, 50) }{{} rt(bob) indent This is known as a for loop. Why is this helpful? Change it, how? How many places would we have to change it before? How many now? Huge improvement! We can put a loop inside a function!
44 4.3 Exercises 4 REPETITION AND TURTLES How would you write greet n times? Header: def greet n times(name, n): Let s do the same for our turtles! Let s draw squares with side length Exercises 4.4 Encapsulation >>> bob draw square() <bob draws a square of side length 100> >>> bob draw plus sign() <bob draws a plus sign> Implement it! Bonus challenge: bob draw plus sign >>> bob draw hexagon() <bob draws a hexagon with side length 100> >>> bob draw star() <bob draws a star>
45 4.4 Encapsulation 4 REPETITION AND TURTLES Implement bob draw hexagon! Hint: try: rt(bob, 30). Bonus challenge: bob draw star Next: let s make these functions more useful! We might do a lot of square drawing. Perhaps we are drawing lines for four-square! Before our function creation, our code might have looked like: for i in range(4): fd(bob, 100) rt(bob)... for i in range(4): fd(bob, 100) rt(bob)... for i in range(4): fd(bob, 100) rt(bob) We simplified this by replacing the repetitive code with function calls! Now our code might look like: bob draw square()... bob draw square()
46 4.5 Generalization 4 REPETITION AND TURTLES... bob draw square() Known as Encapsulation. Def: Encapsulation Encapsulation: repeated code block put code in function, replace blocks with function call. 4.5 Generalization Now, what if we have two turtles? Could have two functions. >>> bill = Turtle() >>> fd(bill, 150) >>> bob draw square() >>> bill draw square() Is there a better option? >>> draw square(bob) >>> draw square(bill)
47 4.5 Generalization 4 REPETITION AND TURTLES Implement it! Header: def draw square(turtle): Bonus Challenge: update to draw hexagon, draw star, and draw plus sign This is Generalization! Def: Generalization Generalization: function specific to one value function applicable to different values by adding parameters Can we generalize draw square further? >>> draw square(bill, 25) >>> draw hexagon(bill, 35) >>> draw plus sign(janelle, 100) >>> draw star(bob, 50) Implement it! Header: def draw square(turtle, side length): Bonus Challenge: same for draw hexagon, draw plus sign, draw star.
48 4.5 Generalization 4 REPETITION AND TURTLES Which two functions are very similar? Should we generalize these into one function? >>> draw polygon(bob, 9, 30) >>> fd(bob, 100) >>> draw polygon star(bob, 7, 30) Which parameter are we adding?
49 4.6 Interface Design 4 REPETITION AND TURTLES Implement it! Header: def draw polygon(turtle, num sides, side length): Hint: total angle degree is 360. Bonus Challenge: draw polygon star >>> draw box stack(bob, 5, 30) >>> rt(bob) >>> fd(bob, 100) >>> draw box grid(bob, 5, 30) 4.6 Interface Design Let s try drawing a circle! Let s approximate (often the best we can do with computers) by drawing a polygon with lots of short sides. >>> for i in range(180): fd(bob, 4) rt(bob, 2) Is this something we might do a lot?
50 4.6 Interface Design 4 REPETITION AND TURTLES What should we do, then? >>> bobdrawcircle() Do it! Header: def bobdrawcircle(): Can we rewrite this by calling drawpolygon? Hint: in the book What should we do to improve bobdrawcircle? First, let s rewrite to use any turtle.
51 4.6 Interface Design 4 REPETITION AND TURTLES >>> drawcircle(bob) >>> sally = Turtle() >>> drawcircle(sally) Implement it! (Change the original one!) Header: def drawcircle(turtle): Now the radius! More tricky, need to calculate the circumference! >>> drawcircle(bob, 50) >>> drawcircle(sally, 125) Implement it! (Change the original one!) Header: def drawcircle(turtle, radius): Hint: last line is: drawpolygon(turtle, numberofsides, sidelength) Double Hint: It s in the book!
52 4.7 Refactoring 4 REPETITION AND TURTLES Should we generalize to add numberofsides as a parameter? Is this appropriate? >>> drawcirclebad(bob, 75, 50) >>> drawcirclebad(bob, 100, 12) Is this appropriate? turtle and radius describe what is to be drawn. numberofsides describes how functions should always work. Arguments should tell them what to do, but not necessarily how to do it. Assume they know best how to do it already! Def: Interface A function s interface includes what a function does, arguments and a return value, if any. 4.7 Refactoring 4.8 Docstrings (Order swapped with Develpment Plan.) Interfaces should be as uncluttered as possible. Use docstring to describe a function s interface! Def: docstring A docstring is a string used to describe a python function s interface. It should be in triple quotes and belongs directly after the header.
53 4.9 Development Plan 4 REPETITION AND TURTLES (On board) def greet(name): Prints out a greeting to someone called name. print( Hi, + str(name) +! ) Notice, it s still indented over! Try adding a docstring to drawsquare! docstrings: use triple quotes, so it can be a multi-line string! explains what, but not how. shouldn t be too hard to write. If it is, indication of inappropriate function. do for all functions! I will now deduct points if they re not there! An Interface is a contract between the function and the user. User promises to provide appropriate arguments. Function promises what it will do/accomplish. 4.9 Development Plan Now we have a good plan for writing programs: Write a small program with no functions. Get it working.
54 Encapsulate it into a function. 5 CONDITIONALS AND RECURSION Generalize the function by adding parameters. Start writing the next part of your program outside of any function. Repeat the steps above to build a complete set of functions. Look for places to rework your functions to improve interfaces and remove code re-use. When writing functions, use the following order: Write the header. Write the docstring. Add the body. This way you know what you re expecting your function to do logistically. 5 Conditionals and Recursion 5.0 The Modulus Operator New Math: >>> 13 / 4 3 ("Quotient") >>> 13 % 4 1 ("Remainder") Def: % % is the modulus operator. >>> 12 % 3 0 >>> 100 % 20 0
55 5.1 Boolean Expressions 5 CONDITIONALS AND RECURSION When is x%y zero? 5.1 Boolean Expressions New Data Type: Booleans! Used to represent Truthiness. Only two values: True and False >>> True True >>> False False >>> type(true) <type bool > >>> not False True >>> x = True >>> x True >>> not x False We can have expressions that return a boolean value! For example, test whether two things are equal!
56 5.2 Logical Operators 5 CONDITIONALS AND RECURSION >>> 5 == 5 True >>> 5 == 6 False >>> 5 < 6 True >>> 5 > 6 False >>> 5 >= 6 False >>> not (5 == 6) True Note: HAVE to use double equals when testing for equality! >>> 5 = 6 Error! >>> x = 4 >>> y = 8 >>> not (x == y) True >>> x!= y True 5.2 Logical Operators We also have operators that take booleans: and, or, not. >>> True or False True >>> False or False False >>> True and False False >>> True and True True >>> not (False and False) True
57 5.2 Logical Operators 5 CONDITIONALS AND RECURSION What are some other expressions equivalent to: (x == 10) or (x > 10)? Expression equivalent to x [0, 10]? If I have two ints, a, b, how do I test whether a is divisible by b? Test whether int x is odd?
58 5.2 Logical Operators 5 CONDITIONALS AND RECURSION >>> print about positivity(5) It is True that 5 is positive. >>> print about positivity(-22.3) It is False that is positive. >>> print about positivity(0) It is False that 0 is positive. >>> print all about sign(42) It is True that 42 is positive. It is False that 42 is negative. It is False that 42 is zero. >>> Write print about positivity(number)! Bonus challenge: print all about sign >>> print whether in closed interval(5, 3, 1200) It is True that 5 is in the interval [3, 1200]. >>> print whether in closed interval(-5, -3, 1200) It is False that -5 is in the interval [-3, 1200]. >>> min(10, 100) 10 >>> print whether in closed interval(23, 30, 4) It is True that 23 is in the interval [4, 30]. >>>
59 5.3 Conditional Execution 5 CONDITIONALS AND RECURSION Get print whether in closed interval to work as in the first two examples. Header: print whether in closed interval(x, low, high). Bonus challenge: get it to work for the harder case, where the lower interval boundary might be last. 5.3 Conditional Execution Often, we want to execute a block of code based on the value of a boolean expression. For example, might want to print out whether the value in a variable is positive. (On board) if x > 0: print( x is positive. ) This is known as a Conditional! Let s break it down! Break down: keyword space {}}{{}}{ condition colon {}}{{}}{} if {{ x > 0 : } header body {}}{}{{} x is positive indent Notice: another colon. This means we have a compound statement! Def: Compound Statement A compound statement is a statement that contains a header and a body consisting of other substatements. There must be at least one statement inside the body of a compound statement!
60 5.3 Conditional Execution 5 CONDITIONALS AND RECURSION As an example, let s modify draw polygon by adding a conditional (and a docstring and comments). (On board) def draw polygon(turtle, num sides, side): Specified turtle draws a regular polygon with num sides sides, each of length side. if (num sides) > 1: #draw the polygon! for i in range(num sides): fd(turtle, side) rt(turtle, 360.0/num sides) if (num sides) <= 1: #print a message about not doing it Will this run? What if we don t know what we want to write yet? pass is a line of code that does nothing.
61 5.4 Alternative Execution 5 CONDITIONALS AND RECURSION >>> world = TurtleWorld() >>> raphael = Turtle() >>> draw polygon(raphael, 5, 50) >>> rt(raphael) >>> pu(raphael) >>> fd(raphael, 100) >>> pd(raphael) >>> draw polystar(raphael, 7, 50) >>> pu(raphael) >>> fd(raphael, 100) >>> pd(raphael) >>> draw polystar(raphael, 8, 50) >>> >>> better print whether in closed interval(5, 0, 10) Yes, it is! >>> x = 13 >>> better print whether in closed interval(x, -3, 3) No, it isn t! >>> better print whether in closed interval(10, 0, 10) Yes, it is! Implement it! Header: def better print whether in closed interval(number, lower, upper) Challenge: print out better message. Example: Yes, 5 is between 0 and 10! 5.4 Alternative Execution We are often doing one thing or something else. Trick: use else.
62 5.5 Nested Conditionals 5 CONDITIONALS AND RECURSION (On Board) if x > 0: print( x is positive. ) else: print( x is either negative or zero. ) Replace our implementation of better print whether in closed interval so that it uses else. >>> better print whether in closed interval(6, 10, 0) Yes, it is! >>> print whether monkey("sneasel") sneasel isn t a monkey! >>> print whether monkey("monkey") monkey! >>> Change yours so the same things happens! Also, code up print whether monkey 5.5 Nested Conditionals (order swapped with Chained Conditionals) We can nest conditionals! (On Board) if x > 0: print( x is positive. ) else: if x < 0: print( x is negative. ) else: print( x is zero )
63 5.6 Chained Conditionals 5 CONDITIONALS AND RECURSION Does the following code work? (On Board) if x > 0: print( x is positive. ) if x < 0: print( x is negative. ) else: print( x is zero. ) Why not? 5.6 Chained Conditionals Alternatively, we can use elif. Called a chained conditional. (On Board) if x > 0: print( x is positive. ) elif x < 0: print( x is negative. ) else: print( x is zero. ) There can be an unlimited number of elifs in one conditional!
64 5.6 Chained Conditionals 5 CONDITIONALS AND RECURSION (On Board) if x > 0: print( x is positive. ) elif x < 0: print( x is negative. ) elif x == 0: print( x is zero. ) else: print( x must not be a number! ) What happens if I start with an elif instead of an if? >>> print about sign(13) 13 is positive. >>> print about sign(-2210) is negative. >>> print about sign(5-5) 0 is zero. >>>
65 5.7 Recursion 5 CONDITIONALS AND RECURSION Write print about sign(number)! You may use either nested or chained conditionals! TODO: need a bonus question 5.7 Recursion We have functions call other functions. themselves! Whoa!!!!! We can also have functions call (On Board) def countdown(n): if n <= 0: print( Blastoff! ) else: print(n) countdown(n-1) What s going to happen when I make this function call: countdown(3)?
66 5.8 Recursive Stack Diagrams 5 CONDITIONALS AND RECURSION >>> countdown(3) Blastoff! 5.8 Recursive Stack Diagrams A stack diagram will help figure out what happened! Draw out the stack diagram for this! Def: Recursion Recursion is the process of a function calling itself. I could write this differently (On Board) def countdown alternative(n): if n <= 0: print( Blastoff! ) return print(n) countdown alternative(n-1) >>> countdown alternative(3) Blastoff! What does return do?
67 5.9 Infinite Recursion 5 CONDITIONALS AND RECURSION 5.9 Infinite Recursion (On Board) def keep going(): print( Let s keep going! ) keep going() What happens when I call keep going()? Why? Def: Infinite Recursion Infinite Recursion is a sequence of recursive calls that will never terminate. What if we swap the two lines in the body of keep going? >>> keep going backwards() You can press Ctrl + C to stop execution. Demonstrate! Break down parts of countdown: def countdown(n): if n <= 0: print( Blastoff! ) } base case
68 5.9 Infinite Recursion 5 CONDITIONALS AND RECURSION else: print(n) countdown(n-1) recursive case When you are writing recursive functions, make sure you have both base and recursive cases! Recursive Function Writing Plan: (with countdown as the example) 1. Write the condition for the base case. (n <= 0) 2. Write the body of the base case (print( Blastoff! )). 3. Write the recursive call. 4. Leap of Faith: What should that recursive call do? Assume it does that! 5 Source: 5
69 5.9 Infinite Recursion 5 CONDITIONALS AND RECURSION 5. Little bit of work: Write the code that uses that recursive call to solve the problem. What is the leap of faith for countdown? In countdown, what was the little bit of work that is done? Consider countdown(3). What will the recursive call look like (with the value instead of the actual argument expression)? What part of the output is handled by the recursive call?
70 5.9 Infinite Recursion 5 CONDITIONALS AND RECURSION So what is the little bit of work that is done in countdown(3) s recursive case? The Cat in the Hat Comes Back! (Go slow, only takes minutes.) The recursive case is often tricky! Two parts: Do a small amount of the work. Make the recursive call. Always write the base case first. Then, if you get stuck on the recursive case, consider the case where the recursive call will call the base case. (For example, countdown(1). Then think about what the little bit of work will be that your recursive case will do and put the two parts together. Often, this will get you close to writing your recursive case. Example: I m going to give the count for just this number, then trust that the recursive call will count down the rest. >>> final countdown(5) Blastoff! >>> final countdown(20) Blastoff!
71 5.10 Keyboard Input 5 CONDITIONALS AND RECURSION How could we implement final countdown? It only counts down the last ten numbers Keyboard Input input() gets input while the program is running! It is a fruitful function! >>> word = input() Monkieeeez! >>> print(word) Monkieeeez! You can add text and ask a question! >>> name = input("what is your name?") What is your name?kyle Burke >>> greet(name) Hi, Kyle Burke! What s the problem here? One solution: add more spaces. >>> name = input("what is your name? ") What is your name? Kyle Burke >>> greet(name) Hi, Kyle Burke! Another solution: add a line break!
72 5.10 Keyboard Input 5 CONDITIONALS AND RECURSION >>> name = input("what is your name?\n") What is your name? Kyle Burke >>> greet(name) Hi, Kyle Burke! Let s add input to the body of a function! >>> greet prompt() Whom would you like to greet? Steve Hi, Steve! Implement it! Header: def greet prompt(): >>> is between prompt(0, 10) Which number would you like to test? 0 Yes, it is! >>> is between prompt(0, 10) Which number would you like to test? 16 No, it isn t!
73 5.10 Keyboard Input 5 CONDITIONALS AND RECURSION Implement it! Header: def is between prompt(lower, upper): Hint: input always returns a string! >>> is between maybe keep asking(-6, 3) Which number would you like to test? 0 Yes, it is! Would you like to test another number? yes Which number would you like to test? 24 No, it isn t! Would you like to test another number? no >>> is between keep asking(-1, 5) Which number would you like to test? 0 Yes, it is! Which number would you like to test? 24 No, it isn t!...
74 6 FRUITFUL FUNCTIONS Implement it! Header: def is between keep asking(lower, upper): Challenge: is between maybe keep asking(lower, upper) 6 Fruitful Functions 6.1 Return Values Alright, it s time to write fruitful functions! Now we will write functions that return a value! We ve already seen: >>> import math >>> x = math.sin(0) >>> print(x) 0.0 >>> x = greet( Kyle ) Hi, Kyle! >>> print(x) None What if we want a function like math.sin that returns a value when called? We will use the keyword return.
75 6.2 Incremental Development 6 FRUITFUL FUNCTIONS def area of circle(radius): Returns the area of a circle with the specified radius. area = math.pi * (radius ** 2) return area >>> area = area of circle(3) >>> print(area) >>> print(area of circle(5)) What does the return area line do? What do you think return alone does? 6.2 Incremental Development 6.3 Composition I could use this to calculate the volume of a cylinder with radius 10 and height 7! Draw a picture of cylinder and describe formula for the volume. >>> circle area = area of circle(10) >>> volume = circle area * 7 >>> print(volume)
76 6.3 Composition 6 FRUITFUL FUNCTIONS Notice: keyword return, followed by a value. How might we write the body of area of circle in one line? >>> area = area of triangle(base = 4, height = 5) >>> print(area) 10.0 >>> trapezoid area = area of trapezoid(top = 4, base = 6, height = 3) >>> print(trapezoid area) 15.0 Implement it! Header: area of triangle(base, height): Challenge: area of trapezoid(top, base, height)
77 6.3 Composition 6 FRUITFUL FUNCTIONS >>> volume = volume of cylinder(radius = 5, height = 7) >>> print(volume) >>> cone volume = volume of cone(base radius = 7, height = 18) >>> print(cone volume) 42.0 Draw a picture! Implement it! Header: def volume of cylinder(radius, height): Hint: use area of circle Challenge: volume of cone >>> number = absolute value(4) >>> number 4 >>> weight = absolute value(-27) >>> print weight 27
78 6.4 Boolean Functions 6 FRUITFUL FUNCTIONS Write this! (There is a function that does it for you in the math package; I want you to try writing it on your own!) def absolute value(number): Challenge: after you get it to work, do in one line? You have to be careful! Mine doesn t work for zero! >>> print absolute value(0) None 6.4 Boolean Functions Can write Boolean Fruitful functions as well! >>> parity = is even(3) >>> print(parity) False >>> is even(222) True >>> is square(4) True >>> is square(5) False >>>
79 6.4 Boolean Functions 6 FRUITFUL FUNCTIONS Implement it! Header: def is even(number): Hint: use modulus operator! Challenge: write in one line. Bigger Challenge: write is square(number) >>> parity = is odd(3) >>> print(parity) True >>> is odd(222) False TODO: needs a bonus challenge! Implement def is odd(number): Bonus challenge: composition call is even!
80 6.4 Boolean Functions 6 FRUITFUL FUNCTIONS >>> between = is between(5, 10) Which number would you like to test? 8 >>> print(between) True >>> test value = is between(5, 10) Which number would you like to test? 265 >>> if test value: print("that s crazy!") else: print("that s what I expected.")... That s what I expected >>> is between(10, 5) Which number would you like to test? 7 True >>> Implement it! Header: def is between(lower, upper): Bonus Challenge: get it to work so that the first doesn t have to be the lower bound.
Python for Informatics
Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.
More informationAlgorithms and Programming I. Lecture#12 Spring 2015
Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationHow To Think Like A Computer Scientist, chapter 3; chapter 6, sections
6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How
More informationHello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications
Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this
More informationVariables, expressions and statements
Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the
More informationDownloaded from Chapter 2. Functions
Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationDM536 Introduction to Programming. Peter Schneider-Kamp.
DM536 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! DEFINING FUNCTIONS 2 Function Definitions functions are defined using the following grammar
More informationAl al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department
Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department 0901212 Python Programming 1 st Semester 2014/2015 Course Catalog This course introduces
More informationConditionals and Recursion. Python Part 4
Conditionals and Recursion Python Part 4 Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print (remainder) 1 Boolean expressions An expression that
More informationCourse Outline - COMP150. Lectures and Labs
Course Outline - COMP150 Lectures and Labs 1 The way of the program 1.1 The Python programming language 1.2 What is a program? 1.3 What is debugging? 1.4 Experimental debugging 1.5 Formal and natural languages
More informationGetting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners
Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008
More informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationPython for Non-programmers
Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013
More informationCMSC 201 Fall 2016 Lab 09 Advanced Debugging
CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working
More informationIntroduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15
1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details
More informationEXPRESSIONS, STATEMENTS, AND FUNCTIONS 1
EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 COMPUTER SCIENCE 61A June 24, 2014 0.1 Warmup What Would Python Do? >>> x = 6 >>> def square(x):... return x * x >>> square(x) >>> max(pow(2, 3), square(-5)) -
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationProgramming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.
Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers
More informationPRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops
PRG PROGRAMMING ESSENTIALS 1 Lecture 2 Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical
More informationCSC326 Python Imperative Core (Lec 2)
i CSC326 Python Imperative Core (Lec ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 Invoking Python 1 3 Value, Type, Variable 1 4 Keywords 2 5 Statement 2 6 Expression
More informationIteration. # a and b are now equal # a and b are no longer equal Multiple assignment
Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop
More informationFunctions and Decomposition
Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the
More informationPython The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT
Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationCS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007
CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted
More informationDEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A
DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.
More informationAt full speed with Python
At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise
More informationThe compiler is spewing error messages.
Appendix B Debugging There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly. Compile-time errors are
More informationPREPARING FOR PRELIM 1
PREPARING FOR PRELIM 1 CS 1110: FALL 2012 This handout explains what you have to know for the first prelim. There will be a review session with detailed examples to help you study. To prepare for the prelim,
More informationControl Structures 1 / 17
Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops
More information[CHAPTER] 1 INTRODUCTION 1
FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2
More informationHow to Think Like a Computer Scientist: Learning with Python 3»
How to Think Like a Computer Scientist: Learning with Python 3» previous next index 1. The way of the program The goal of this book is to teach you to think like a computer scientist. This way of thinking
More informationFundamentals of Programming (Python) Getting Started with Programming
Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More informationThere are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)
I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications
More informationDM502 Programming A. Peter Schneider-Kamp.
DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! TURTLE WORLD & INTERFACE DESIGN 2 Turtle World available from http://imada.sdu.dk/~petersk/dm502/lit/swampy-2.0.zip
More informationGetting Started with Python
Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More informationDecisions, Decisions. Testing, testing C H A P T E R 7
C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little
More informationage = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s
Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences
More informationText Input and Conditionals
Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS VARIABLES, EXPRESSIONS AND STATEMENTS João Correia Lopes INESC TEC, FEUP 27 September 2018 FPRO/MIEIC/2018-19 27/09/2018 1 / 21 INTRODUCTION GOALS By the end of this class, the
More informationFunctions. Python Part 3
Functions Python Part 3 1 Function Calls Function A named sequence of statements that performs a computation Name Sequence of statements call function by name >>> type(32) Function name type
More informationCS1 Lecture 3 Jan. 22, 2018
CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow
More informationCMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you
More informationCSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch
CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed
More information06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python
CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison
More informationFunctions and Recursion
Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2
More informationENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python
ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python ENGG1811 UNSW, CRICOS Provider No: 00098G W4 Computers have changed engineering http://www.noendexport.com/en/contents/48/410.html
More informationCS1 Lecture 5 Jan. 25, 2019
CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line
More informationPROBLEM SOLVING 11. July 24, 2012
PROBLEM SOLVING 11 COMPUTER SCIENCE 61A July 24, 2012 Today s section will be a kind of Meta-Section, we are going to walk through some medium to hard-ish problems in Scheme, and we will discuss some methods
More informationPython for Analytics. Python Fundamentals RSI Chapters 1 and 2
Python for Analytics Python Fundamentals RSI Chapters 1 and 2 Learning Objectives Theory: You should be able to explain... General programming terms like source code, interpreter, compiler, object code,
More informationIntroduction to: Computers & Programming: Review prior to 1 st Midterm
Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in
More informationCS 1301 Exam 1 Answers Fall 2009
Page 1/6 CS 1301 Fall 2009 Exam 1 Your Name: I commit to uphold the ideals of honor and integrity by refusing to betray the trust bestowed upon me as a member of the Georgia Tech community. CS 1301 Exam
More informationSAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik
SAMS Programming A/B Lecture #1 Introductions July 3, 2017 Mark Stehlik Outline for Today Overview of Course A Python intro to be continued in lab on Wednesday (group A) and Thursday (group B) 7/3/2017
More informationWELCOME! (download slides and.py files and follow along!) LECTURE 1
WELCOME! (download slides and.py files and follow along!) 6.0001 LECTURE 1 6.0001 LECTURE 1 1 TODAY course info what is computation python basics mathematical operations python variables and types NOTE:
More informationExpressions and Variables
Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,
More informationMobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02
Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.
More informationAbout the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix
CS 21 Final Review About the Final Saturday, 7-10pm in Science Center 101 Closed book, closed notes Not on the final: graphics, file I/O, vim, unix Expect Questions That Ask You To: Evaluate Python expressions
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationAnimations involving numbers
136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive
More informationLOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
More informationLecture 4. Defining Functions
Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in
More informationCSCE 110 Programming I
CSCE 110 Programming I Basics of Python (Part 1): Variables, Expressions, and Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2013 Tiffani
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationCS1 Lecture 3 Jan. 18, 2019
CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due
More informationCMSC 201 Computer Science I for Majors
CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset
More informationCSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output
CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed
More informationChapter 7. Iteration. 7.1 Multiple assignment
Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);
More informationAct like a code monkey Coding Basics
Act like a code monkey Coding Basics Announcement Homework 1 grade is posted If you believe there is an error in grading (assignments or quizzes), you may request a regrading within one week of receiving
More informationCS1 Lecture 5 Jan. 26, 2018
CS1 Lecture 5 Jan. 26, 2018 HW1 due Monday, 9:00am. Notes: Do not write all the code at once (for Q1 and 2) before starting to test. Take tiny steps. Write a few lines test... add a line or two test...
More informationChapter 4: Conditionals and Recursion
Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative
More informationBeyond Blocks: Python Session #1
Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike
More informationLecture 4 CSE July 1992
Lecture 4 CSE 110 6 July 1992 1 More Operators C has many operators. Some of them, like +, are binary, which means that they require two operands, as in 4 + 5. Others are unary, which means they require
More informationCopied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017
Hw 1, Part 2 (Lab): Functioning smoothly! Using built-in functions Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017 First, try out some of Python's many built-in functions. These
More informationProgramming with Python
Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2
More informationroboturtle Documentation
roboturtle Documentation Release 0.1 Nicholas A. Del Grosso November 28, 2016 Contents 1 Micro-Workshop 1: Introduction to Python with Turtle Graphics 3 1.1 Workshop Description..........................................
More informationIntroduction to Python (All the Basic Stuff)
Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions
More information61A Lecture 2. Friday, August 28, 2015
61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max
More informationDM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.
DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! RECURSION 2 Recursion a function can call other functions a function can
More informationCS1 Lecture 4 Jan. 23, 2019
CS1 Lecture 4 Jan. 23, 2019 First graded discussion sections this week yesterday/today 10 DS assignments worth 2 points each everyone gets one free 2-pointer. I.e. your lowest DS grade will be replaced
More informationnostarch.com/pfk For bulk orders, please contact us at
nostarch.com/pfk For bulk orders, please contact us at sales@nostarch.com. Teacher: Date/Period: Subject: Python Programming Class: Topic: #1 - Getting Started Duration: Up to 50 min. Objectives: Install
More informationPython 1: Intro! Max Dougherty Andrew Schmitt
Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and
More information: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics
Assignment 1: Turtle Graphics Page 1 600.112: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics Peter H. Fröhlich phf@cs.jhu.edu Joanne Selinski joanne@cs.jhu.edu Due Date: Wednesdays
More informationLecture 3. Input, Output and Data Types
Lecture 3 Input, Output and Data Types Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and
More informationPart II Composition of Functions
Part II Composition of Functions The big idea in this part of the book is deceptively simple. It s that we can take the value returned by one function and use it as an argument to another function. By
More informationBuilding a snowman with Racket
Building a snowman with Racket Christopher Lemmer Webber March 16, 2018 This tutorial introduces some basics of programming in Racket and then guides the user through making a snowman. It assumes no previous
More informationCS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore
CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationIf Statements, For Loops, Functions
Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements
More informationCHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS
CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations
More informationProblem Solving for Intro to Computer Science
Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More information4. Java Project Design, Input Methods
4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java
More information4. Modules and Functions
4. Modules and Functions The Usual Idea of a Function Topics Modules Using import Using functions from math A first look at defining functions sqrt 9 3 A factory that has inputs and builds outputs. Why
More informationPython I. Some material adapted from Upenn cmpe391 slides and other sources
Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationCOMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods
COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,
More informationThe Dynamic Typing Interlude
CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,
More information