CS1 Lecture 4 Jan. 23, 2019

Similar documents
CS1 Lecture 4 Jan. 24, 2018

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 9 Feb. 5, 2018

CS1 Lecture 13 Feb. 13, 2019

CS1 Lecture 2 Jan. 16, 2019

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

CMSC 201 Spring 2017 Project 1 Number Classifier

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules

CS1 Lecture 22 Mar. 6, 2019

Lecture 4. Defining Functions

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

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

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

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

CS 100: Computability, Python Lists

Types, Expressions, and States

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

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

Introduction to Counting, Some Basic Principles

Introduction to Python

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

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

Repetition Through Recursion

Lecture 4. Defining Functions

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

CSC209. Software Tools and Systems Programming.

(Refer Slide Time 3:31)

Copied from: on 3/20/2017

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CMSC 201 Computer Science I for Majors

MS6021 Scientific Computing. MatLab and Python for Mathematical Modelling. Aimed at the absolute beginner.

APPM 2460 Matlab Basics

Lecture Transcript While and Do While Statements in C++

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

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

CS110: PROGRAMMING LANGUAGE I

Have the students look at the editor on their computers. Refer to overhead projector as necessary.

Introduction to Python Part 2

61A Lecture 2. Friday, August 28, 2015

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

Lecture 4. Defining Functions

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

Execution order. main()

PROGRAMMING FUNDAMENTALS

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Problem One: A Quick Algebra Review

Introduction to Scientific Computing

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

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

Downloaded from Chapter 2. Functions

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

CSE : Python Programming

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

CS Summer 2013

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

Usability Testing! Hall of Fame! Usability Testing!

Genome Sciences 373 Genome Informa1cs. Quiz Sec1on #1 March 31, 2015

61A Lecture 2. Wednesday, September 4, 2013

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

Skill 1: Multiplying Polynomials

CS Introduction to Programming Fall 2016

Science One CS : Getting Started

4. Java Project Design, Input Methods

CSCE 120: Learning To Code

SCHEME AND CALCULATOR 5b

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Today in CS161. Lecture #12 Arrays. Learning about arrays. Examples. Graphical. Being able to store more than one item using a variable

(Python) Chapter 3: Repetition

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Lecture 4: Defining Functions

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

61A Lecture 3. Friday, September 5

PROBLEM SOLVING 11. July 24, 2012

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Module 01: Introduction to Programming in Python

Please write your name and username here legibly: C212/A592 6W2 Summer 2017 Early Evaluation Exam: Fundamental Programming Structures in Java

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

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

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CS 1110 Prelim 1 October 4th, 2012

CMSC 201 Fall 2018 Lab 04 While Loops

Starting to Program in C++ (Basics & I/O)

Algebra 1. Standard 11 Operations of Expressions. Categories Combining Expressions Multiply Expressions Multiple Operations Function Knowledge

CS Lecture 19: Loop invariants

CS1 Lecture 12 Feb. 11, 2019

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

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

COM110: Lab 2 Numeric expressions, strings, and some file processing (chapters 3 and 5)

Semester 2, 2018: Lab 1

>>> * *(25**0.16) *10*(25**0.16)

Transcription:

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 with a 2. First homework due Mon., 9:00am Meet specifications precisely. Functions only (except import math also okay) Use a file editor! Don t type functions/long sections of code directly into Python interpreter. Keep the code you re working with in a.py file. Use run (or similar, depending on IDE) to send that code to interpreter. Test your code in interpreter by calling functions defined by your.py file.(then modify code/fix errors in editor, send modified code back to interpreter, test again, etc. - editor < - > interpreter until correct.) If you have downloaded Anaconda: launch the Spyder IDE that you ll see among other tools in the Anaconda-Navigator First homework (and discussion) assignment can be difficult for students completely new to programming. Read the book, practice, think it will make sense if you work at it. No need to / value in sending me email if you miss lecture. Lecture notes always posted. If you have a question after reading lecture notes, email certainly fine.

Last time Chapter 2 Expressions Variables and assignment statements Strings and expressions Plus a very quick look at defining functions (from Ch 3)

(last time) Variables and Assignment Statements Expressions yield values and we often want to give names to those values so we can use them in further calculations. A variable is a name associated with a value. The statement >>> x = 10 >>> creates the variable x and associates it with value 10. x = 10 is a statement not an expression. It doesn t produce a value. Instead, it associates x with the value 10 and subsequently x can be used in expressions! >>> x + 3 13

(last time) Variables and Assignment Statements In general, you write: >>> var_name = expression where var_name is a legal variable name (see book/python reference) and expression is any expression >>> zxy1213 = 14.3 + (3 * math.sin(math.pi/2)) >>> zxy1213 17.3 And since zxy1213 is a variable, thus a legal expression, we can write: >>> sillyvarname = zxy1213 1.0 >>> sillyvarname 16.3

(last time) Variables and Assignment Statements Only a single variable name can appear on to the left of an = sign (unlike for ==, the equality question ) >>> x + 3 = 4 X (crashes, yields syntax error.) >>> x + 3 == 4 OK (will return True or False, or give error if x has not been assigned a value)

(last time) Variables and Assignment Statements x >>> x = 3 >>> y = 4 * x >>> result = x + y y 12 3 result 15

(last time) Variables and Assignment Statements >>> x = 3 >>> y = 4 * x >>> result = x + y Rule (very important to remember): 1) Evaluate right hand side (ignore left for a moment!) yielding a value (no variable involved in result) 2) Associate variable name on left hand side with resulting value x y result 12 3 15 100 >>> x = 100 >>> y >>>? >>>result >>>? y and result are not changed! Don t think of assignments as constraints or lasting algebraic equalities. They make (perhaps temporary) associations between names and values.

Today Chapter 3 Function calls Math function (math module) Composition Defining functions <- super important! Flow of execution Parameters and arguments (There s a bit more to Ch3 but we ll cover that on Friday.)

Ch 3: Function calls In general: >>> fn_name(param1, param2,, paramn) returned_value We say a function takes N arguments and returns a computed value, returned_value (note: some functions, notably print, don t return anything other than special Python value None! Printing is not the same as returning a value. I will say more on this later ) >>> abs(-3) ß function call 3 ß value returned from function call >>> min(17, 4) ß function call 4 ß value returned

Ch 3: Function calls When arguments to function calls are expressions (very common), evaluate expressions first: Presume variable a has value 23, b has value -3 >>> max(a, 14, b+12) is evaluated by passing 23, 14, and 9 to the max function, yielding 23 In no sense are the variables a and b given to the function. Again, each argument expression is evaluated to produce a value, and those values are passed to the function.

Ch 3: Math functions I ve mentioned that Python has many libraries of useful functions (and sometimes special values). They re called modules. The functions in these modules are not part of basic Python. Usually, to get access, you use the import statement to load functions from a module into Python. We ll cover this in more detail later, but you should know about one key module: math (and you probably want to include import math in your HW1 Python file) >>> sqrt(4) error not defined in basic Python >>> import math >>> math.sqrt(4) 2.0 >>> math.pi 3.141592653589793 >>> math.sin(math.pi/2) 1.0

Ch 3: Function composition Get used to / do not be afraid to compose/nest function calls! Just like in math, f(g(h(x),i(y)), j(z)) is legal/sensible/normal. >>> math.log(abs(math.sin(-math.pi / 2.0))) Evaluate from inside out: math.sin(-math.pi / 2.0) -> -1 abs(-1) -> 1 math.log(1) -> 0.0

Ch 3: Defining New Functions Super important to understand this! (You will do a lot of this in this course!) Again, a function call, f(a,b,c) is an expression with a value, just like other Python expressions. Like in math, a function takes some input arguments, computes something, and returns an answer (though sometimes that answer is special Python value None) def enables you to define your own functions

Ch 3: Defining New Functions def functionname (param1, param2,, paramn):.. (body of function, can be many lines,. computes results value in terms of parameter. variables bound to input values). return some_result_value Make sure you understand: A primary use of functions is to define a general computation: Compute square root of any (non-neg) number Compute min of any pair of numbers, etc. If you don t include a return statement, function returns special value None Function body/computation specified in terms of variables (param1,, paramn) rather than specific values. The variables will be bound to specific values when the function is actually called (not at function definition time!)

HW1: function choosevehiclefortrip def tripcost (distancekm, vehspeedkph, kwhoursper100km, electricitycostperkwh, hotelcostpernight, breakfastcostperday, lunchcostperday, dinnercostperday) :.. Lines of code that calculate, in terms of parameters, cost of trip. print( string summarizing trip cost info ) return To the user of function, it s a black box. User sends in values, sees printed answer! (Note: actual returned value of function is None. The function doesn t return anything; instead it prints information) distancekm vehspeedkph INPUT... dinnercostperday tripcost OUPUT Printed trip cost info

HW1: function tripcost def tripcost(distancekm, vehspeedkph, kwhoursper100km, electricitycostperkwh, hotelcostpernight, breakfastcostperday, lunchcostperday, dinnercostperday) : totalcost = 0 # compute length of trip in hours hours = # compute kilowatt-hours needed kwhoursneeded = # compute electricity cost electricitycost = # compute number of nights (hotel stays) needed nights = This should be an integer! # perhaps compute a number (0.0->1) representing fraction of final day lastdayfraction = # compute breakfast, lunch, and dinner costs breakfastcost = # (lunchcost might involve more than one line and an if statement) dinnercost = # sum costs totalcost = # print results print(.)

Ch3: Defining functions def mymin (a,b): if (a < b): return a else: return b ----------------------- >>> mymin(5,7) >>> 5 (think of it like) a, b = 5, 7 if (a < b): return a else: return b 5

Ch 3: Defining functions def mymin (a,b): if (a < b): return a else: return b ----------------------- >> x, y = 12, 10 >> mymin(x,y) mymin(12,10) a, b = 12, 10 if (a < b): return a else: return b >> 10

Ch 3: Defining New Functions def foo(a, b, c): temp = a * b result = temp + c return result IMPORTANT When executing a function call: 1) first, the function s parameter variables are bound to the values of the function call s arguments 2) then, body of the function is executed >>> x = 3 >>> foo(x * x, x + 1, 3) ß foo will be executed with variable a bound to 9, b bound to 4, c bound to 3 foo knows nothing about x. x *isn t* passed in. 9, 4, and 3 are passed into foo.

HW1 Q2 - test function? Write function testtripcost() that makes at least five calls to tripcost(...) with different arguments." Students email me what s this, dude???? You should get in the habit of writing functions that you use to test your code as you are debugging it. When you wrote tripcost, you probably (I hope!) test it by trying >>> tripcost(...) multiple times with different values in the interpreter. But that can get tedious, especially for larger, more complicated program. It can be better to "package up" the tests, so you can easily run them. def testtripcost(): tripcost(...) tripcost(... different arguments...) tripcost(... Different arguments...) Then, every time you change tripcost, you just run testtripcost and examine the output version what it should be. It s important that you choose the arguments of your tests carefully! Think about what sets of argument test the variety of situations that the function should handle

HW1 Q2 - test function? It s important that you choose the arguments of your tests carefully! Think about what sets of argument test the variety of situations that the function should handle def testtripcost() tripcost(100.0, 100.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0) tripcost(200.0, 100.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0) Not very effective from random import random for testing! def testtripcost() tripcost(random(),random(),random(),random(),random(),random(), random(), random()) tripcost(random(),random(),random(),random(),random(),random(), random(), random()) tripcost(random(),random(),random(),random(),random(),random(), random(), random()) tripcost(random(),random(),random(),random(),random(),random(), random(), random()) tripcost(random(),random(),random(),random(),random(),random(), random(), random())

Next time Ch 3: The rest Variables and parameters are local Stack diagrams Fruitful functions Why Functions? Skip to first part of Ch 5: Conditionals Logical/Boolean expressions Conditional execution if/elif/else Read those sections!