Q&A
Q: What’s the difference between print and return? I still don’t really get it
A:returnis a special operator that only shows up at the end of functions; it specifies what the output of a function should be.print()on the other hand is used whenever you want to display something to screen. [Will do an example in class b/c this is an important distinction.]
Q: Can you give a mini-example of how this would be used in a widely-applicable setting (i.e., an example in the coding world of when you would use a function like this to run a larger, more complex type of code)?
A: In programming any time you want to accomplish a task with code, writing a function is typically your go to. So, let’s consider an app that you need to login to use. You could have a functioncheck_for_email()that takes in a user’s email address and checks against the app’s database to see if that email has a login. Then, you could have a second functioncheck_password()that takes in a user’s username and password and checks if the username and password match. You could then have a functionlogin()that takes in a username and password as inputs. Inside that function it could runcheck_for-email()andcheck_password(). If both returnTruethen the user is allowed to login!
Q: How to easily decipher what a coding question is asking us to do? I believe I’m able to code but I think sometimes instructions are phrased weirdly or I don’t understand what the they’re asking at times.
A: This is a skill we’ll continue to discuss and practice. The best approach is deeply understanding each concept. So, for functions, understanding definition, parameters,returnstatements, etc. rather than just memorizing a specific example. This makes interpreting questions when you see something similar…but new a lot easier. But, this is a skill we’re still developing!
Q: I am confused about the difference between positional vs keyword arguments and default values
A: default values are specified on function definition. They are a value that the function will use by default. positional/keyword arguments are two different ways to specify the values for paramters on function execution.
Q: Are we able to use parenthesis for a math function within parameters?
A: I’m not totally sure I understand this question. But typically, if you want to carry out some operations (i.e. math), you’d want to do that inside the function, not in the parameters. Do follow up if this doesn’t answer!
Q: do you have to run the function in the same cell that you wrote it in (like the same cell in the notebook), or will it generalize to all cells and can be used anywhere?
A: Good question! Once you have defined it and executed that cell, a function can be used in any cell of the notebook (including the original function definition cell).
Q: when is it appropriate to put spaces and when is it not appropriate to put spaces? when in doubt should I just put a space
A: Typically, spaces around all operators. Only exception: no spaces around=for parameters/arguments.
Q: If it possible to post the questions student have or tend to not understand which we usally review at beginning of class, since it dosent update or show on our notes. it owuld be helful to just make sure those are reviwed.
A: The website is the easiest place to reference these! (Sometimes/typically they’ll be in your notes…but you’re right not always depending upon where we end class).
Q: Is there a way to see the code inside a function that is not yours?
A: Yes…but. Some code in python (i.e.print()) is actually written in C (another programming language), so reading the source code (code inside) is not straightforward. That said, if the source code is in python, putting two question marks after a function will display the source code, for example:
import random
random.randint??
Q: Is it all the time you put return after a function?
A: Almost all the time - anytime you want output from a function, you need areturnstatement. For our purposes, assume it should always be there.
Q: Why is the ouput sometimes called something different? does it always follow a similar process of creating a function? Is there a formula we could remember for writing them?
A: The variable followingreturnis the name of the variable whose value you want returned from the function. So, it could beoutputor another variable.
Q: does the definition/name of the function matter greatly? like will the function be changed if the name is slightly different than what it originally was?
A: It matters that the name you use for function definition matches the name you use for function execution. And, for class purposes, the function name has to match what we specify exactly…as the autograder is looking for that particular name.
Q: Will the functions we create on the midterm be a similar difficulty level to what we do in class?
A: Yes, but we will start writing more complicated functions as the course goes on. Typically functions on VQs, in class, and on labs are similar to midterm difficulty. The hardest functions on assignments go beyond what we’d expect on a midterm.
Course Announcements
Due:
CL5 due Fri
A1 due Sun
VQ6 due Mon
Notes:
Course Q&A - maybe get in habit of checking on website if not in notes?
Practice Exam will be available Tuesday evening (4/21; after we finish material covered on exam in class)
USE THIS
take it multiple times
Difference between return and print
returnkeyword for outputs of functions (always inside a functiondef) <- use this for function outputprint()simply displays the value to screen; most helpful for debugging
# do an example
# using a return - THIS IS HOW TO GET OUTPUT FROM A FUNCTION
def add_two_numbers(num1, num2):
out = num1 + num2
return out
add_two_numbers(5, 3)
8
# assign output from function to new variable
my_return_output = add_two_numbers(5, 3)
my_return_output
8
def add_two_numbers_print(num1, num2):
out = num1 + num2
print(out)
add_two_numbers_print(5, 3)
8
my_print_output = add_two_numbers_print(5, 3)
8
print(my_print_output)
None
Conditionals#
ifelifelse
value = 5
if value == True:
print('if statement executed')
elif value == False:
print('elif statement executed')
else:
print('else statement executed')
else statement executed
Conditionals#
speed_limit = 65
speed = 60
if speed > speed_limit:
ticket = True
elif speed == speed_limit:
ticket = 'warning'
else:
ticket = False
print(ticket)
False
Properties of conditionals#
All conditionals start with an
if, can have an optional and variable number ofelif’s and an optionalelsestatementConditionals can take any expression that can be evaluated as
TrueorFalse.At most one component (
if/elif/else) of a conditional will runThe order of conditional blocks is always
ifthenelif(s) thenelseCode following
if/elifis only ever executed if the condition is met
Activity: Conditionals I#
Complete the question in this Google Form (https://forms.gle/h7LZNmD4WcpveLam6) and then click submit.
bool(0)
False
bool('')
False
# SPACE TO TEST THINGS OUT
math = 4 < 5
if math:
print('True')
True
my_value = 4 < 2
if my_value:
print('True')
else:
print('False')
False
condition = False
if condition:
print("John")
elif not condition:
print("Paul")
elif not condition:
print("George")
else:
print("Ringo")
Paul
Functions + Conditionals#
Let’s define a more interesting function than what we did in the functions lecture. Here we are using conditionals within our function.
# Determine if a value is even or odd
def even_odd(value):
if value % 2 == 0:
out = "even"
else:
out = "odd"
return out
# Execute our function to check that
# it is working according to our expectations
even_odd(5)
'odd'
Code Style: Conditionals#
avoid single line statements
a single conditional (if + elif + else) has no additional line spaces between statements
Conditionals: Good Code Style#
value = 16
if value % 2 == 0:
out = "even"
else:
out = "odd"
Conditionals: Code Style to Avoid#
if value%2==0:out="even" # avoid statement on same line as conditional
# avoid blank line between if and else
else:out="odd" # don't forget about spacing around operators!
Activity: Conditionals II#
Complete the question in this Google Form (https://forms.gle/ebekT5weU4mgwsNq9) and then click submit.
There are three questions, the third of which requires coding:
In a previous lecture, we wrote a function
convert_to_f…but you’d probably want a function that could go in both directions.
Write a function
convert_temperaturethat will convert a temperature C->F and F->C, returning the converted temperature.
Note: A temperature in Celsius will be multiplied by 9/5 and then 32 will be added to that quantity to convert to Fahrenheit. A temperature in Fahrenheit would have 32 subtracted and then that quantity multiplied by 5/9.
## SPACE TO TEST THINGS OUT
if 1 + 1 == 2:
print("I did Math")
elif 1/0:
print("I broke Math")
else:
print("I didn't do math")
I did Math
# cannot divide by zero
# will error
1/0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[20], line 1
----> 1 1/0
ZeroDivisionError: division by zero
conditional = True
python = "great"
if conditional:
if python == "great":
print("Yay Python!")
else:
print("Oh no.")
else:
print("I'm here.")
Yay Python!
Write a function convert_temperature that will convert a temperature C->F and F->C, returning the converted temperature.
Note: A temperature in Celsius will be multiplied by 9/5 and then 32 will be added to that quantity to convert to Fahrenheit. A temperature in Fahrenheit would have 32 subtracted and then that quantity multiplied by 5/9.
def convert_temperature(temp, unit):
if unit == "C":
out_temp = temp * 9/5 + 32
elif unit == "F":
out_temp = (temp - 32) * 5/9
return out_temp
convert_temperature(20, "c")
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[23], line 1
----> 1 convert_temperature(20, "c")
Cell In[22], line 7, in convert_temperature(temp, unit)
4 elif unit == "F":
5 out_temp = (temp - 32) * 5/9
----> 7 return out_temp
UnboundLocalError: cannot access local variable 'out_temp' where it is not associated with a value
def convert_temperature(temp, unit):
# if unit is C -> F
if unit == "C": #or unit=="Celsius" or unit=="c":
out_temp = temp * 9/5 + 32
# elif unit is F -> C
elif unit == "F": #or unit=="Fahrenheit" or unit=="f":
out_temp = (temp - 32) * 5/9
else:
out_temp = "Please enter unit as either C or F"
return out_temp
convert_temperature(20, "C")
68.0
convert_temperature(68, "F")
20.0
convert_temperature(20, "Celsius")
'Please enter unit as either C or F'
Notes:
11A: discuss issues with solution posted; discuss if/elif/else decisions
2P: discuss issue with 2PM solution below; discuss if/elif/else decisions
## 11 AM
def convert_temperature(temp, unit):
if unit == "C" or unit == "c" or unit == "Celsius" or unit == "celsisus":
out_temp = temp * 9/5 + 32
elif unit == "F" or unit == "f" or unit == "Fahrenheit" or unit == "fahrenheit":
out_temp = (temp - 32) * 5/9
else:
out_temp = "Please use either unit as either C or F"
return out_temp
convert_temperature(20, "c")
68.0
# shortcomings
# not handling input units other than "C" or "F" -> else statement
# have your solution actually handle more than C/F (c/f) -> include additional conditionals for if/elif
# questions
# is it wrong if you just have an if and an else?
def convert_temperature(temp, unit):
if unit == "C":
out_temp = temp * 9/5 + 32
else:
out_temp = (temp - 32) * 5/9
return out_temp
convert_temperature(68, 'C')
154.4
2P: discuss issue with 2PM solution below; discuss if/elif/else decisions
## 2 PM
def convert_temperature(temp, unit):
if unit == "C" or unit == "c" or unit == "celsius" or unit=="Celsius": # you need another equal sign; = is for assignment; == checks for equality
out_temp = temp * 9/5 + 32
else:
out_temp = (temp - 32) * 5/9
return out_temp
# DISCUSS:
# when to use elif? when to use else?
# can you use else here (instead of elif)?
convert_temperature(20, "Shannon")
-6.666666666666667
(20 - 32) * 5/9
-6.666666666666667
convert_temperature(20, "F")
-6.666666666666667
Activity: Conditionals III#
Commplete the question in this Google Form (https://forms.gle/n45ykyKZa5RwMoCSA) and then click submit
Write a function called
calculate_tipthat uses thebill_amountandtip_percent, will return the tip and the total amount to pay
Now for the catch: we want it to calculate the tip correctly whether people enter a proportion (i.e.
.2to represent 20%) or a percent (i.e.20to represent 20%)…we’re going to assume that a value greater than zero but less than or equal to 1 is a proportion.
Test cases:
calculate_tip(100, .10)andcalculate_tip(100, 10)should both return the tip of 10.0 and a total of 110.0
Final note: two variables can be returned from a function if they are separated by a comma
## SPACE TO TEST THINGS OUT
# if type(tip_percent) == int
# elif type(tip_percent) == float
# if tip_percent <1 and tip_percent >0:
# if between 0 and 1
# elif above 1 and less than 100
# else: #below 0
def calculate_tip(bill_amount, tip_percent):
if tip_percent > 0 and tip_percent < 1 :
new_tip = tip_percent * bill_amount
elif tip_percent >= 1 and tip_percent <= 100:
new_tip = tip_percent/100 * bill_amount
new_bill = bill_amount + new_tip
return new_tip, new_bill
calculate_tip(100, 12.5)
(12.5, 112.5)
calculate_tip(100, 0.1)
(10.0, 110.0)
Summary#
if/elif/elseCode Style
Conditionals + Functions
Collections (sneak peak)#
ability to store more than one piece of information in a single variable
lists, dictionaries, tuples
# list
my_list = [1, 2, 3, 4]
# tuple
my_tuple = (1, 2, 3, 4)
# dictionary
my_dictionary = {'Shannon': 'mom',
'Josh': 'dad',
'Kayden': 'kid',
'Kaia': 'kid'}
Indexing#
access a value or set of values from of a collection
uses square brackets
[]
my_list[0]
Lists are mutable; tuples are not#
my_list[0] = 6
my_list
# THIS WILL ERROR
my_tuple[0] = 6
my_tuple