I'm trying to do a challenge to practice. I'm trying to use an input to decide how much you would pay on a loan. Really basic stuff - but when I print I'm getting whatever was answered in the input repeating over and over again and I can't figure out where I'm going wrong. The code I'm trying to run is:
# $200 a month at 1.7% interest a year. Automate total based on months using user input.
months_given = input("How many months? ")
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")
I've tried using for/while loops but I'm not proficient with those yet and am still trying to understand how they work exactly.
You need to parse your input first then use it.
when you use input it return str.
in this total = int(months_given * monthly_total) line. months_given is str and when you use * operator and second operand is an int, str value repeated.
correct:
months_given = input("How many months? ")
months_given = int(months_given) # <-- here
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")
Related
I have posted this on a different site, but haven't received an answer there...so posting here to get an answer that will help me understand what is going on. My original post is below:
So, I did my own code for this before going back and viewing the video of the instructor walking through this exercise.
My code:
(01) hours = input('How many hours did you work?')
(02) rate = input('How much do you make per hour?')
(03) if float(hours) <= 40:
(04) strhrs = hours # strhrs = straight-time hours
(05) else:
(06) reghrs = 40
(07) othrs = float(hours)-40 # othrs = over-time hours
(08) strhrs = 0
(09) if strhrs != 0:
(10) pay = float(strhrs)*float(rate)
(11) else:
(12) regpay = float(reghrs)*float(rate)
(13) otpay = (float(rate)*1.5)*float(othrs)
(14) pay = regpay+otpay
(15) print(pay)
Then, I went back and watch the video covering this exercise. Obviously our codes are going to be a little different. Here is what the instructor coded:
Instructor's code:
(01) sh = input("Enter Hours: ")
(02) sr = input("Enter Rate: ")
(03) fh = float(sh)
(04) fr = float(sr)
(05)
(06) if fh > 40 :
(07) reg = fr * fh
(08) otp = (fh-40.0)*(fr*0.5)
(09) xp = reg + otp
(10) else:
(11) xp = hours * rate
(12)
(13) print("Pay:",xp)
My question is, with the "otpay" (line 13 of my code) calculating the rate1.5, I'm getting the same result as "otp" (line 8 in the instructor's code) that calculates fr0.5.
What is the difference in how Python is handling the two pieces of code (rate * 1.5 VS float rate * 0.5)?
If I put in "1.5" in the instructor's code, the result is complete different (it calculates to 2.5 times the normal rate of pay instead of 1.5 times the normal rate of pay). I'm not seeing what the difference in syntax is that would cause this to happen.
First, a comment on your code: What's the difference between straight-time hours and regular hours? There is none. You could simplify your code by not making that distinction. Also, all those float casts are unnecessary AFAICT.
Like this (untested)
hours = input('How many hours did you work?')
rate = input('How much do you make per hour?')
if hours <= 40:
reghrs = hours # reghrs = regular hours
othrs = 0 # othrs = over-time hours
else:
reghrs = 40
othrs = hours-40
regpay = reghrs*rate
otpay = (rate*1.5)*othrs
pay = regpay+otpay
print(pay)
To answer your question: You're just using a different way to come to the same result. You're computing payment for the first 40 hours (regpay) + payment for the overtime time (otpay). Your instructor is computing regular payment for the time worked (reg) + additional payment for overtime (otp).
Btw: Please tell your instructor to use better variable names.
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
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
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.
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))