Parameters: Enable getting data into functions
Return values: Enable getting data out of functions - think of it as the result of a function
Let's think about examples from functions we've called:
name = input("What is your name? ")
name_length = len(name)
print(name,"has",name_length,"letters")
input() returns a string (whatever the user typed) and we saved that result to name
len() returns an integer (the length of the string name) and we saved that result to name_length
print() doesn't return anything - we never see print on the right side of an =
To return a value from a function you've defined, put the return statement somewherer in your function
returndef f_to_c(fahrenheit_temp):
celsius_temp = (fahrenheit_temp-32)*(5/9)
return celsius_temp
f_reading = float(input("Enter fahrenheit reading: "))
c_temp = f_to_c(f_reading)
print(c_temp)
Because f_to_c() returns something, we can save its result to c_temp
Note that the return statement will cause the function to end - even if it is in the middle of the function, so you usually find it at the end of a function.
print("100F is",f_to_c(100),"in Celsius.")
kelvin_reading = 273.15 + f_to_c(100)
print("In Kelvin, it is",kelvin_reading)
Returning values gives you more flexibility in how the function can be used.
Consider the pay calculator. We might want to allow a user to interact with it to check their pay; or, we might read employee information from a file so that we can process all their paychecks.
import csv
def calculate_pay(wage,hours):
if hours <= 40:
pay = wage*hours
else:
overtime_hours = hours-40
pay = (wage*40) + (wage*1.5*overtime_hours)
return pay
def user_pay_calculator():
hourly_wage = float(input("Enter your hourly wage: "))
num_hours = float(input("Enter your number of hours worked: "))
print("Your total pay is",calculate_pay(hourly_wage,num_hours))
def process_payroll(employee_hours_logged_filename):
with open(employee_hours_logged_filename) as hours_log_file:
employees_log = csv.reader(hours_log_file)
employees_log = list(employees_log)
counter = 0
while counter < len(employees_log):
print(employees_log[counter][0],":",calculate_pay(float(employees_log[counter][1]),float(employees_log[counter][2])))
counter += 1
#user_pay_calculator()
process_payroll("emp_hours_log_2021_June20-26.csv")