global name 'getYearlyCost2' is not defined - python

I'm using python for the very first time and I am stuck on this stinking problem and cant for the life of me figure out why its not working. When I try and run my program I can get an answer for the yearly cost without the modification (even though its wrong and I dont know why) but not the yearly cost with the modification.
I've tried rewriting it in case I missed a colon/parenthesis/ect but that didnt work, I tried renaming it. And I tried taking it completely out (this is the only way I could get rid of that annoying error message)
payoff file
from mpg import *
def main():
driven,costg,costm,mpgbm,mpgam = getInfo(1,2,3,4,5)
print("The number of miles driven in a year is",driven)
print("The cost of gas is",costg)
print("The cost of the modification is",costm)
print("The MPG of the car before the modification is",mpgbm)
print("The MPG of the car afrer the modification is",mpgam)
costWithout = getYearlyCost(1,2)
print("Yearly cost without the modification:", costWithout)
costWith = getYearlyCost2()
print("Yearly cost with the modification:", costWith)
While I know there is an error (most likely a lot of errors) in this I cant see it. Could someone please point it out to me and help me fix it?
Also I added my mpg.py in case the error is in there and not the payoff file.
def getInfo(driven,costg,costm,mpgbm,mpgam):
driven = eval(input("enter number of miles driven per year: "))
costg = eval(input("enter cost of a gallon of gas: "))
costm = eval(input("enter the cost of modification: "))
mpgbm = eval(input("eneter MPG of the car before the modification: "))
mpgam = eval(input("enter MPG of the car after the modification: "))
return driven,costg,costm,mpgbm,mpgam
def getYearlyCost(driven,costg):
getYearlyCost = (driven / costg*12)
def getYealyCost2(driven,costm):
getYearlyCost2 = (driven / costm*12)
return getYearlyCost,getYearlyCost2
def gallons(x,y,z,x2,y2,z2):
x = (driven/mpgbm) # x= how many gallons are used in a year
y = costg
z = (x*y) # z = how much money is spent on gas in year
print("money spent on gas in year ",z)
x2 = (driven/mpgam) # x2 = how much money is spent with mod.
z2 = (x2*y)
y2 = (costm + z2)
1,1 Top

Here's your immediate problem:
costWith = getYearlyCost2()
The function you're trying to call is named getYealyCost2() (no "r").
There are other problems that you'll find as soon as you fix that, such as no return statement in getYearlyCost() and trying to return the function getYearlyCost() in getYearlyCost2() and calling getYearlyCost2() without any arguments.
On top of that, import * is frowned upon, and then there's the use of eval()... but that'll do for starters.

Related

'NoneType' object has no attribute 'format' python string

I wrote a program in python to find compound interest (more like copied). This program was written in python 2 and I am having a problem on the last line .format(years).
I need to know what I can do with this code, and how to write it properly in Python 3. Also with the {} part in the last line. Should I change it to %s? The error says:
"AttributeError: 'NoneType' object has no attribute 'format'".
My code looks like this :
# Estimated yearly interest
print ("How many years will you be saving ? ")
years = int(input("Enter the number of years : "))
print("How much money is currently in your account ? ")
principal = float(input("Enter current amount in account : "))
print("How much money do you plan on investing monthly ? ")
monthly_invest = float(input("Monthly invest : "))
print("What do you estimate the interest of this yearly investment would be ? ")
interest = (float(input("Enter the interest in decimal numbers (10% = 0.1) : ")))
print(' ')
monthly_invest = monthly_invest * 12
final_amount = 0
for i in range(0, years ):
if final_amount == 0:
final_amount = principal
final_amount = (final_amount + monthly_invest) * (1 + interest)
print("This is how much money you will have after {} years: ").format(years) + str(final_amount)
I find it a bit of a shame that no one recommended f-strings. There are only available since Python 3.6 but they are quite powerful, easy to use and the recommended string formatting option in PEP 498 (unless I'm mistaken).
If you want to get serious about python and work with other people I really recommend reading up on best practices, in this case, f-strings.
Solution using f-strings:
print(f"This is how much money you will have after {years} years: {final_amount}")
Change
print("This is how much money you will have after {} years: ").format(years) + str(final_amount)
to
print("This is how much money you will have after {} years: ".format(years)) + str(final_amount)
format() is a method of the string class. You're using it on the print() function which is of NoneType, hence the error.
You can do a normal string concatenation like this :
Print("This is how much money you will have after " + format(years) + " years: " +str(final_amount)
Or if you wish to keep the same format you can do this
print("This is how much money you will have after {} years: ".format(years) + str(final_amount))
A very basic solution would be to change the last line to:
print("This is how much money you will have after {} years:".format(years), str(round(final_amount,2)))
That will do the trick for you
You could also use Numpy's financial functions
For $1000 invested monthly for 10 years at annual rate of 4%:
>>> import numpy as np
>>> np.fv(.04/12, 10*12, -1000, 0)
147249.8047254786
With an initial principal of $100,000:
>>> np.fv(.04/12, 10*12, -1000, -100000)
296333.07296730485

How do I fix this TypeError in Python concerning non-int and floats?

I'm working with Python 3 on Visual Studio Code and the project I'm working on is to calculate the user's lunar weight after receiving their terrestrial weight, then output how their weight changes overtime given an increase and a period of time.
This is the error message I've received multiple times, no matter how many times I've re-code:
TypeError: can't multiply sequence by non-int of type 'float'
This specifically happens whenever I use the input() and/or sys.stdin.readline() functions, but all of the pertaining variables are integers or floats, whether or not I try to convert them to floats by using the float() function around my inputs.
Here is my code:
# this programs converts your terra weight to your lunar weight, then it takes increase over a period of time
# error whether I use float() or not
terraWeight = float(input("Terra Weight: "))
ask = input("Is this in LBS or KG? ")
# converts pounds to kilograms
# 2.204... is used to convert lbs to kgs
if ask == "lbs" or "LBS":
initial = terraWeight / 2.2046223302272
# didn't need this, but assignment error popped up
x = 0
# or replace input() with sys.stdin.readline()
increase = input("Increase: ")
period = input("Period: ")
# gets lunar weight over time
def lunarWeight():
global increase
global period
global x
global initial
print("Earth Weight = %s kgs." % terraWeight)
year = 0
lunarWeight = initial * 0.165
print("Moon Weight = %s kgs. \n" % lunarWeight)
postIncrease = lunarWeight * increase
for x in range(0, period):
year += 1
lunarWeight += postIncrease
print("Year %s = %s kgs." % (year, lunarWeight))
lunarWeight()
The terminal directs to the this section of my code:
postIncrease = lunarWeight * increase
Which is on line 28. I'm not sure what the problem is, and I tried debugging but I still get the same error messages. I saw other posts with the same problem but they had problems using lists, which I'm pretty sure I'm not using. Any advice please?
Screenshot
I think you should write this lines as:
increase = float(input("Increase: "))
period = int(input("Period: "))
period is used in range() so it should be integer

Why is my function not getting called properly?

I'm writing a program that will greet somebody (given name) and then ask them how many hours they worked and how much their hourly pay is. The program runs but is not spitting back the correct math. I'm getting this for my answer... you earned<function wage at 0x00EA9540>
I have already tried calling payment but not getting an answer with that either.
def greet(greeting):
name = input("Hi, whats your name?")
return greeting + name
print(greet ("Hey "))
hourly = input("How much is your hourly wage?")
hours = input("How many hours did you work this week?")
def wage(hourly, hours):
if hours > 40:
payment = 40 * hourly
payment = payment + hourly * (hours-40) * 1.5
return payment
else:
return hours * hourly
print("you earned" + str(wage))
You missed the parameters to the wage function.
in your case, it just prints the memory address of the function wage...
you need to change the print call with the correct parameters to the wage function:
print("you earned" + str(wage(hourly, hours)))
You need to call the wage function with the parameters:
print("you earned" + str(wage(hourly, hours)))
Otherwise you are simply printing the string representation of the wage function object, and that doesn't really make much sense.

Python - Passing variables through functions

I am about a week into Python. I have looked at various other questions regarding this, and have grown fairly frustrated that my attempts to implement those suggestions are falling flat.
I have tried a few means of passing variables through, based on things I have read. For example (this isn't necessarily representative of a coherent attempt... I have tried many variations and have had to walk back to get code worth posting):
def verify_nums():
globhours = hours
globrate = rate
try:
globhours = float(globhours)
globrate = float(globrate)
return globhours,globrate
except:
print("You must provide numbers")
def calc():
globhours = globhours
globrate = globrate
if globhours > 40:
base = 40 * globrate
ot = (globhours - 40) * (globrate * 1.5)
pay = base + ot
print(pay)
else:
pay = globrate * globhours
print(pay)
hours = input("Enter hours worked: ")
rate = input("Enter hourly rate: ")
verify_nums()
calc()
I am supremely confused on how to transfer the hours and rate variables over to the calc() function.
I eventually figured out I could just merge these into one function...
def paycalc(hours,rate):
etc.
etc.
hours = input("Enter hours: ")
hours = input("Enter hours: ")
paycalc(hours,rate)
But for the sake of learning, I really want to get this global/local thing figured out.
Thanks for the help!
You seem to be trying to get Python to guess which functions are supposed to be global and which local based on their names. Python doesn't do that. If you assign to a variable in a function, and you want that assignment to be global, you need a global statement at the top of the function:
def verify_nums():
global globhours
global blograte
globhours = hours
globrate = rate
# ...
Also, globhours = globhours doesn't do anything useful—and, in fact, it causes a problem. If you global globhours in that function as well, the statement is meaningless. Without that, you're creating a local variable, and assigning it… the value of that local variable that doesn't exist yet.
Anyway, if you add the right global declarations to all of your functions, they will work, but it won't be a great design.
You really don't need any global variables here. If you think about values rather than variables, everything gets a lot easier.
Your verify_nums function needs to work on two values. So just pass those values in as parameters. And it needs to return two values—that's easy, you already did that part.
Now the caller has to store those two values that it returned, so it can pass them to the calc function. Which can also take two values as parameters.
Putting that all together:
def verify_nums(hours, rate):
try:
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
except:
print("You must provide numbers")
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
calc(hours, rate)
One problem left: what happens if there's an error with the user's input? Inside verify_nums, you handle the error with an except:, then you print a message and do nothing. That means you return None. So, when the caller tries to do hours, rate = None, it's going to get an error, which you're not handling. And you can't just carry on without values. What can you do?
More generally "return a pair of numbers, or return None" is a confusing contract for a function to fulfill. How do you use that function? With a whole lot of ugly type-checking. But "return a pair of numbers, or raise an exception" is a perfectly good contract. How do you use that function? With a simple try.
That's why it's better to put the exception handling in exactly the right place where you can deal with it. You want to skip calling calc if there's an error, so the except has to be where you call calc.
def verify_nums(hours, rate):
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
try:
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
except ValueError:
print("You must provide numbers")
else:
calc(hours, rate)
Another improvement you might want to consider: Have calc return the pay, instead of printing it, and make the caller print the value it returns.

Working with commas in output

I'm in an intro programming class and am lost. We've had several labs that required knowledge that we haven't been taught but I've managed to find out what I need on google (as nobody responds to the class message board) but this one has me pretty frustrated. I'll include a pastebin link here: https://pastebin.com/6JBD6NNA
`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))
time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))
rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))
interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`
So I need the output of the dollar amounts to have a comma ($27,500.00) but I have no idea how to do this. I've seen a couple of solutions on this site and others but I can't get them to work. PLEASE can someone help me?
In Python 2.7 or above, you can use
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
This is documented in PEP 378.
Source: Python Add Comma Into Number String
Here is a working example:
principal = float(input('Enter the Principal Value of your investment: $'))
time = int(input('\nEnter the Time(in years) you plan to save your investment: '))
rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))
interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
Your last line should be:
print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

Categories