CS1 Lecture 5 Jan. 26, 2018

Similar documents
CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 4 Jan. 24, 2018

CS1 Lecture 4 Jan. 23, 2019

CS1 Lecture 13 Feb. 13, 2019

CS1 Lecture 3 Jan. 22, 2018

Introduction to Python (All the Basic Stuff)

CS1 Lecture 11 Feb. 9, 2018

Problem Solving for Intro to Computer Science

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 22 Mar. 6, 2019

Conditionals & Control Flow

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

CS1 Lecture 2 Jan. 16, 2019

CS1 Lecture 15 Feb. 19, 2018

Text Input and Conditionals

CS1 Lecture 9 Feb. 5, 2018

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Beyond Blocks: Python Session #1

Intro. Speed V Growth

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Conditional Expressions and Decision Statements

CS1102: Macros and Recursion

(Refer Slide Time: 01.26)

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Induction and Semantics in Dafny

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

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

Lecture Transcript While and Do While Statements in C++

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Lecture 3: Recursion; Structural Induction

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

CS1 Lecture 15 Feb. 18, 2019

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

CS1 Lecture 12 Feb. 11, 2019

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts

PREPARING FOR PRELIM 1

Lecture Notes, CSE 232, Fall 2014 Semester

COMP-520 GoLite Tutorial

Lecture 2: SML Basics

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

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

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

CS1210 Lecture 28 Mar. 27, 2019

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

More Lambda Calculus and Intro to Type Systems

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CS1 Lecture 22 Mar. 8, HW5 available due this Friday, 5pm

Introduction to Denotational Semantics. Brutus Is An Honorable Man. Class Likes/Dislikes Survey. Dueling Semantics

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Repetition Through Recursion

Chapter 1 Getting Started

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Lecture 8. Conditionals & Control Flow

TUPLES AND RECURSIVE LISTS 5

(I m not printing out these notes! Take your own.)

Python Boot Camp. Day 3

Semantic Analysis. Lecture 9. February 7, 2018

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

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

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

ENCM 369 Winter 2017 Lab 3 for the Week of January 30

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Comp 151. Control structures.

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree:

Control Structures in Java if-else and switch

Homework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3

6.001 Notes: Section 15.1

LOOPS. Repetition using the while statement

Conditionals & Loops /

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Lecture 3. Input, Output and Data Types

The compiler is spewing error messages.

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

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Typing Control. Chapter Conditionals

Here redirection. Case statement. Advanced Unix Tools Lecture 6 CS214 Spring 2004 Friday March 5, 2004

Functions and Decomposition

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CS1 Lecture 27 Mar. 26, 2018

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CMSC201 Computer Science I for Majors

Reviewing all Topics this term

CSE 341 : Programming Languages Midterm, Spring 2015

ENGR 102 Engineering Lab I - Computation

Operational Semantics. One-Slide Summary. Lecture Outline

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Lab 6: P.S. it s a stack Due 11:59 pm Monday, Mar 31, 2008

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Project 4 Due 11:59:59pm Thu, May 10, 2012

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Transcription:

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... add another line test...!! Q2, choosevehiclefortrip( ), should not compute values that tripcost computes. It should 1) covert units, 2) call tripcost twice, 3) print results the math.ceil function can be helpful calculating the number of hotel nights. (See slide later in this lecture) floor division (//) and modulus (%) can also be useful in HW1 calculations. (See slide later in this lecture) HW2 available Monday First survey (ICON) due 5pm today.

Last time Much of chapter 3 Function calls Math functions (math module) Function composition Defining functions <- super important! Flow of execution Parameters and arguments

side note: be careful with floats! >>> v1 = 2 ** 64 >>> v2 = 2.0 ** 64 >>> v1 == v2 True >>> (v1-1) == (v2-1) False >>> (2.0 **64) == (2.0**64) + 1 True >>> (2.0**53) + 1 + 1 == (2.0**53) + 2 False Those might seem esoteric but consider: >>> (2.2 * 3) == 6.6? False Floating point representations are often not exact. It probably won t be an issue in this class, but keep in mind for the future. Be careful when comparing floating point numbers for equality with each other or with 0.0! Instead of x == 0.0 use comparisons like x <= abs(epsilon) for some suitably small value epsilon

Today Ch 3: The rest Variables and parameters are local Stack diagrams Fruitful functions - incl return vs. print Why Functions? Skip to first part of Ch 5: Conditionals Floor division and modulus (useful for HW1) Logical/Boolean expressions Conditional execution if/elif/else

Ch 3: Variables and parameters are local A function s parameters are local variables. That is, they exist only during the execution of that function. Other variables that are assigned-to within a function body are also local (note: we ll see exception to this later) Top-level variables (not within defs) are called global def foo(a, b): >>> foo(3, 4) c = (a + b) * 2 14 return(c) >>> a Error >>> c IMPORTANT! Error Demo examples: lec5.py

Ch3: local/global variables Another way to say this is that each function has its own scope or namespace >>> def f(x): y = 1 x = x + y print(x) return x >>> x = 3 >>> y = 2 >>> z = f(x) 4 >>> x? 3 >>> y? 2 >>> z? 4 Function f s variable x. A local variable that exists only within scope of definition of f Top-level or global variable x Two completely different variables! Hint: think of them as, e.g., x f and x global

Ch3: Stack frames At top level (the interpreter/shell) a symbol table keeps track of all variables (and values bound to them) defined at that level When a function is called, a new symbol table, or stack frame, is created to keep track of variables defined in the function and the values associated with those names. This includes (1) the function s parameters and (2) any other variables assigned to within the function When the function finishes, the stack frame goes away. Note: this isn t just one level, of course. As functions call other functions that call other functions, the stack (of stack frames) grows deeper

Ch3: Stack frames >>> def f(x): y = 1 x = x + y print(x) return x f: x X3 4 y 1 >>> x = 3 >>> y = 2 >>> z = f(x) 4 >>> x >>> y >>> z Demo: fn1, fn2, fn3 example in lec5.py UNDERSTAND IT! Draw stack frames! _main_: x 3 y 2 z 4

Ch 3: Fruitful functions Functions generally produce and return values: def add1(number): result = number + 1 return result Often use a variable to grab / catch the returned value so you can use it in further computations: >>> a = 3 >>> b = add1(5) >>> c = (a + b) ** 2 >>> c 81

Fruitful functions Though not covered in chapter 3, functions can also return more than one value via, e.g. return val1, val2, val3 def minandmax(a, b): if (a<b): return a, b else: return b, a >>> small, big = minandmax(23, 4) >>> small 4 >>> big 23 >>>

Ch 3: Fruitful functions. return vs print print and return are very different (and some students never quite get this!) def add1a(number): result = number + 1 return result def add1b(number): result = number + 1 print(result) Explore difference by using invoking them in shell in a couple of ways.

Ch 3: Why functions? Functions let you name a group of statements that make up a meaningful computation. Make programs easier to read and debug E.g. debug functions one by one, assemble into whole program Make programs shorter (in lines of code) by eliminating duplication. If you start seeing same (or nearly the same) segments of code in various places in your program, consider defining a function and replacing the common segment with function calls. Well designed functions often useful in other programs you write.

Ch 3: A few words on debugging For beginning programmers, I m not a big advocate of using real debuggers (the tools that come with IDEs like Wing and even IDLE). I m a fan of reading code carefully and critically and Using a lot of carefully placed print statements print early, print often - see where things go wrong! in HW1, if printed final results don t seem right, print out all your intermediate variables. Most people have variables for, e.g. driving time, gas needed, gas cost, hotel nights needed, etc. print them all! I am also a fan of baby steps : as I said earlier, write a little bit of code, then test, then a little more, and test again, etc. Small changes to a so-far-working program makes errors much easier to find. More to say on this later

Skip to Ch 5: Conditional execution Recall list of key programming components: Expressions, variables and assignment, functions, if-then-else (conditional execution), iteration We ve covered three of them! Can t easily compute a lot yet. Need the last two. Conditional execution today, iteration next week.

Ch5: Floor Division and Modulus But first, Ch5 has oddly placed section of two math ops (not really related to rest of Chapter!) Convenient right now, though, since useful for HW1 //: floor division operator. Divides two numbers and truncates (rounds down) to whole number 14 // 3 yields 4 8.1 // 2 yields 4.0 %: modulus operator. Yields remainder 11 % 3 yields 2 % can be very useful for, e.g., odd/even tests ((14 // 3) * 3) + (11 % 3) == 14 and in general (except for possible floating point issues), ((n // d) * d) + (n % d) == n math.ceil(x) yield nearest integer equal or greater than x. E.g. math.ceil(23.01) -> 24 and math.ceil(16.0) -> 16

Ch5: Boolean expressions and Logical Operators Demonstrated in Lec 3. Boolean expressions: have True/False as value E.g. 3 == (5 x) Boolean/relational operators: <, >, >=, <=,!= E.g. (x + y) < 4 Logical operators and, or, not E.g. (x < 5) or (z == foo ) Understand these well. Critical for conditional execution, decision making in programs!

Ch5: Condition execution - if The most basic conditional statement is if if (Boolean expression): lines of code that execute when Boolean expression evaluates to True more lines of code. These execute whether or not Boolean expression evaluated to True

Ch5: Condition execution if-else if (Boolean expression): code that executes when Boolean expr evaluates to True else: code that executes when Boolean not true code that executes after if-else statement, whether Boolean expression was True or not

print( before if ) if (a < b): print( a is smaller ) else: print( a is not smaller ) print( after if ) print( goodbye ) Ch5: if-else NOTE: indentation semantically important. Has execution effect.

Next time Finish conditional execution part of Chapter 5 nested conditionals, if-elif-else Note: the recursion section of Chapter 5 is very important but we will return to it later) start iteration (the last of the five key programming components). Read Ch 7