EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Similar documents
EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

CONTROL AND ENVIRONMENTS 1

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

C ONTROL AND H IGHER O RDER F UNCTIONS

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

61A Lecture 3. Friday, September 5

CONTROL AND HIGHER ORDER FUNCTIONS 2

CONTROL AND HIGHER ORDER FUNCTIONS 1

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Wednesday, September 4, 2013

SCHEME AND CALCULATOR 5b

CONTROL AND HIGHER ORDER FUNCTIONS 1

ENVIRONMENT DIAGRAMS AND RECURSION 2

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

CS61A Notes Week 3: Environments and Higher Order Functions

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

CS1 Lecture 3 Jan. 18, 2019

CS61A Notes Week 13: Interpreters

CS1 Lecture 3 Jan. 22, 2018

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

Python Evaluation Rules

Python for C programmers

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

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

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CSE : Python Programming

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

HIGHER ORDER FUNCTIONS 2

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Conditional Execution

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

Python: common syntax

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

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

Python - Conditional Execution

Python for Informatics

Lecture 02 Making Decisions: Conditional Execution

Lists, loops and decisions

APPM 2460 Matlab Basics

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

TUPLES AND RECURSIVE LISTS 5

Racket Style Guide Fall 2017

UNIVERSITY of CALIFORNIA at Berkeley Department of Electrical Engineering and Computer Sciences Computer Sciences Division

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Starting. Read: Chapter 1, Appendix B from textbook.

Ruby: Introduction, Basics

CIS 110: Introduction to Computer Programming

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

Statements 2. a operator= b a = a operator b

Conditional Execution

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS 61A Discussion 8: Scheme. March 23, 2017

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

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Control Structures 1 / 17

Comp Exam 1 Overview.

Downloaded from Chapter 2. Functions

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

Introduction to Python (All the Basic Stuff)

RECURSION: n. SEE RECURSION 3

Introduction and Functions Summer 2018 Discussion 0: June 19, 2018

Test #2 October 8, 2015

CIS192: Python Programming

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS 11 python track: lecture 3. n Today: Useful coding idioms

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

CMSC 201 Computer Science I for Majors

Lecture #3: Environments

Mastering Python Decorators

APCS Semester #1 Final Exam Practice Problems

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

CSCE 110: Programming I

Discussion 4. Data Abstraction and Sequences

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

CSE341, Spring 2013, Final Examination June 13, 2013

CS 11 Haskell track: lecture 1

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

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

Ruby: Introduction, Basics

LOOPS. Repetition using the while statement

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

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

EXCEPTIONS, CALCULATOR 10

Language Reference Manual

6.001 Notes: Section 15.1

ENGR 101 Engineering Design Workshop

COSC2031 Software Tools Introduction to C

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Coral Programming Language Reference Manual

Problem Solving for Intro to Computer Science

CS 111X - Fall Test 1

Transcription:

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)) - square(4) 1 Expressions Expressions describe a computation and evaluate to a value. There are two types of expressions, primitive and compound. 1.1 Primitive Expressions A primitive expression is a single evaluation step: you either look up the value of a name, or take the literal value. For example, numbers, variable names, and strings are all primitive expressions. >>> 2 2 >>> Hello World! Hello World! 1

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 2 1.2 Call Expressions Call expressions are expressions that involve a call to some function. Call expressions are just another type of expression, called a compound expression. A call expression invokes a function, which may or may not accept arguments, and returns the function s return value. Recall the syntax of a function call: Every call expression is required to have a set of parentheses delimiting its comma-separated operands. To evaluate a function call: 1. First evaluate the operator, and then the operands (from left to right). 2. Apply the function (the value of the operator) to the arguments (the values of the operands). If the operands are nested function calls, apply the two steps to the operands. 1.3 Questions 1. Determine the result of evaluating f(4) in the Python interpreter if the following functions are defined: from operator import add def double(x): return x + x def square(y): return y * y def f(z): add(square(double(z)), 1)

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 3 2. What is the result of evaluating the following code? from operator import add def square(x): return x * x def so_slow(num): return num num / 0 square(so_slow(5)) 3. What will python print? def f(): print( f ) return print def a(): print( a ) return "hello" def b(): print( b ) return "world" f()(a(), b())

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 4 2 Statements A statement in Python is executed by the interpreter to achieve an effect. For example, we can talk about an assignment statement. In an assignment statement, we ask Python to assign a certain value to a variable name. There are also compound statements but we will cover them later! We can assign values to names using the = operator Every assignment will assign the value on the right of the = operator to the name on the left. For example: >>> foo = 5 Binds the value 5 to the name foo. We can also bind values to names using the import statement. >>> from operator import add Will bind the name add to the add function. Function definitions also bind the name of the function to that function. >>> def foo():... return 0 Will bind foo the function defined above Assignments are also not permanent, if two values are bound to the same name only the assignment executed last will remain. >>> add = 5 >>> from operator import add After the above two statements are executed the value 5 will no longer be bound to add but rather the add function from operator will.

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 5 2.1 Questions 1. Determine the result of evaluating f oo(5) in the Python interpreter if the following functions are defined in the order below: >>> def bar(param):... return param >>> bar = 6 >>> def foo(bar):... return bar(bar) 2. Determine the result of evaluating f oo(5) in the Python interpreter if the following functions are defined in the order below: >>> def bar(param):... return param >>> zoo = bar >>> bar = 6 >>> def foo(bar):... return zoo(bar) 3. What would python print? >>> from operator import add >>> def sub(a, b):... sub = add... return a - b >>> add = sub >>> sub = min >>> print(add(2, sub(2, 3)))

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 6 3 Control Control refers to directing the computer to selectively choose which lines of code get executed. This can mean skipping a portion of code (conditionals) or repeating a portion of code multiple times (iteration). 3.1 Conditional Statements Conditional statements allow programs to execute different lines of code depending on the current state. A typical if-else set of statements will have the following structure: if <conditional expression>: <suite of statements> elif <conditional clause>: <suite of statements> else: <suite of statements> The else and elif statements are optional and you can have any number of elif statements. Here a conditional clause is something that evaluates to either True or False. The body of statements that get executed are the ones under the first true conditional clause. After a true conditional clause is found, the rest are skipped. Note that in python everything evaluates to True except False, 0, "", and None. There are other things that evaluate to False but we haven t learned them yet. >>> if 2 + 3:... print(6) 6 Here s some example code: >>> def mystery(x):... if x > 0:... print(x)... else:... x(mystery)... >>> mystery(5) 5 >>> mystery(-1) TypeError: int object is not callable

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 7 1. Write a simple function that takes in one input x, whose value is guaranteed to be between 0 and 100. if x 75 then print Q1. If 50 x < 75 then print Q2. If 25 xs < 50 then print Q3. If x < 25 then print Q4. def find_quartile(x): 2. Now try rewriting the function so that at most 4 lines of code inside the function will ever get executed. def find_quartile(x):

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 8 3.2 Iteration Using conditional statements we can ignore statements. On the other hand using iteration we can repeat statements multiple times. A common iterative block of code is the while statement. The structure is as follows: while <conditional clause>: <body of statements> This block of code literally means while the conditional clause evaluates to T rue, execute the body of statements over and over. >>> def countdown(x):... while x > 0:... print(x)... x = x - 1... print("blastoff!")... >>> countdown(3) 3 2 1 Blastoff! 1. Fill in the is prime function to return T rue if n is a prime and F alse otherwise. Hint: use the % operator. x%y returns the remainder when x is divided by y. def is_prime(n):

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 9 4 Pure and Non-Pure Functions Pure function It only produces a return value (no side effects), and always evaluates to the same result, given the same argument value(s). Non-Pure function It produces side effects, such as printing to the screen. Further in the semester, we will further expand on the notion of a pure function versus a non-pure function. 4.1 One Moar Question 1. What do you think Python will print for the following? om and nom are defined as follows: >>> def om(foo):... return -foo >>> def nom(foo):... print(foo) >>> nom(4) >>> om(-4) >>> save1 = nom(4) >>> save1 + 1 >>> save2 = om(-4) >>> save2 + 1

DISCUSSION 1: EXPRESSIONS, STATEMENTS, AND FUNCTIONS Page 10 5 Secrets to Success in CS61A CS61A is definitely a challenge, but we all want you to learn and succeed, so here are a few tips that might help: Ask questions. When you encounter something you dont know, ask. That is what we are here for. This is not to say you should raise your hand impulsively; some usage of the brain first is preferred. You are going to see a lot of challenging stuff in this class, and you can always come to us for help. Go to office hours. Office hours give you time with the instructor or TAs by themselves, and you will be able to get some (nearly) one-on-one instruction to clear up confusion. You are not intruding; the instructors and TAs like to teach! Remember that, if you cannot make office hours, you can always make separate appointments with us! Do the readings (on time!). There is a reason why they are assigned. And it is not because we are evil; that is only partially true. Do (or at least attempt seriously) all the homework. We do not give many homework problems, but those we do give are challenging, time-consuming, and rewarding. The fact that homework is graded on effort does not imply that you should ignore it: it will be one of your primary sources of preparation and understanding. Do all the lab exercises. Most of them are simple and take no more than an hour or two. This is a great time to get acquainted with new material. If you do not finish, work on it at home, and come to office hours if you need more guidance! Study in groups. Again, this class is not trivial; you might feel overwhelmed going at it alone. Work with someone, either on homework, on lab, or for midterms, as long as you don t violate the cheating policy! Most importantly, have fun!