I am new at python, probably as new as it gets. I am working on a simple python code for mpg and refactoring. I am not sure exactly what I am doing wrong. Its giving me a error on line 65, "in goodbye print("your miles per gallon:", mpg) name error name 'mpg' is not defined. any help would be appreciated.
def main():
miles_driven = 0.0
gallons_of_gas_used = 0.0
mpg = 0.0
print_welcome()
print_encouragement()
goodbye()
# imput
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = 0.0
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = 0.0
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
mpg = 0.0
your_mpg = your_miles_driven / gas_used
return your_mpg
def goodbye():
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
main()
Your code has 2 problems.
the goodbye function needs to receive mpg as an argument
you need to do the inputs before calling goodbye(), and pass the function the mpg
the following lines of code should be before calling goodbye().
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
Your code should look like this:
def main():
print_welcome()
print_encouragement()
# input before goodbye()
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# after input calc the mpg
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
# and then call the goodbye function and pass mpg
goodbye(mpg)
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
your_mpg = your_miles_driven / gas_used
return your_mpg
# goodbye function also needs to receive mpg
def goodbye(mpg):
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional functions soon!")
if __name__ == '__main__':
main()
mpg is defined in your main function and is not passed to your goodbye function. If you add it as a parameter, it becomes available in that function with whatever value is passed as an argument:
def goodbye(mpg):
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
Now in your main function you can do:
mpg = your_mpg(miles_driven, gallons_of_gas_used)
goodbye(mpg)
and goodbye() will receive the value of mpg that was returned by your_mpg().
Related
Write a program that will ask the user for the cost of a meal, compute the tip for the meal (18%), compute the tax on the meal (8.25%), and then displays the cost of the meal, the tip amount for the meal, the tax on the meal, and the total of the meal which is a sum of the cost, tip, and tax amount
Here is my code:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip():
tip = get_cost()*.18
return tip
def compute_tax():
tax = get_cost()*.0825
return tax
def compute_grand_total():
total = get_cost() + compute_tip() + compute_tax()
return total
def display_total_cost():
meal1 = print('Cost:', format(get_cost(), '.2f'))
tip3 = print('Tip:', format(compute_tip(), '.2f'))
tax3 = print('Tax:', format(compute_tax(), '.2f'))
total2 = print('Total:', format(compute_grand_total(), '.2f'))
return meal1, tip3, tax3, total2
def main():
m, t, ta, to = display_total_cost()
print('Cost:' , format(m, '.2f'))
print('Tip:', format(t, '.2f'))
print('Tax:', format(ta, '.2f'))
print('Total:', format(to, '.2f'))
main()
Output on Python Shell:
Enter cost of meal: 19.95
Cost: 19.95
Enter cost of meal: 19.95
Tip: 3.59
Enter cost of meal: 19.95
Tax: 1.65
Enter cost of meal: 19.95
This may be a very simple fix but how can I fix this where it doesn't ask for meal again? I'm still starting out.
Call get_cost() once and assign it to a variable; then pass that as a parameter to the other functions.
def compute_tip(meal):
return meal * .18
def compute_tax(meal):
return meal * .0825
def display_total_cost():
meal = get_cost()
return meal, compute_tip(meal), compute_tax(meal), compute_grand_total(meal)
You are calling get_cost() over and over again internally and that's why you are unable to find where the problem is. See you call it only once in the display_total_cost function but you are calling some other functions like compute_tip,compute_tax and compute_grand_total where all of them are internally calling the get_cost() function and that's why the programme asks you for multiple inputs.
Now, as suggested by everyone else you can store the return value in a variable and then pass it to all the other functions as an argument.
You also have a trivial main function in your programme which does the same thing as the display_total_cost function.
meal1 = print('Cost:', format(get_cost(), '.2f')) this is not the correct syntax.You can not use print statement after the assignment operator i.e. = Even though it won't raise any errors but why would you write extra things when you could just do a print statement cause using a print statement with assignment operator won't assign the variable with a value.
You also have another trivial function compute_grand_total you need not call functions again and again just to calculate previously calculated values unless and until you have a memory bound and you can not store values.
Fix it the following way:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip(meal):
tip = meal*.18
return tip
def compute_tax(meal):
tax = meal*.0825
return tax
def display_total_cost():
meal = get_cost()
print('Cost:', format(get_cost(), '.2f'))
tip = compute_tip(meal)
print('Tip:', format(tip, '.2f'))
tax = compute_tax(meal)
print('Tax:', format(tax, '.2f'))
print('Total:', format(meal + tip + tax, '.2f'))
display_total_cost()
The input function of my code is repeating 3 times before going onto the next function. I have tried using while true and break and return None but none of that helps.
def welcome():
print("Welcome to the Interest Loan Calculator")
def inp():
loan = input("Enter loan amount: ")
rate = input("Enter interest rate: ")
return loan, rate
def conv():
loan, rate=inp()
if loan.endswith('K'):
multiplier = 1000
loan = loan[0:len(loan)-1]
elif loan.endswith('M'):
multiplier = 1000000
loan = loan[0:len(loan)-1]
return int(float(loan) * multiplier)
def calc():
loan = conv()
print (loan)
def close():
print ("close placeholder")
def main():
welcome()
inp()
conv()
calc()
close()
if __name__ == "__main__":
main()
When running the code it asks me to input both loan and rate 3 times before moving to the calc function.
If you don't want to call inp three times, then don't. You call it once directly from the main program; you call it a second time through the sequence main => conv => inp, and a third time through main => calc => conv => inp.
I think you need to draw out the call tree of your program, and then alter it to match the design you actually want.
I am new to python and I am not sure where I am wrong with my code
I could really use help.
# this program will get hourly rate, pay rate validate.
# and then will calculate the gross pay.
pay = [7.50, 18.26]
time = [0, 41]
def main():
getRate(pay)
getHours(time)
grossPay(pay, time)
def getRate(pay):
pay_rate = float(input('Enter your hourly pay rate: '))
while pay_rate < 7.50 or pay_rate > 18.25:
print('Pay rate must be between $7.50 and $18.25')
print('Enter a valid pay rate.')
pay_rate = float(input('Enter your hourly pay rate: '))
def getHours(time):
get_hours = float(input('Enter hours worked: '))
while get_hours < 0 or get_hours > 40:
print('Hours must be between 0 and 40!')
print('Enter a valid number of hours.')
get_hours = float(input('Enter hours worked: '))
def grossPay(pay_rate, get_hours):
result = pay_rate * get_hours
print(result)
main()
In your functions, you never return the results of your pay rate or your hours.
Change your main function to include saving the return values, like
def main():
rate = getRate(pay)
hours = getHours(time)
grossPay(rate, hours)
And in your getRate and getHours functions, include a return statement of your pay_rate and get_hours variables, like
def getRate(pay):
pay_rate = float(input('Enter your hourly pay rate: '))
while pay_rate < 7.50 or pay_rate > 18.25:
print('Pay rate must be between $7.50 and $18.25')
print('Enter a valid pay rate.')
pay_rate = float(input('Enter your hourly pay rate: '))
return pay_rate # As you want to get the value captured back to where the function was called from
The error is caused by this line from grossPay:
result = pay_rate * get_hours
because you are calling grossPay like
grossPay([7.50, 18.26], [0, 41])
Your functions aren't doing what you think they do... you are passing an argument, and generating a new value, but you are not returning that value entered by the user.
I think you must redefine
def grossPay(pay_rate, get_hours):
for hrs, rate in zip(pay_rate, get_hrs):
result = hrs * rate
print(result)
I'm in Grade 11 Computer Science at my highschool, and I'm just starting out in Python. I'm supposed to make a function called computepay that will ask the user their name, their wage, and their hours that week and automatically calculate the total, including any overtime and not error out when an incorrect input is included. I made different functions for all the inputs, but when I plug it all into my computepay function it tells me this:
TypeError: float() argument must be a string or a number
def mainloop(): #Creating a loop so it doesn't error out.
response = input('Make another calculation?[y/n]') #inputing loop
if response == 'n': #creating input for n
return
if response == 'y':
computepay()
else:
print("\n")
print ("Incorrect input. .")
mainloop()
def getname():
name = input ("What's your name?") #input of name
def getwage():
wage = input ("Hello there! How much money do you make per hour?") #input
try:
float(wage) #Making it so it does not error out when a float
except:
print ("Bad Input")
getwage()
def gethours():
hours = input ("Thanks, how many hours have you worked this week?")
try:
float(hours) #Making it so it does not error out when a float
except:
print("Bad Input")
gethours()
def computepay():
name = getname()
wage = getwage()
hours = gethours()
if float(hours) > float(40):
newhours = float(hours) - float (40) #figuring out the amount of overtime hours the person has worked
newwage = float (wage) * float (1.5) #figuring out overtime pay
overtimepay = float (newwage) * float (newhours) #calculating overtime total
regularpay = (float(40) * float (wage)) + overtimepay #calculating regular and overtime total.
print (name,",you'll have made $",round(regularpay,2),"this week.")
else:
total = float(wage) * float(hours)
print (name,",you'll have made $",round (total,2),"this week.")
mainloop() #creating the loop.
#-------------------------------------------------------------------------------
computepay()
None of these functions are returning anything
name = getname()
wage = getwage()
hours = gethours()
So they all end up being None
Try this
def getname():
return input("What's your name?") # input of name
def getwage():
wage = input("Hello there! How much money do you make per hour?") # input
return float(wage)
def gethours():
hours = input("Thanks, how many hours have you worked this week?")
return float(hours)
What the error message is telling you is that somewhere (on the line number reported in the part of the error message that you didn't show us) you are calling float and giving it an argument (i.e. an input) that is neither a number, nor a string.
Can you track down where this is happening?
Hint: Any Python function which doesn't return anything (with the return keyword) implicitly returns None (which is neither a string nor a number).
i am just writing a simple currency converter program, and the one problem that i am facing is that i can't think how to have the user change the content of the variable. Below is an the basic bit:
def D2Y():
def No():
newconv=float(input("What is the rate that you want to use: "))
amount=float(input("How much do you want to convert: $"))
conversionn=round(amount*newconv,2)
print("¥",conversionn)
return (rerun())
def Yes():
conrate2=float(97.7677)
amount=float(input("How much do you want to convert: $"))
conversion=round(amount*conrate2,2)
print("¥",conversion)
return (rerun())
def rerun():
rerun=int(input("Do you want to go again?\n1 - Yes\n2 - No\nChoice: "))
if rerun==1:
return (main())
else:
print("Thank you for converting")
conrate1=int(input("The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1\n1 - Yes\n2 - No\nDo you want to use this rate?: "))
if conrate1==1:
return (Yes())
else:
return (No())
I dont know how you do it. I dont mind if you get rid of the def functions.
Here's an approach that does away with the functions and allows you to modify the exchange rate:
rate = CONVERSION_RATE = 97.7677
while True:
print "The currency conversion rate for Yen to 1 US Dollar is ¥%.4f to $1" % rate
print 'Select an option:\n1)Modify Conversion Rate\n2)Convert a value to dollars\n0)Exit\n'
choice = int(raw_input('Choice: '))
if choice == 0:
print("Thank you for converting")
break
if choice == 1:
try:
rate = float(raw_input("What is the rate that you want to use: "))
except ValueError:
rate = CONVERSION_RATE
amount = float(raw_input("How much do you want to convert: $"))
print "¥", round(amount * rate,2)
print '\n\n'
In use, it looks like this:
The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1
Select an option:
1)Modify Conversion Rate
2)Convert a value to dollars
0)Exit
Choice: 2
How much do you want to convert: $1.00
¥ 97.77
...
Choice: 1
What is the rate that you want to use: 96.9000
How much do you want to convert: $1.00
¥ 96.9