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)

Slides:



Advertisements
Similar presentations
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Advertisements

Introduction to Computing Science and Programming I
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.
Introduction to Python and programming Michael Ernst UW CSE 190p Summer 2012.
ECS 10 10/8. Outline Announcements Homework 2 questions Boolean expressions If/else statements State variables and avoiding sys.exit(…) Example: Coin.
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
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? 
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?
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.
Introduction to Python and programming Ruth Anderson UW CSE 140 Winter
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
Chapter 7 Problem Solving with Loops
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Input, Output and Variables GCSE Computer Science – Python.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
ENGINEERING 1D04 Tutorial 1. WELCOME! What we’re doing today Who am I How to do well What are computer programs Software Development Cycle Pseudo Code.
Chapter 2 Writing Simple Programs
Introduction to Decision Structures and Boolean Variables
Repetition Structures
Introduction to Python
Formatting Output.
Loops BIS1523 – Lecture 10.
Python: Control Structures
Introduction to Python and programming
Other things: functions
ECS10 10/10
CS 115 Lecture 8 Structured Programming; for loops
Topics The if Statement The if-else Statement Comparing Strings
While Loops in Python.
Variables, Printing and if-statements
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Adapted from slides by Marty Stepp and Stuart Reges
Topics The if Statement The if-else Statement Comparing Strings
Introduction to Python and programming
Conditions and Ifs BIS1523 – Lecture 8.
Introduction to Python and programming
Decision Structures, String Comparison, Nested Structures
TIPS: How to Be Successful
Logical assertions assertion: A statement that is either true or false. Examples: Java was created in The sky is purple. 23 is a prime number. 10.
Intro to Nested Looping
Topic 1: Problem Solving
The while Looping Structure
Module 4 Loops.
Adapted from slides by Marty Stepp and Stuart Reges
3. Decision Structures Rocky K. C. Chang 19 September 2018
Introduction to Python and programming
Introduction to Decision Structures and Boolean Variables
Conditional and iterative statements
Intro to Nested Looping
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Building Java Programs
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Flowcharts and Pseudo Code
Python Basics with Jupyter Notebook
More While Loops.
Making decisions with code
Strings: Strings? concatenate (join) + make multiple copies using *
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
The while Looping Structure
While Loops in Python.
Introduction to Python and programming
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Data Types and Expressions
Getting Started in Python
Presentation transcript:

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) + 2) print(g2(1)) 10

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

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): #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?

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)) 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 35000 or more and they’ve been employed for at least 2 years, they qualify. If they make 35000 or more, 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: return("You will qualify in " + str(round(2-yrs) ,2)+ " years.") if (yrs>=2): return("You need to make at least 35000 to qualify for a loan") 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)) Class 1

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.") if (yrs>=2): return("You need to make at least 35000 to qualify for a loan") 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)) Class 1

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 True/False (Boolean Values) are a TYPE!!! We can use True and False like other types (e.g., ints, strings) E.g., return(True)

George Boole (1815-1864) English mathematician First professor of mathematics at Queen's College, Cork in Ireland. Best known as the author of The Laws of Thought (1854) which contains Boolean algebra. Boolean logic lays the foundations for programming Boolean: True/False

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") print(func2(7)) Print(func2(9)) 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

Random Numbers Used all the time for so many things!!!! Python lets you generate random numbers within a range import the random number library from random import * generate a random number between 2 numbers: randrange(0,10)

Example: from random import * def guess(x): #what type does guess return? if (x == randrange(1,10)): return True else: return False print(guess(3)) #what might be printed here? Better version: def guess2(x): return(x==randrange(1,10))

What’s wrong with this function? (hint: none printed out when I ran it) from random import * def beloworabove(): if (randrange(-10,10) < 0): return("random number is below 0") elif (randrange(-10,10) == 0): return("random number is 0") elif (randrange(-10,10) > 0): return("random number is above 0") print(beloworabove())

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 function Then we can use them inside the function def f(x): #simple and silly example of using a variable y = 3 # y only exists within this function return(x + y)

Variables: def f(x): y=3 y=y+x # Do the right side first, then put # that value into the left side. return(y**2) f(5)

More examples: def calcvol(length,width,depth): area = length * width #area only exists inside this function vol = area * depth return(vol) def bankaccount(x,add): dollars = 2.57 print("Currently, you have " + str(dollars) + " in your bank account") if add == 1: dollars = dollars + x # evaluate right, then assign to left else: dollars = dollars - x return("you now have " + str(dollars) + " in your bank account") #again, function ends when the return statement is executed. print(bankaccount(0.10,1) print(bankaccount(1.0, 0)

Remember this? Better! from random import * def beloworabove2(): from random import * def beloworabove(): if (randrange(-10,10) < 0): return("random number is below 0") elif (randrange(-10,10) == 0): return("random number is 0") elif (randrange(-10,10) > 0): return("random number is above 0") print(beloworabove()) Better! from random import * def beloworabove2(): x = randrange(-10,10) if (x < 0): return("random number is below 0") elif (x == 0): return("random number is 0") elif (x > 0): return("random number is above 0") print(beloworabove2())

Variables: from random import * def f(x): y = randrange(0,10) if (x > 0): y = y + x # Do the right side first, then put # that value into the left side. return(y) elif (x < 0): y = y - x else: return y print(f(7)) print(f(-2))

Variables: def sqr(x): x = x*x return(x) print(sqr(3)) print(sqr(-2))

Variables from random import * def ag(k): x = randrange(1,10) if (k == 2): x = x +randrange(1,10) elif (k == 3): x = x + randrange(1,10)+randrange(1,10) elif (k == 4): x = x + randrange(1,10)+randrange(1,10)+randrange(1,10) x = x/k return x print(ag(3)) print(ag(4)) print(ag(2))

Variables from random import * def jackpot(): x = randrange(1,10) y = randrange(1,10) print("x is "+str(x)+", y is "+str(y)) return (x==y) print(jackpot())

Shortcuts >>> x = 4 >>> x +=2 #same as x = x + 2 >>> x 6 >>> x -=7 #same as x = x - 7 -1 >>> x *= 32 #same as x = x * 32 -32 >>> x /=8 #same as x = x/8 -4.0

Example: def f(p1,p2): if p1>p2: x = p1-p2 else: x = p2-p1 if (x%2) == 1: # x is now what value? x+=1 # Now what is x? x/=2 # and now what is x? return(x) print(f(7,2)) print(f(24,82))

Input from user: What if we want to ask the user to input something? We can use input! answer = input(“Is this your favorite class?”) Takes what you typed in and places it in the variable, answer. It’s always a string unless we convert it to another type if (answer == “yes”): return (“You get an A!”) else: return(“You fail.”)

Input The input function always returns a string type. def getage_1(): x = input(“How old are you?”) if x< 16: return(“You can’t drive”) else: return(“Get your license”) print(getage_1()) def getage_2(): x = input(“How old are you?”) x = int(x) if x < 16: return(“You can’t drive”) else: return(“Get your license”) print(getage_2()) The input function always returns a string type. what you type in in response to the question is always considered a string. If you want it to be an int, you must convert it.

Why should I use a variable here?: def f(): k = input("What is your favorite color?") if (k == 'blue'): return("You love harmony, are reliable, sensitive and always make an effort to think of others. You like to keep things clean and tidy and feel that stability is the most important aspect in life.") elif (k == 'red'): return(“you live life to the fullest and are tenacious and determined in their endeavors.") elif (k == 'green'): return("you are often affectionate, loyal and frank. Green lovers are also aware of what others think of them and consider their reputation very important. ") elif (k == 'yellow'): return("you enjoy learning and sharing your knowledge with others. Finding happiness comes easy to you and others would compare you to sunshine. ") elif (k == 'purple'): return("you are artistic and unique. You have a great respect for people but at times can be arrogant.") elif (k == 'brown'): return("you are a good friend and try your hardest to be reliable and dependable. Flashy objects are not something you desire; you just want a stable life.") print(f())

x = int(input("heads or tails? (1 or 0) ")) y = randrange(0,2) from random import * def f(): x = int(input("heads or tails? (1 or 0) ")) y = randrange(0,2) if x == y: return("You guessed right! You both guessed " + str(x)) else: return("You’re wrong. You guessed "+str(x)+" and computer generated "+str(y)) print(f())

While Loop def ThreeYearOld(): x = "" while (x != "Because."): x = input("But why?") return("Oh. Okay.") print(ThreeYearOld()) Look at this code: What must be true in order for the loop to start? This is the starting condition!! What will make the loop end? What must become false? This is the stopping condition!! Does something INSIDE the loop that changes so that eventually the loop will end?

Generic While Loops: While Loops: What value does this code return? def f(x): counter = 0 while counter < x: #counter<x is the condition that must be true for the loop to continue! # code can go here counter = counter + 1 return(counter) print(f(5)) While Loops: Continues while condition is true Must initialize to make condition true in while loops we stop when the while condition is false. Something inside the loop must change so that the condition becomes false eventually. What value does this code return?

What does this print? def f(x): counter = 0 while counter < x: print(counter) counter = counter + 1 return(counter) print(f(5))

What does this print? def f(x): counter = x while counter > 0: print(counter) counter = counter - 1 return(counter) print(f(5))

What does this print? def f(x): counter = 0 while counter < 30: print(counter) counter = counter + x return(counter) print(f(4))

What does this print? def f(x): total = 0 counter = 0 while counter < x: total = total + counter counter = counter + 1 return(total) print(f(6))

What does this do? def f(x): total = 0 counter = 0 while counter < x: total = total + x counter = counter + 1 return(total) print(f(6)) print(f(4)) print(f(5))

What does this print? def f(x): counter = 0 while counter < 2: x = x + “an” counter = counter + 1 x = x+”a” return(x) print(f(“a b”))

While Loops: loop must have a True/False condition while count >= 1: While loops starts when the condition is True It continues to loop while the condition is True It stops looping when the condition is False Something must change inside the loop that will eventually make the True/False condition False count = count -1

While loops Starting condition? What makes the loop stop? def f(total): while count >= 1: print(“bla”) count = count -1 return(total) print(f(0)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

While loops def f(total, count): while count >= 1: print(“glub”) count = count + 1 return(total) print(f(0, 4)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

While loops def f(total, count): while count != 0: print(“blug”) count = count - 2 return(total) print(f(0, 4)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

While loop rules: We must initialize values BEFORE entering the while loop count = 0 answer = “anything” We must make sure the while loop condition is initially true to enter the loop: while count < 5: while answer != “because” We must make sure that something inside the loop changes so that the while loop condition will become false at some point! count = count + 1 answer = input(“But why?”)

Differences (syntactic): We can initialize variables used by the while loop inside the function (BUT BEFORE THE WHILE LOOP!) def f(): x = 5 counter = 0 while counter < x: print(counter) counter = counter + 1 return(counter) print(f()) def f(x, counter): while counter < x: print(counter) counter = counter + 1 return(counter) print(f(5, 0))

What does this do? def w2(x,y): tot = 0 while (y > 0): tot += x y -= 1 return(tot) print(w2(3,5)) print(w2(4,6))

How about this? def f(x): while(x < 100): if (x**2 - 3 *x - 4) == 0: print(str(x) + " solves the equation ") x = x + 1 return(“done”) print(f(-100))