Other things: functions

Slides:



Advertisements
Similar presentations
What gets printed out? def f(n): if (n == 0): return (" ") else: print(“blug ") return f(n-1) f(3)
Advertisements

Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Introduction to Computing Science and Programming I
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), ______)
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 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.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in 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? 
PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?
REVIEW A relation is a set of ordered pairs. {(2,3), (-1,5), (4,-2), (9,9), (0,-6)} This is a relation The domain is the set of all x values.
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.
Strings:  Strings?  concatenate (join) +  make multiple copies using *  compare: > =
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.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
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 – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Input, Output and Variables GCSE Computer Science – Python.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Math operations 9/19/16.
Basic concepts of C++ Presented by Prof. Satyajit De
Python Review 1.
Whatcha doin'? Aims: To start using Python. To understand loops.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Debugging and Random Numbers
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Variables, Expressions, and IO
The CS 5 Black Post Penguins Invade Dormitory
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson #6 Modular Programming and Functions.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Conditional Statements
Selection CIS 40 – Introduction to Programming in Python
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Coding Concepts (Sub- Programs)
Algorithm Discovery and Design
Topic 1: Problem Solving
We’re moving on to more recap from other programming languages
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Python Programming Language
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Lesson #6 Modular Programming and Functions.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
CISC101 Reminders All assignments are now posted.
For loops Taken from notes by Dr. Neil Moore
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)
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
More While Loops.
Chapter 3: Selection Structures: Making Decisions
Making decisions with code
Strings: Strings? concatenate (join) + make multiple copies using *
Hardware is… Software is…
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
COMPUTING.
Selamat Datang di “Programming Essentials in Python”
Getting Started in Python
Lecture 6 - Recursion.
Presentation transcript:

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

Functions: Math: f(x) = x3 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 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 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 Class 3 stopped after first example on Wed

Given the function def Squr(par1): return(par1 ** 2) def dbl(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 Given the function def Squr(par1): return(par1 ** 2) def dbl(par2): return(par2 + par2) Class 2 stopped (Wed)

Piecewise functions Can we have a function like this? 32 if x > 0 𝑥 0 otherwise

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

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

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

Comparators (return T or F) == equal to 5==5 true != not equal to 8!=5 true > greater than 3>10 false < less than 5<8 true >= greater than 6>=8 false or equal to <= less than 6<=8 true or equal to Class 3 stopped here

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: elif condition3 is true: else: #only one else condition!

Rules for If/elif/else: 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)… If does not require an elif or an else Only one else if there is an else The first branch that is true is executed, and nothing else: if (x > 3): return(3) elif (x > 2): return (2) 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)) ? Class 2 stopped here

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)) What does and do? 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) not (not True) (not False)

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)) Class 3

What have we learned so far? Atomic data Types Operators Functions Input parameters Return values Diff between return and print!!! Function composition Branching (if conditions)

Strings Python cares about types: Can’t add a string with a number: 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"))

def getname(x): if x == 3: return("John") elif x == 13: return("Joe") elif x == 7: return("Sam") else: return("Bob") print(getname(13)) def getpron(x): if x == 2: return("you") elif x == 3: return("I") elif x == 4: return("she") elif x == 5: return("he") return("it") print(getpron(5)) def getverb(x): if x == 17: return("am") elif x == 24: return("was") elif x == 32: return("love") else: return("ran over") print(getverb(27)) def makeit(x,y,z): return(getname(z) + getpron(y) + getverb(x)) print(makeit(17,3,7))

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 Note: def f_to_c(ftemp): print("The temp before conversion is” + str(ftemp)) return((ftemp - 32 )/ 1.8) print (“The temp after conversion is” + str(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

return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(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?

elif ((x > 0)and (x < 100)) : #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)) 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))

Quick function: Write a function that checks to see if a number is even or not. What TYPE does this return?

Boolean Values We now know functions can return: True or False ? Numbers (int, double) Strings True or False ? AKA Boolean Values Yes, No 1, 0 We can use True and False as if they are a type) E.g., return(True)

def ismultof3(x): if ((x%3) == 0): return(True) else: return(False) When python executes the following statement, what is the result? (x%3)==0 def ismultof3(x): return((x%3) == 0) def func2(x): if (ismultof3(x)): # Can we see why specifying what type # is returned from a function is critical?!? return(str(x) + " is a multiple of 3") return(str(x) + " is not a multiple of 3") Class1 stopped here Class 2 stopped here

Returning to Boolean Values: Quadratic Equation: x2 - 3x – 4 = 0 Is this true for 1? 2? 3? 4? Can you write a function that returns the answer to this question? Hint: the function needs to return a boolean value. What is the input? How do you check for the output? Class 3

Function to represent this: #Name: eqcheck #Calculation: Determines if input value (x) will solve #the problem: # x2 - 3x – 4 = 0 #Input: x: a number #Output: a boolean value def eqcheck(x): return (x**2 – 3*x – 4) == 0 What is returned? print(eqcheck(3)) print(eqcheck(4)) Class 1

Remember? def Squr(par1): return(par1 ** 2) def dbl(par2): return(par2 + par2) def Func4(p1,p2): return(dbl(Squr(p2)+ Squr(p2)+3)) print(Func4(2,4)) def Func5(p1): return(dbl(dbl(dbl(p1)))) print(Func5(4))

What gets printed out? def f(n): if (n == 0): return (" ") else: print(“blug ") return f(n-1) f(3)

What about? def f(x): if (x == 0): return x else: return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return (str(x)) return(str(x) + f2(x-1)) print(f2(4)) class 3

Recursion (one of 3 types of loops) Recursion is when a function is defined in terms of itself (it calls itself). Def: A recursive definition is one that defines something in terms of itself (that is, recursively) Recursion is, in essence, making a function happen again and again without our having to call it (convenient, huh?) It is one of 3 types of loops we will learn all do the same thing, just different syntax) #This is recursion def recurse(): return(recurse()) #This isn’t def nonrecurse(): return(“nope”) Class 2

Try: def f(x): return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): else: return(x + f3(x-2)) print(f3(4)) def f(x): return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return x else: return(x + f2(x+1)) print(f2(4)) class2

How about: def f(x): if x == 100: return(“none") else: if (x**2 - 3 *x - 4) == 0: print(str(x) + " solves the equation ") return(f(x+1)) print(f(-100))

Loop Essentials We now have the basics: Must formulate a problem in terms of itself. (Recursion: the function must call itself) Must include a condition for stopping the recursion (base case) Must make sure that we will always hit that stopping condition.

Sum numbers (1-5) def summing(x): If we start by calling the function with 1, when should we stop? if (x >= 5): # must return something that does not make the loop happen again!!!!! return(x) #why x? Assume the smallest case possible: Summing one number. No matter what the number is, if you are summing that number and that number only, you want to return that number. Alt: if we start summing 1-5 by calling the function with 5, when should we stop? if (x <= 1): return(x) Note: Sometimes we can have MORE THAN ONE stopping condition (you only have to make one of them happen)

Sum numbers (1-5) def summing(x): Stopping Condition? if (x >= 5): return(x) How do we make sure that we get to the stopping condition? Increase x every time we “loop” E.g., summing(x+1) Alternative: summing(x-1) If we do these two things, we will likely avoid an infinite loop

Sum numbers 1-5 (cont.) def summing(x): Stopping condition if (x >= 5): return (x) Progressing towards stopping condition: summing(x+1) Finally, we need to write our function: Pretend there are only 2 cases – the last case (step 1, above) and the case right before that. (e.g., summing 4-5) We want to return(x + summing(x+1)), right? From step 1 we know summing (x+1) returns 5 And we know x holds 4. So summing(4) returns 9 Now what if we summed from 3-5? Can we use what we just did?

Sum Numbers 1-5 (cont.) Put it all together: def summing(x): if (x >= 5): return(x) else: return(x + summing(x+1)) print(summing(1))

Try: Write a recursive function that creates a string of every other number starting at 1 and ending at 10 Write a recursive function that sums every other number between two integers (you can assume the second integer is greater than the first integer) Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y

Problem 1:Write a recursive function that prints out every other number starting at 1 and ending at 10 def g(x): if x == 10: return(str(x)) elif x > 10: return() else: return(str(x) + g(x+2)) print(g(1))

Problem 2: Write a recursive function that sums every other number between two integers def g(x,y): if x == y: return(x) elif x > y: return() else: return(x + g(x+2)) print(g(3,12))

Problem 3: Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y Same? def h(x,y,z): if x >=y: return(z) elif x%3 == 0: return (h(x + 1,y,z+1)) else: return(h(x+1,y,z)) print(h(3,28,0)) def h(x,y): if x >=y: return(0) elif x%3 == 0: return (1 + h(x + 1,y)) else: return(h(x+1,y)) print(h(3,28))

Try: def g(x): if (x == 0): return('r') elif (x%5==0): return(g(x-1)+'t') elif (x%3 == 0): return(g(x-1) + 'b') elif (x%2 == 0): return(g(x-1) + 'o') else: return(g(x-1)) print(g(5))

Random Numbers Used for Everything! To create a random number: Gaming (games of chance, unpredictable movements, unpredictable timing, etc. Generating noise in signals Random checking of data And the list goes on and on! To create a random number: from random import * #imports the random library, including all the functions to generate random numbers And then x=randrange(1,10) #x now holds a number between 1 and 9 (doesn’t include 10) Example: import turtle def f(x): if (x == 5): return("Done") else: x = randrange(0,10) print("the random number is " + str(x)) return(f(x)) print(f(10))