Having some trouble grasping why this "quick math" formula I was taught in high school does not seem to work correctly.
The premise is to take your hourly salary, double it and add three Zeros, the result will roughly equate to your yearly salary if you work full time 50 weeks out of the year.
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
mult = money * 2
result = mult + str(000)
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result
Result:
my result looks something like this: "you make roughly $10100 per year, working full-time for 50 weeks out of the year"
I must be making a mistake in my expression...Simply put, I just do not know
You got all the types wrong.
raw_input acquires a string, so money is acquired as such. Thus, when you do mult=money*2 you are not doubling a number, but a string; writing money*2 thus has the effect of creating a string that is the concatenation of two copies of the string you provided. If you enter 10, mult will be '1010'.
Also, in str(000) 000 is an integer, so it's actually a plain 0; str(000) thus results in '0', which is concatenated to your doubled-string. 1010 concatenated with '0' => 10100.
What you actually want is
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
By the way, adding zeroes and the like is fine for humans, but since we are dealing with a computer you can just multiply by 2000:
result = 2000*int(raw_input("How much money do you earn per hour?"))
You're trying to do math with a string. Convert it into an integer first:
money = int(raw_input("How much money do you earn per hour?"))
and multiply instead of trying to add a string to the end
result = money * 2000
Though if you really wanted to, you could convert the integer back to a string to add 3 zeros to the end:
mult = money * 2
strmult = str(mult)
result = strmult + '000'
The raw_input() function returns a string.
When you multiply money by a number, instead of multiplying the integer value, you are multiplying the string value. This results in the variable's new value being a multiple of the string, or the string repeated multiple times. I would suggest using the money=int(money) function on money to turn it into an integer, or better yet money=float(money) to get a floating-point number.
try this
money=int(input('how much you make an hour'))
final_yearly=money*2000
print(final_yearly)
You do realize the following would give you the desired answer, right?
#Math Work
mult = money * 2000
First, money is a string, when you read user input. So when the user inputs 10, you get '10'.
So when you do money*2, you don't get the expected 20. Rather, you get '10'*2, which is '10' concatenated twice, i/e/ '1010'.
Next, 000 is an int that evaluates to 0, the str of which is '0'. What you wanted to add is '000'
I would go about your task this way:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
Alternatively, you could do this as well:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
result = money*2000 # because adding three 0s is the same as multiplying by 1000
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
result = str(int(money)*2) + '000'
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result
Related
I have already written the program but when I run it I am getting shorted by one penny. (The problem is at the very bottom)
My instructor said it was fine because we haven't learned what to add to the string (?) to prevent that from happening, but said we could try and find out what to add if we wanted to.
Here's the the problem:
price=float(input("What is the price of the item?"))
tax=round(price*0.0725,2)
grandTotal=price+tax
tendered=float(input("How much money did customer give you?"))
print(format("The price of the item is $","26"), format(price,"6.2f"))
print(format("The tax on the item is","26"), format(tax, "6.2f"))
print(format("The total cost is","26"), format(grandTotal, "6.2f"))
print(format("You tendered","26"), format(tendered, "6.2f"))
change=tendered-grandTotal
print(format("Your change is","26"), format(change, "6.2f"))
Calculating the breakdown of change
penny=int(change*100) #transform change into pennies
dollars=penny//100 #how many dollars are there
pennyleft= penny%100 #remainder operator to find how many pennies are left
quarters= pennyleft//25 #number of quarters
pennyleft=pennyleft%25 #remainder operator to find how many pennies are left
dimes=pennyleft//10 #number of dimes
pennyleft=pennyleft%10
nickels=pennyleft//5 #number of nickels
pennyleft=pennyleft%5
pennies=pennyleft//1 #number of pennies
pennyleft=pennyleft%1
print("Your change is:")
print( format(dollars, "5"), "dollar bills,")
print( format(quarters, "5"), "quarters,")
print( format(dimes, "5"), "dimes,")
print( format(nickels, "5"), "nickels, and")
print( format(pennies, "5"), "pennies.")
And this is the output;
What is the price of the item?5.00
You owe a total of $ 5.36
How much money did customer give you?10.00
The price of the item is $ 5.00
The tax on the item is 0.36
The total cost is 5.36
You tendered 10.00
Your change is 4.64
Your change is:
4 dollar bills,
2 quarters,
1 dimes,
0 nickels, and
3 pennies.
So my issue is that the 3 pennies should actually be 4. Any suggestions on how to fix this?
Thank you!
You are working with floating point numbers, and as such the result may be just a bit more or less than you'd expect. Not all floating point numbers can be stored exactly in a computer. It may sound suprising but it's really not that different from the usual decimal system. After all, you cannot "store" 1/3 in a decimal number either! It will be 0.3333333... (an infinite amount of 3s omitted for clarity and lack of storage space).
If you test the values you get by printing out more decimals, you will find that this line
print(format("Your change is","26"), format(change, "6.20f"))
shows
Your change is 4.63999999999999968026
and, since int(x) always rounds down (more specifically, it "truncates towards zero" (documentation)), the next line
penny=int(change*100)
only cuts off the excess decimals so you end up with 463. After this, the number is converted to an integer and so no further floating point mishaps occur – but it's too late.
To get the proper calculation, all you have to do is add another round:
penny=int(round(change*100)) #transform change into pennies
and this will reimburse that lost penny.
I am a beginner at python and I'm struggling with one of my (simple) college assignments. I have been given the following instructions:
A bank is offering a savings account where a yearly fee is charged. Write
a program that lets the user enter
An initial investment.
The yearly interest rate in percent.
The yearly fee.
the program should then calculate the time it takes
for the investment to double. The interest is added on once per year.
An example run of the program:
Enter the investment: 1000
Enter the interest rate: 10
Enter the fee: 10
The investment doubles after 7 years.
I have formulated the following code but am receiving an error message with regards to t. I would really appreciate if I could get some help, thanks!:
t=0
p=float(input("Enter the investment:"))
a=float(input("Enter the interest rate:"))
m=float(input("Enter the fee:"))
i=(float(a/100))
f=p
while f<=(2*p):
f=(float(f*((1+i)**t)-m)
t=t+1
print("The investment doubles after",t,"years")
I tried to write this in a way that was very easy to follow and understand. I edited it with comments to explain what is happening line by line. I would recommend using more descriptive variables. t/p/a/m/f may make a lot of sense to you, but going back to this program 6 months from now, you may have issues trying to understand what you were trying to accomplish. NOTE You should use input instead of raw_input in my example if using Python 3+. I use 2.7 so I use raw_input.
#first we define our main function
def main():
#investment is a variable equal to user input. it is converted to a float so that the user may enter numbers with decimal places for cents
investment = float(raw_input("Starting Investment: "))
#interest is the variable for interest rate. it is entered as a percentage so 5.5 would equate to 5.5%
interest = float(raw_input("Interest Rate as %, ex: 5.5 "))
#annual_fee is a variable that will hold the value for the annual fee.
annual_fee = float(raw_input("Annual Fee: "))
#years is a variable that we will use with a while loop, adding 1 to each year (but we wait until within the loop to do this)
years = 1
#we use a while loop as opposed to a for loop because we do not know how many times we will have to iterate through this loop to achieve a result. while true is always true, so this segment is going to run without conditions
while True:
#this is a variable that holds the value of our total money per year, this is equal to the initial investment + investment * interest percentage - our annual fee per year
#I actually had to try a few different things to get this to work, a regular expression may have been more suited to achieve an interest % that would be easier to work with. do some research on regular expressions in python as you will sooner or later need it.
total_per_year = investment + (years * (investment * (interest / 100))) - (annual_fee * years)
#now we start adding 1 to our years variable, since this is a while loop, this will recalculate the value of total_per_year variable
years += 1
#the conditional statement for when our total_per_year becomes equal to double our initial investment
if total_per_year >= 2 * investment:
#print years value (at time condition is met, so it will be 5 if it takes 5 years) and the string ' Years to Double Investment'
print years,' Years to Double Investment'
#prints 'You will have $' string and then the value our variable total_per_year
print 'You will have $', total_per_year
#this will break our while loop so that it does not run endlessly
break
#here is error handling for if the fee is larger than investment + interest
if (years * annual_fee) >= (years * (investment * (interest / 100))):
print('Annual Fee Exceeds Interest - Losing Money')
break
#initial call of our main function/begins loop
main()
I'm writing a simple program where a person can go on a trip, but the trip has to last 3 days minimum. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function hotel_cost(days) to 3
In it's most basic form, my function is:
def hotel_cost(days):
# hotel costs 140$ per day
return 140 * int(days)
And the above obviously works, but I want to change it so that it does not accept less than 3.
I'm experimenting with while and a boolean but it gives me None, and I've also faced accidental infinite recursion. Sorry if this question is too basic, it's my first one. I tried searching but to no avail.
Your can condense asking the user for the number of days, and giving them there price in in one function.
def ask_num_hotel_days():
i = int(input("Enter nuber of days: "))
while(i < 3):
print(str(i) + " is not a valid number of days")
i = int(input("Enter nuber of days: "))
return 140 * i
From my understanding of the question, you can do this:
def hotel_cost(days):
if int(days) >= 3:
return 140 * int(days)
else:
return False
And then you can do:
while not hotel_cost(days):
print("How many days are you staying?")
days = input()
Once it gets out of the while, the days amount will be valid, as well as the cost.
EDIT :
I wrote the code inside the while loop, to be more clear about what I suggested.
I hope it helps.
Cheers.
Hi I am python beginner!
Here is the questions I am having problem with!
Question:
Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
My answer was below but can't get 498.75, and I am not too sure where it went wrong.
Please help :)
hrs = raw_input('Enter hours ')
h= float(hrs) #why use float?
rate = float(10.5)
if h <= 40:
pay = h*rate
elif h > 40:
pay = ((h-40)*rate*1.5)+rate*40
print "Your pay is %d" %pay
Your code is correct, but you are using %d to print the value of variable pay, which converts it back to int and the decimal part is ignored.
So try using %s or %f or %.2f.
Your calculation is correct, you just need to format the output correctly. %d is for integers so changing to %f which is used for floats will do the trick:
print "Your pay is %f" %pay
With above change you'll get following output:
Your pay is 498.750000
You can find the full list of different format specifiers from Python docs.
When you print the pay of the user, you use %d to print the actual pay. To display floating point numbers (such as 498.75), you have to use %f (or more precisely, %.2f since you can't pay someone less than 1 cent).
So this would be the correct way, that wields 498.75 :
hrs = raw_input('Enter hours ')
h= float(hrs) #why use float?
rate = float(10.5)
if h <= 40:
pay = h*rate
elif h > 40:
pay = ((h-40)*rate*1.5)+rate*40
print "Your pay is %.2f" %pay
You can find more informations regarding string formatting here
Also, regarding the h= float(hrs) #why use float? :
by default, raw_input() returns a string, you have to use float() to parse this string to a floating point number, and to use it in your computation later on.
Hope it'll be helpful.
def main():
#Get amount of principal, apr, and # of years from user
princ = eval(input("Please enter the amount of principal in dollars "))
apr = eval(input("Please enter the annual interest rate percentage "))
years = eval(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0:5d} {0:5d}'.format(years, princ))
I'm trying to print the years and the principal value in a table, but when I print all that comes out is two columns of 10.
So you have several problems. The first problem is a display issue.
Your output statement print('{0:5d} {0:5d}'.format(years, princ)) has several issues.
printing years instead of i, so it's always the same value instead of incrementing
the 0 in the format statement{0:5d} means the 0'th element out of the following values, so you're actually printing years twice, the second one should be 1 instead of 0
you're using d to print what should be a floating point value, d is for printing integers, you should be using something along the lines of {1:.2f} which means "print this number with 2 decimal places
Once you've corrected those you'll still see incorrect answers because of a more subtle problem. You're performing division with integer values rather than floating point numbers, this means that any decimal remainders are truncated, so apr / 100 will evaluate to 0 for any reasonable apr.
You can fix this problem by correcting your input. (As a side note, running eval on user input is usually an incredibly dangerous idea, since it will execute any code that is entered.) Instead of eval, use float and int to specify what types of values the input should be converted to.
The following is corrected code which implements the above fixes.
#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0} {1:.2f}'.format(i, princ))