Beyond programming. CS 199 Computer Science for Beginners Spring 2009 Lois Delcambre Week 5/12/2009 1

Similar documents
Lecture. Simulation && Design. Richard E Sarkis CSC 161: The Art of Programming

Python Programming: An Introduction to Computer Science

Lecture 19. Topics: Chapter 9. Simulation and Design Moving to graphics library Unit Testing 9.5 Other Design Techniques

Lecture Object-Oriented Design. Richard E Sarkis CSC 161: The Art of Programming

Beyond Blocks: Python Session #1

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Chapter 2 Writing Simple Programs

Introduction to Computer Programming for Non-Majors

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Loop structures and booleans

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python

Programming with Python

About Variables in Python F E B 1 1 T H

Introduction to Computer Programming for Non-Majors

Fundamentals of Programming (Python) Getting Started with Programming

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

CS 1110, LAB 1: PYTHON EXPRESSIONS.

(Python) Chapter 3: Repetition

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Intro. Scheme Basics. scm> 5 5. scm>

Introduction to Domain Testing

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Getting Started with Python

Jython. secondary. memory

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python Programming: An Introduction To Computer Science

CMSC 201 Computer Science I for Majors

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CSCE 110 Programming I

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

The float type and more on variables FEB 6 TH 2012

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

CS 112: Intro to Comp Prog

Decisions, Decisions. Testing, testing C H A P T E R 7

More Lambda Calculus and Intro to Type Systems

CS 115 Lecture 4. More Python; testing software. Neil Moore

Object-oriented design

CSE 120. Computer Science Principles

Introduction to Problem Solving and Programming in Python.

CS1 Lecture 13 Feb. 13, 2019

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Variables, expressions and statements

CS1 Lecture 3 Jan. 22, 2018

Introduction to Computer Programming for Non-Majors

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

These are notes for the third lecture; if statements and loops.

CSCI 270: Introduction to Algorithms and Theory of Computing Fall 2017 Prof: Leonard Adleman Scribe: Joseph Bebel

Python Programming: An Introduction To Computer Science

More Lambda Calculus and Intro to Type Systems

Repetition Structures

Controls Structure for Repetition

T H E I N T E R A C T I V E S H E L L

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Here is a sample IDLE window illustrating the use of these two functions:

Impossible Programs. Tom Stuart

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

If Statements, For Loops, Functions

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

cs1114 REVIEW of details test closed laptop period

Lecture Transcript While and Do While Statements in C++

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

ENGR 101 Engineering Design Workshop

CS 374 Fall 2014 Homework 5 Due Tuesday, October 14, 2014 at noon

Chapter01.fm Page 1 Monday, August 23, :52 PM. Part I of Change. The Mechanics. of Change

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

STUDENT LESSON A14 Boolean Algebra and Loop Boundaries

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Getting started 7. Saving data 23

Static Methods. Why use methods?

Invent Your Own Computer Games with Python

Introduction to Programming

Introduction to Programming

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

More Lambda Calculus and Intro to Type Systems

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Reliable programming

CS1 Lecture 5 Jan. 25, 2019

(Refer Slide Time: 01.26)

nostarch.com/pfk For bulk orders, please contact us at

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

mith College Computer Science Week 12 CSC111 Spring 2018 Dominique Thiébaut

CS 5 Nightly Wrapup College Canceled

1 Lecture 5: Advanced Data Structures

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

CS1 Lecture 3 Jan. 18, 2019

Test #2 October 8, 2015

Chapter 2. The Algorithmic Foundations of. Computer Science INVITATION TO. Computer Science. Tuesday, September 10, 13

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Transcription:

Beyond programming CS 199 Computer Science for Beginners Spring 2009 Lois Delcambre Week 5/12/2009 1

Introduction We ve covered: Python data types Python expressions Python statements We ve written approximately 30 programs that allow students to practice the various data types, expressions, and statements It s time to step back; talk about this 5/12/2009 2

You ve learned a lot of Python Look at the reserved word list (p. 30) How many of these have you learned? and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print if, elif, else for control structures 5/12/2009 3

You ve learned a lot of Python and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print def, return, import, from used when you define functions and import functions in modules 5/12/2009 4

You ve learned a lot of Python and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print Logical expressions that evaluate to true or false 5/12/2009 5

You ve learned a lot of Python and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print For loop and while loop: break jump out, past the loop continue jump to the bottom of this loop and keep going pass do nothing - a placeholder 5/12/2009 6

You ve learned a lot of Python and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print print statement del and in used with iterables (list, set, tuple) 5/12/2009 7

Python statements (documentation) 6. Simple statements 6.1. Expression statements 6.2. Assignment statements 6.3. The assert statement 6.4. The pass statement 6.5. The del statement 6.6. The print statement 6.7. The return statement 6.8. The yield statement 6.9. The raise statement 6.10. The break statement 6.11. The continue statement 6.12. The import statement 6.13. The global statement 6.14. The exec statement 7. Compound statements 7.1. The if statement 7.2. The while statement 7.3. The for statement 7.4. The try statement 7.5. The with statement 7.6. Function definitions 7.7. Class definitions 8. Top-level components 8.1. Complete Python programs 8.2. File input 8.3. Interactive input 8.4. Expression input 5/12/2009 8

You ve used modules A module is a file: with your program in it with a function definition in it with a set of (often related) functions in it You can: run a module (using Run in IDLE) import a module You ve seen: The string and math modules There are dozens (hundreds?) of others 5/12/2009 9

Many programming languages have the statements that you ve learned Java has: assignment statements for loops while loops do/while loops break if, else print return 5/12/2009 10

We haven t talked about classes and objects (object-oriented programming or oop) Object-oriented programming is one paradigm for programming Procedural programming is another paradigm for programming (we have been using Python in a procedural way; we write one Python statement after another) Functional programming is another paradigm where everything is a function (no loop; no assignment statements) 5/12/2009 11

How is a program used? It might be run for a long time unchanged. Have you heard about the Y2K problem? It might be part of something larger that evolves over time. It might be used by others, exactly as it is written if you put it in a module. It might be used and modified by others, e.g., in an open source setting. 5/12/2009 12

Therefore we need it to be: It might be run for a long time unchanged. Have you heard about the Y2K problem? Correct for all inputs It might be part of something larger that evolves over time. Testable(again & again) It might be used by others, exactly as it is written if you put it in a module. Readable & Understandable It might be used and modified by others, e.g., in an open source setting. Readable & Understandable 5/12/2009 13

How do we know a program is correct for all inputs? In general, we can t Alan Turing proved in 1936 that it is not possible to write a program that can take as input: a program and an input and decide whether or not the program will finish or will run forever. This is called the halting problem. Thus, we say it is undecidable 5/12/2009 14

Halting problem (cont.) So don t expect to generate a bunch of code and then expect some automatic procedure to figure out whether it s correct. (A general purpose automatic procedure can t even figure out whether or not a program will finish or not.) Shortest lie in computer science: it works. 5/12/2009 15

What about testing? Very important. You should be systematic in your testing. Figure out your boundary conditions the smallest/largest input that your program should work for. Then test: The smallest input A range of typical/normal inputs; variations The largest input An input smaller than the smallest An input larger than the largest 5/12/2009 16

Testing (cont.) Testing can never completely identify all the defects within software. Som software is released for use before it is bug-free (in many cases). Some software is life-critical so proper testing is really important. [Note that for some programs it is possible to prove, mathematically, that they meet their specification.] 5/12/2009 17

So how should we develop software? How do we begin? It is generally a bad idea to write one big program (i.e., one big function called main()) that does everything. Why? Given what we know so far in Python, how can we decompose a program into smaller pieces (where each piece could be written AND tested) separately? That is, what language feature should we use? 5/12/2009 18

So how should we develop software? How do we begin? It is generally a bad idea to write one big program that does everything. Why? People don t want to read long programs Longer programs are (usually) more complex because some variables may be used in more than one place; thus some parts of the program may depend on others. Given what we know so far in Python, what language feature should we use? Functions! Each function can be written and tested. It doesn t see variables except those that are input and those that it returns. 5/12/2009 19

So, how do we decide which functions to write? Top-down design Break the big program into a series of small ones. (Assume, for the moment, that you or someone else will be able to write the functions that you need.) 5/12/2009 20

Example of top-down design Over years of playing racquetball, Denny has noticed a strange quirk in the game. He often competes with players who are just a little bit better than he is. In the process, he always seems to lose the vast majority of matches. Susie suggests that they can write a computer program to figure out if it s just the nature of the game (or not). 5/12/2009 21

Racquetball To start the game, one of the players puts the ball into play by serving. The players then alternate hitting the ball to keep it in play in a rally. The rally ends when one of the players fails to hit a legal shot. The player who misses the shot loses the rally. If the server wins the rally, the server earns one point. Players can only score points during their service. If the server does NOT win the rally then NO point is awarded and service passes to the other player. The first player to reach 15 points wins the game, in the amateur version of scoring. Book uses this. 5/12/2009 22

Specification of a Racquetball Simulation Program Input The program first prompts for and gets the service probabilities of the two players (called Player A and Player B ). Then the program prompts for and gets the number of games to be simulated. Output The program will provide a series of initial prompts such as the following: What is the prob. player A wins a serve? What is the prob. player B wins a serve? How many games to simulate? The program will print out a nicely formatted report showing the number of games simulated and the number of wins and winning percentage for each player. Here is an example: Games Simulated: 500 Wins for A: 268 (53.6%) Wins for B: 232 (46.4%) Notes: All inputs are assumed to be legal numeric values, no error or validity checking is required. In each simulated game, player A serves first. 5/12/2009 23

How do we figure out who wins/loses a serve? We know the probability that player A wins his/her serve. We know the probability that player B wins his/her serve. We need to flip a coin. We need to use a random number generator. (Also called a pseudo random number generator.) It returns a value between 0 and 1. 5/12/2009 24

Python has a random module randrange(start, stop, step) returns an integer in the requested range random() returns a floating point number between 0 and 1 >>> import random as r >>> r.random() 0.40664291180330725 >>> r.random() 0.73249446651324879 5/12/2009 25

To determine whether player A wins the rally, when they serve: if <player wins serve>: score = score + 1 This can be coded in Python like this: if random() < prob for player A: score = score + 1 5/12/2009 26

Top-down design: get started Print an Introduction Get the inputs: proba, probb, n Simulate n games of racquetball using proba and probb Print a report on the wins for playera and playerb def main(): printinstructions() def printintro(): print "This program simulates a game of racquetball between two" print proba, players called probb, "A" and n "B". = The getinputs() abilities of each player is print "indicated by a probability (a number between 0 and 1) that" print "the player wins the point when serving. Player A always" print "has the first serve." winsa, winsb = simngames(n, proba, probb) printsummary(winsa, winsb) 5/12/2009 27

Notice, at this point, You may not know how to write each of these functions. Imagine that you will You are choosing the inputs and outputs for each function. This is a very important step! You are defining the interface for the function. (Also, called the signature.) You can write the functions: def printsummary(a, b): pass 5/12/2009 28

Structure chart for what we have so far At this point, you might code the functions that you understand or (instead) focus on the ones you DON T know how to write. You can continue doing top-down design. Which ones do you know how to write? 5/12/2009 29

Now, consider each function We know how to write printintro. Here s one way: def printintro(): print "This program simulates a game of racquetball between two" print players called "A" and "B". The abilities of each player is print "indicated by a probability (a number between 0 and 1) that" print "the player wins the point when serving. Player A always" print "has the first serve." 5/12/2009 30

What about getinputs()? We know how to write this as well: def getinputs(): # RETURNS the three simulation parameters proba, probb and n a = input("what is the prob. player A wins a serve? ") b = input("what is the prob. player B wins a serve? ") n = input("how many games to simulate? ") return a, b, n 5/12/2009 31

What about simngames (This is the hard one; what shall we do?) Here s some pseudocode: Initialize winsa and winsb to 0 loop n times simulate a game if playera wins Add one to winsa else Add one to winsb 5/12/2009 32

Code for simngames def simngames(n, proba, probb): # Simulates n games and returns winsa and winsb winsa = 0 winsb = 0 for iin range(n): scorea, scoreb = simonegame(proba, probb) We did it again; we invented/imagined a function called simonegame (it needs to know the probability that player A wins his/her serve and the probability that player B wins his/her serve). 5/12/2009 33

Accumulate wins, based on simonegame def simngames(n, proba, probb): winsa = winsb = 0 for iin range(n): scorea, scoreb = simonegame(proba, probb) if scorea > scoreb: winsa = winsa + 1 else: winsb = winsb + 1 return winsa, winsb 5/12/2009 34

Updated Structure Diagram 5/12/2009 35

Continue top-down design How do we write simonegame? Pseudocode: Initialize scores to 0 Set serving to "A" Loop while game is not over: Simulate one serve of whichever player is serving update the status of the game Return scores 5/12/2009 36

Getting started simonegame def simonegame(proba, probb): scorea = 0 scoreb = 0 serving = "A" while <condition>: What is the condition? We need to keep this function running until the game is over. We can invent a function for that: 5/12/2009 37

gameover returns a Boolean def simonegame(proba, probb): scorea = 0 scoreb = 0 serving = "A" while not gameover(scorea, scoreb): 5/12/2009 38

New structure chart 5/12/2009 39

Complete simonegame 5/12/2009 40

Another function: gameover Pseudocode Python code We also need to write the function printsummary; but that s easy. See pages 280-282 for the complete program, in your book. 5/12/2009 41

Analysis and Design Some jobs require that you ONLY do design. Some jobs require that you ONLY gather requirements (analysis). Some jobs require that you ONLY test software. Some jobs require that you do all of these. (Not everyone writes code all day long.) 5/12/2009 42