Announcements Reading Read Chapter 4 (functions).

Slides:



Advertisements
Similar presentations
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Advertisements

Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Chapter 6 Horstmann Programs that make decisions: the IF command.
Jay Summet CS 1 with Robots IPRE Python Review 1.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Flow control 1: if-statements (Liang 72-80) if(radius < 0) { System.out.println(“cannot get area: radius below zero”); } else { double area = radius *
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Recitation 1 Programming for Engineers in Python.
Announcements Class / Recitation slides available on the syllabus page Check morning of for latest version We will start grading clickers next lecture.
Announcements Project 2 Available Tomorrow (we will send mail) Will be due 11:59PM October 9 th (Sunday) Week 6 ( I will be traveling this week) Review.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Introduction to Python
PPT 2. Other things: functions  Can you have a function with no inputs?  Yes: def f( ): return (3 + 4 )  Can you have a function with no outputs? 
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Announcements Project1 Due Wednesday September 21 st 4:30pm We will post instructions on how to turnin from home Note: you can always turn in from the.
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Announcements Survey link (can be found on piazza): OCJ6
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Programming Languages Programming languages are a compromise between spoken language and formal math. They allow humans to communicate with computers at.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 CS Review, iClicker -Questions Week 15. Announcements 2.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Discussion 4 eecs 183 Hannah Westra.
Python Boot Camp Booleans While loops If statements Else clauses
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
Announcements Reading Project1 Codelab: Read Chapter 4 (functions)
Python Review 1.
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
Control Structures – Selection
Arithmetic operations, decisions and looping
Topics Introduction to File Input and Output
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
Coding Concepts (Sub- Programs)
CISC101 Reminders Assn 3 due tomorrow, 7pm.
5. Functions Rocky K. C. Chang 30 October 2018
Chapter 3: Selection Structures: Making Decisions
CISC101 Reminders All assignments are now posted.
15-110: Principles of Computing
Summary of what we learned yesterday
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
COMPUTER PROGRAMMING SKILLS
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Topics Introduction to File Input and Output
Presentation transcript:

Announcements Reading Read Chapter 4 (functions)

Python Boot Camp Recap Variables name values: X_12, _par, greeting, … All variables can be assigned: x = 15 All variables can be “read”: y = x Values have types: int, float, str, list, … The type determines what additional operations can be performed on the values, and what they mean Some values can be converted to another type: chr(66), ord(“B”), float(5), int(3.2)

Python Boot Camp Recap Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction( ) The number of arguments is fixed; could be zero The function returns a value; could be None

Function Output The return statement specifies what value the function returns to the call site: return Return Statement Passing a value out of a function (output) Last statement executed Multiple conditional exit possible

Function Call as Substitution When a function is called The argument values are bound (assigned) to the parameter names The program of the function is executed as if those program statements were substituted for the call Upon execution of the return statement, the return value is substituted for the function call If no return statement is executed, and the program of the function body ends, the function returns None, indicating that no value is returned to the calling place.

Example x = 12 y = 4 def mySum(a,b): u = a+b x = 1 return u print(x,y) print(mySum(x,y)) print(x,y) Unless explicitly declared global, x is a local variable

More on Returns Returns are the last statement executed by a function The function is considered to be “done” at this point There may be other statements “after” the return, but these are not executed (but see conditionals later-on def sumOfTwo(a,b): return a+b print(a+b) print(sumOfTwo(4,5))

Stringing together functions We can build up complex expressions from functions def sumOfTwo(a,b): return a+b print(sumOfTwo(sumOfTwo(4,5), sumOfTwo(1,2))) OR a = sumOfTwo(4,5) b = sumOfTwo(1,2) c = sumOfTwo(a,b) print(c)

A “Sample” Program def task1(a,b): … y = …. return y def task2(a,b,c): …. z = … return z def main(): input1, input2 = eval(input(…)) output1 = task1(input1, input2) output2 = task2(input1, input2, output1) print(output2)

Local Variables Function parameter names act as local variables: They are available as variables for the execution of the function body They get their initial value from the values at the call site (value binding) When the function ends, they are no longer available You can define additional variables in the function body They will be local variables by default When the function ends, they no longer exist

Local Variables a = 3 y = 10 def myFun(a): print (a) y = 1 myFun(4) print(a) print(y)

Question: does this program print 3 or 4? x = 3 def myFun(): print (x) x = 4 myFun() A: 3 B: 4

Question: Are these programs equivalent? a = 3 def myFun(a): print (a) myFun(4) a = 3 print (a) 21 A: yes B: no

Variables and Functions Variables defined outside of the function are global variables Global variables can be changed inside a function body Using global variables inside functions is dangerous: Multiple calls to a function may yield different results if the program “rebinds” such variables At minimum, declare global variables as global in the function body and document their use.

Variables and Functions x = 3 def myFun(): print (x) x = 4 myFun() x =5 myFun()

You must be careful! x = 3 def myFun(): print (x) x = 1 x = 4 myFun() x =5 myFun() ERROR!

Global Variables How can we get the example code we saw earlier to work? Python is not sure if we want x to be a local variable or if it should refer to the x we defined outside of the function We can inform python if we want x to refer to the variable outside of the function New keyword global

This works! x = 3 def myFun(): global x print (x) x =1 x = 4 myFun()

Global or Local? If the global keyword is used, the variable is global If the first use of the variable is a ‘read’ (reference), the variable is global NOTE: We cannot assign to such a variable later Function arguments are always local If the first use of the variable is a write (assignment), the variable is local Unless the variable is defined global

Clicker Question: Is x global or local? x = 3 def myFun(): y = 4 z = x + y myFun() A: global B: local

Let’s Review Functions take input and produce output Output is provided by the “return” statement Otherwise the function does not provide output At the call site of the function the arguments get bound The arguments can rebind variables that have already been defined for the duration of the call You can use global variables, defined outside the function, but you must be careful!

Advice Unless absolutely necessary avoid naming parameters and local variables the same as global variables

Argument Typing Functions typically assume something important about the arguments Will this work no matter what we provide as arguments? def sumOfTwo(a,b): return a+b

Function Arguments Consider the following three cases: One of these cases will throw an error. This behavior is defined by the code inside the function res = sumOfTwo(1,2) res = sumOfTwo(“Hello “, “World”) res = sumOfTwo(“Hello”, 1)

Function Arguments There are two ways to handle this difficulty 1. Tell everyone what the function expects 2. Include checks inside the function to ensure the arguments are what is expected A combination of both techniques should be used

Function Documentation This solution uses comments and if-statements. We will revisit this in later slides # This function expects two integers # and returns -1 otherwise def sumOfTwo(a,b): if type(a) == int and type(b) == int : return a+b return -1

Announcements Reading Read Chapter 4 (functions) Start on reading Chapter 5 (conditionals) Project1 Will be posted Friday, September 7 Due Saturday, September 15 th 11:58pm We will post instructions on how to turnin from home Note: you can always turn in from the lab machines Codelab: Sign up for CodeLab; instructions on home page Practice, practice, practice

Functions that Modify Parameters Suppose you are writing a program that manages bank accounts. One function we would need to do is to accumulate interest on the account. Let’s look at a first- cut at the function. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance

Functions that Modify Parameters The intent is to set the balance of the account to a new value that includes the interest amount. Let’s write a main program to test this: def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount)

Functions that Modify Parameters We hope that that the 5% will be added to the amount, returning >>> test() 1000 What went wrong? Nothing!

Functions that Modify Parameters The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively. def addInterest(balance, rate): newBal = balance*(1+rate) balance = newBal def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively. def addInterest(balance, rate): newBal = balance*(1+rate) balance = newBal def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters def addInterest(balance, rate): newBalance = balance * (1 + rate) return newBalance def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters def addInterest(balance, rate): newBalance = balance * (1 + rate) return newBalance def test(): amount = 1000 rate = 0.05 amount = addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters Why is the following solution inferior? amount = 1000 rate = 0.05 def addInterest(): global amount global rate amount = amount * (1 + rate) addInterest() print(amount)

Project 1: The Angry Birds Lost Found at homepage >> projects To be posted by tomorrow, Sep 7 (Friday) Due Sep. 15, just before midnight Submit early in case there is a problem

Project 1 The angry birds tried their level best but in the end lost. Now the pigs are celebrating by going on a cruise, and their favorite entertainment is to jump into the pool. Realizing your valuable help, the pigs retain you as consultant and have you calculate the necessary speed to hit the pool squarely in the middle…

Project 1 First scenario: The pigs can’t jump up, so they run off a horizontal stage for their splash-down.

Project 1 Scenario 2: The pigs gained a lot of weight, so the stage collapsed. Lucky for the pigs, it can still be used as a ramp, and they need the exercise, but the calculation is a bit more complex…

Boolean Values True, False Result of comparison, e.g. x < y Boolean operations: And:True and False ≡ False (x >= 5) and (x <= 10) Or:True or False ≡ True (x 10) Not:not True ≡ False not (3 == 4)

Precedence Question Consider a*b+c*d; which of the three is it equal to? A. (a*b) + (c*d) B. a * (b+c) * d C. ((a * b) + c) * d

Precedence Multiplication and division take precedence over addition and subtraction Consider a*b+c*d; which of the three is it equal to? A. (a*b) + (c*d) B. a * (b+c) * d C. ((a * b) + c) * d What about comparison ( =, >) vs. Boolean ops (and, or, not)? Comparisons take precedence …

IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7 if x > 10: print x x = x + 1 x = True if x: print x

if x > 10 print x x = x + 1 TrueFalse x = 7

Conditionals It is also possible to specify what to do if the condition is False. Contrast these two examples. x = 7 if x > 10: print x x = x + 1 x = 7 if x > 10: print x else: x = x + 1

CQ: Are these programs equivalent? 21 A: yes B: no x = 7 if x > 10: print x x = x + 1 print x x = 7 if x > 10: print x else: x = x + 1 print x

if x > 10 print x x = x + 1 True False x = 7 if x > 10: print x x = x + 1

if x > 10 print x TrueFalse x = 7 if x > 10: print x else: x = x + 1

Homework Work on Project 1 Do the pre lab Review chapter 4 (functions) Start on chapter 5 (conditionals)