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? 

Slides:



Advertisements
Similar presentations
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Advertisements

Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Python Programming Language
Introduction to Computing Science and Programming I
Conditional Statements Introduction to Computing Science and Programming I.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
From cisc106 import * def f(x): if x < 10: return (x+9) elif x < 5: return (x + 4) elif x < 0: return (x) else: return(0) assertEqual(f(-1), ______)
Jay Summet CS 1 with Robots IPRE Python Review 1.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Python November 14, Unit 7. Python Hello world, in class.
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.
Making Decisions In Python
Decision Making George Mason University. Today’s topics 2 Review of Chapter 2: Decision Making Go over exercises Decision making in Python.
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Introduction to Python and programming Michael Ernst UW CSE 190p Summer 2012.
19/5/2015CS150 Introduction to Computer Science 1 Announcements  1st Assignment due next Monday, Sep 15, 2003  1st Exam next Friday, Sep 19, 2003  1st.
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
An Introduction to Textual Programming
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
Python – Making Decisions Lecture 02. Control Structures A program that only has one flow is useful but limited. We can use if statements to make these.
PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?
INLS 560 – C ONDITIONALS Instructor: Jason Carter.
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.
PPT 4. Variables: (assignment)  A variable: holds a value.  A space in RAM we give a name to  A lot like parameters, only we create them within the.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Introduction to Python and programming Ruth Anderson UW CSE 140 Winter
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
22/11/ Selection If selection construct.
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Agenda Basic Logic Purpose if statement if / else statement
Python Conditionals chapter 5
Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Strings:  Strings?  concatenate (join) +  make multiple copies using *  compare: > =
Decision Structures and Boolean Variables. Sequence Structures Thus far, we’ve been programming “sequence structures” Thus far, we’ve been programming.
Decision Structures, String Comparison, Nested Structures
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.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
31/01/ Selection If selection construct.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
These Guys? Wait, What? Really?  Branching is a fundamental part of programming  It means taking an action based on decision  The decision is dependent.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Announcements Reading Read Chapter 4 (functions).
Input, Output and Variables GCSE Computer Science – Python.
Introduction to Decision Structures and Boolean Variables
Python Review 1.
Other things: functions
Topics The if Statement The if-else Statement Comparing Strings
Topics The if Statement The if-else Statement Comparing Strings
Line Continuation, Output Formatting, and Decision Structures
Selection CIS 40 – Introduction to Programming in Python
Conditions and Ifs BIS1523 – Lecture 8.
Intro to Nested Looping
Introduction to Programming Using Python PART 2
Intro to Nested Looping
Adding Intelligence Check for the presence or absence of a condition in the environment Take the appropriate actions Involves making a choice (to do or.
What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k)
More While Loops.
COMPUTING.
Presentation transcript:

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?  Yes: def f(x):  Can you have a function with no inputs and outputs?  Yes: def f( ): 3 + 4

Functions:  Math: f(x) = x 3  Python:def f(x): return(x**3) Given a particular input to this function, will we ALWAYS get the same output? e.g. f(2) f(3) Could we say that f(2) is equivalent to 8? Could we say that f(3) is equivalent to 27?

Functions(how they work) def f(x): # code for a function that return(x**3) # returns the cube of a number f(2)# Calls the function. The function is now executed (i.e., calculated, # converted to machine language and instructions run by the CPU). # # After f(2) runs, all that remains is what is RETURNED When the function is done being executed, 8 is returned (i.e., output from the function) and the instructions are removed from memory (RAM). Only 8 remains. Thus, for our purposes, f(2) is exactly the same thing as the number 8.

Using functions:  Remember: after we use a function, what remains is what is returned from the function def add2(x,y): return(x + y) def add(x,y): return(add2(x,y) + add2(x,y)) print(add(7,3))

Using functions: def add2(x,y): return(x + y) def div(x,y,z): return(add2(x,y) / z) print(div(7,3,2))

Using functions: def add2(x,y): return(x + y) def div(x,z): return(add2(x,3) / z) print(div(7,2))

Using functions: def add2(x,y): return(x + y) def div(y,x): return(add2(y,3) / x) print(div(7,2))

Using functions: def add2(x,y): return(x + y) def add3(y,x): return(add2(y,3) + add2(11,x)) print(add3(7,2))

def f1(par1, par2): return(par2 - par1) print(f1(2,4)) #2 def f2(x1,x2): return(x1**2 + x2) print(f2(3,6)) #15 def f3(p1,p2): return(f2(p1,p2) + f1(p1,p2)) print(f3(3,2)) 10 def f4(p1,p2): return(f2(p2,p2) - f1(p1,p1)) print(f4(4,2)) 6 def f5(q1,q2): return(f2(q2,q1)) print(f5(17,5)) 42 def f6(par1,par2): return( 3 + f1(par1, 17+par1)) print(f6(4,26)) 20

Given the function def Squr(par1): return(par1 ** 2) def dbl(par2): return(par2 + par2) def Func1(p1,p2): return(Squr(p1) - Squr(p2)) print(Func1(4,3)) >>7 def Func2(p1,p2,p3): return(Squr(p1) * Func1(p2,p3)) print(Func2(2,3,2)) >>20 def Func3(p1,p2): return(dbl(Squr(p1))) print(Func3(4)) >>AACH CRASH BURN def Func4(p1,p2): return(dbl(Squr(p2)+ Squr(p2)+3)) print(Func4(2,4)) >> 70 def Func6(p1): return(dbl(dbl(dbl(Squr(p1)+1))-Squr(3))) print(Func6(-2)) >>22

Piecewise functions

If /else (branching) def f(x): if x > 0: return (3**2/x) else: return (0) f(3) # this equals? f(0) # this equals? f(-2) # this equals? 3 2 if x > 0 _ f(x) = x 0 otherwise

Piecewise functions  How about this? x 3 + 2x if x > 2 f(x) = -x 3 + 2x if x < 0 -1 otherwise

If /else (branching) def f(x): if x > 2: return (x ** * x) elif x < 0: return(-x ** * x) else: return (-1) f(3) # this equals? f(0) # this equals? f(-2)# this equals? x 3 + 2x if x > 2 f(x) = -x 3 + 2x if x < 0 -1 otherwise

Comparators (return T or F) ==equal to5==5true !=not equal to8!=5true >greater than3>10false <less than5<8true >=greater than 6>=8false or equal to <=less than6<=8true or equal to

Note: ==  if conditions MUST use == (equality)  not = (assignment)  ==  Asks a question: is this equal to that???  this == that ?  Yes or No!  True, this is equal to that, or  False, this is not equal to that  =  We’ll see this in use shortly

If Statement structure: if condition1 is true: execute this statement(s) elif condition 2 is true: execute this statement(s) elif condition3 is true: execute this statement(s) else: execute this statement(s) #only one else condition!

Rules for If/elif/else: 1. If/elif condition must evaluate something that is True or False  if (3== 4)…  if (8 > 4)…  if (f2(3) < 4)…  if (func(7)!=4)… 2. If does not require an elif or an else 1. Only one else if there is an else 3. The first branch that is true is executed, and nothing else: if (x > 3): return(3) elif (x > 2): return (2) 4. If the condition is False, nothing indented under the condition is executed.

Example def f(x): if x > 10: return (x+9) elif x < 7: return (x + 4) else: return(0) print(f(12)) # what is printed? print(f(6)) # what is printed? print(f(8)) # what is printed? print(f(7)) # what is printed?

Example def f(x): if x != 10: return (x * 2) else: return (x ** 2) print(f(6)) print(f(10))

Example def f(x): if x < 10: return (x+9) elif x == 5: return (x + 4) elif x >10: return (x) else: return(0) print(f(5)) ?

and def q(x): if (x>5) and (x < 10): return("just enough") elif (x >= 10) and (x < 15): return("too much") else: return("no idea") print(q(12)) 1. What does and do? 2. What type is returned from this function?

Logical Operators and(True and True) (True and False) (False and True) (False and False) True False or(True or True) (True or False) (False or True) (False or False) True False not(not True) (not False) False True

diff? def q1(x): if (x>6) and (x < 5): return("just enough") elif (x > 15) and (x < 20): return("too much") else: return("no idea") print(q1(7)) print(q1(13)) def q2(x): if (x>6) or (x < 5): return("just enough") elif (x > 15) or (x < 20): return("too much") else: return("no idea") print(q2(7)) print(q2(13))

What happens? def ReturnSomething(value): if value = 1: return “glub” else: return “blug” print (ReturnSomething(1))

Strings  Python cares about types :  We can do different operations on different types  Can’t add a string with a number:  Can’t: print(“puddle” + 4)  Can add strings to strings!  Word of the day: Concatenate  means join (string concatenated to string)  Can: print(“puddle” + “ jumping”)  Can: print(“puddle” + “4”)  Can: return(“bat” + “ty”)  Can multiply a string by a number:  Can: print(“bla” * 38)  Can’t: print(“bla” * “bla”)

Operator overloading:  doing more than one operation with the same operator, depending on the types involved  using + for both numbers (to add) and strings (to join, aka CONCATENATE)  using * to multiply numbers and * to make multiple copies of a string

Adding Strings: def addstrings(par1): return(par1 + "ubba") print (addstrings("gub")) def addmore(par1): return(addstrings(par1)+addstrings(par1)) print(addmore("hab"))

Printing inside my function:  What if I want to see the string that was input into the function? def addstrings(par1): print(“par1 came in”) return(par1 + "ubba") print (addstrings("gub")) We want to print what’s inside par1, not “par1” Now we’re adding what’s inside par1 to “came in” and that is what gets printed by the function before we leave the function. print(par1 + “came in”)

Printing inside a function def f_to_c(ftemp): print("The temp before conversion is ftemp") return((ftemp - 32 )/ 1.8) print (f_to_c(68)) print (f_to_c(22))  Is this what we wanted?  Is this what we want now? print("The temp before conversion is” + ftemp

Solution def f_to_c(ftemp): print("The temp before conversion is” + str(ftemp)) return((ftemp - 32 )/ 1.8) print (f_to_c(68)) print (f_to_c(22))  Note:  ftemp is not in quotes.  When it is not in quotes, we’re talking about what’s inside of ftemp and not the word ftemp  what is inside of ftemp is an integer.  We can’t add integers to strings  str(ftemp)  takes the number inside of the parameter ftemp and converts it to a string

New Function  input : 3 integers - x, y and z  Output: a string  “Yes x is divisible by both y and z” or  “No, x is not evenly divisible by y and z”  “x is not in range”  Function name: isDivisible  Calculations:  Two parts:  check if x is between 0 and 100  Check if x is evenly divisible by both y and z

# input : 3 integers, x, y and z # Output: a string # “Yes x is divisible by both y and z” or # “No, x is not evenly divisible by y and z” # “x is not in range” # Function name: isDivisible # Calculations: check if x is greater than 0 and less than 100 and is evenly #divisible by both y and z def isDivisible(x, y,z): if ((x > 0)and (x < 100)) and ((x%y) == 0) and (x % z) == 0): #ugh! Long and hard to read return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z)) else: return (“No, “+str(x)+” is not evenly divisible by “+str(y)+” and “+str(z)) print(isDivisible(15,5,3)) print(isDivisible(150,5,3)) Is this what we want ? Will it always work?

# input : 3 integers, x, y and z # Output: a string # “Yes x is divisible by both y and z” or # “No, x is not evenly divisible by y and z” # “x is not in range” # Function name: isDivisible # Calculations: check if x is greater than 0 and less than 100 and is evenly #divisible by both y and z def isDivisible(x, y,z): if ((x > 0)and (x < 100)) and ((x%y) == 0) and (x % z) == 0): return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z)) elif ((x > 0)and (x < 100)) : return (“No, “+str(x)+” is not evenly divisible by “+str(y)+” and “+str(z)) else: return (str(x) + “is not in range”) print(isDivisible(15,5,3)) print(isDivisible(150,5,3)) Is this what we want ? Will it always work?

#input : 3 integers, x, y and z #Output: a string # “Yes x is divisible by both y and z” or # “No, x is not evenly divisible by y and z” # “x is not in range” #Function name: isDivisible #Calculations: check if x is greater than 0 and less than 100 and is evenly #divisible by both y and z def isDivisible(x, y,z) if (x > 0)and (x < 100): if ((x%y) == 0) and ((x % z) == 0): return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z)) else: return (“No, “+str(x)+” isn’t evenly divisible by “+str(y)+” and “+str(z)) else: return(str(x ) + “ is not in range”) print(isDivisible(15,5,3)) print(isDivisible(150,5,3)) Now what if x is 250 or -1?

Same? def g(x): if (x>5) and (x < 10): return("just enough") elif (x > 5) and (x < 15): return("too much") else: return("no idea") def g(x): if (x > 5): if (x < 10): return("just enough") elif (x < 15): return("too much") else: return("no idea") print (g(12)) What about: print (g(17))

Loan Qualifier We want to write a function that tells someone whether they qualify for a loan.  If a person makes more than 35,000 and they’ve been employed for at least 2 years,  they qualify.  If they make over 35,000, but haven’t been employed for at least 2 years,  They should get a message saying how long they need to wait before they can get the loan  (e.g., if they’ve only been employed for 1.2 years, the program should tell them to come back in.8 years)  If they don’t make 35,000, but have been employed for over 2 years,  They should get a message telling them the minimum salary requirement  If they don’t make 35,000 and they haven’t been employed for 2 years,  they don’t qualify. Using Nested If (ifs inside of ifs) can you write this?

LoanQualifier def loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else: temp = str(2 – yrs) return("You will qualify in " + str(round(2-yrs),2)+ " years.") else: if (yrs>=2): return("You need to make at least to qualify for a loan") else: return("I'm sorry, you don't qualify.") #Note the test cases – we’re testing all outputs to make sure they work print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2)) print (loanqualifier(20000,4)) print (loanqualifier(20000,1.2))

LoanQualifier def loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else: return("You will qualify in " + str(round(2-yrs),2)+ " years.") else: if (yrs>=2): return("You need to make at least to qualify for a loan") else: return("I'm sorry, you don't qualify.") #Note the test cases – we’re testing all outputs to make sure they work print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2)) print (loanqualifier(20000,4)) print (loanqualifier(20000,1.2))

LoanQualifier def loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else: temp = str(2 – yrs) return("You will qualify in " + temp + " years.") else: if (yrs>=2): return("You need to make at least to qualify for a loan") else: return("I'm sorry, you don't qualify.") #Note the test cases – we’re testing all outputs to make sure they work print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2)) print (loanqualifier(20000,4)) print (loanqualifier(20000,1.2))