Python how to multiply results from input strings [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 months ago.
I'm a programming beginner trying to learn Python. I'm trying to complete the following exercise:
Write a program to prompt the user for hours and rate per hour to
compute gross pay.
Here's what I came up with:
hours = input("Enter number of hours worked\n")
rate = input("Enter pay rate per hour\n")
print(hours * rate)
Of course, I receive the error:
TypeError: can't multiply sequence by non-int of type 'str'
How can I tell Python that the results of the input should be regarded as integers rather than strings?

Any input from the input function is stored as string, you have to convert them both to integers before multiplying like this:
hours = input("Enter number of hours worked\n")
hours = int(hours)
rate = input("Enter pay rate per hour\n")
rate = int(rate)
print(hours * rate)

Of course you need to convert to appropriate type before multiplication, since input("") returns string of user input.
The conversion is as follows:
rate -> float
hours -> int
This is to make sure that you don't loose decimal points where user enter rate with decimals eg 2.2
So from your code you can add the following
hours = int(input("Enter number of hours worked\n"))
rate = float(input("Enter pay rate per hour\n"))
print(hours * rate) # int * float gives float

Problem solved:
hours = int(input("Enter number of hours worked\n"))
rate = int(input("Enter pay rate per hour\n"))
I figured the int function had to be placed in there somewhere.

Related

Make Python Print and Calculate Pay

Just my first question on SU.
I have my code underneath me, the final output needs to read "Pay: #"
Here is my error: TypeError: can't multiply sequence by non-int of type 'float' on line 3
hrs = input("Enter Hours:")
rate = 2.75
pay = rate * hrs
print ("Pay: (pay)")
What am I missing here?
You are trying to multiply string which is a sequence of characters with float value.
You need to convert string to either float or int.
hrs = int(input("Enter Hours:"))
rate = 2.75
pay = rate * hrs
print ("Pay: {}".format(pay))
If the rate value, rate was an integer then this would multiply string rate times and returns resultant string.
Example:
hrs = input("Enter Hours:") # if you input 5
rate = 3
pay = rate * hrs
print(pay) # prints 555

How can I find out the number of outputs in a loop?

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()

Calculating overtime using python

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.

python string formatting error in a definite loop

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))

Zero out a value

I'm trying to create a program that will allow me to enter a value in minutes and the program will output those minutes as the sum of days, hours and minutes between them.
For example if I input 10000 minutes I should get the output, "10000 minutes is 6 days, 22 hours and 40 minutes"). This is how much I have now:
min = int(input("Enter a whole number of minutes: "))
days = min/1440
remainday = min%1440
print (days)
I'm only having one problem asides from it being unfinished, if the user inputs a number of minutes under 1440 then i get a decimal answer for the number of days (which is expected) but if the number of minutes is not sufficient to make a day, then I want the it to say "0 days" not ".153 days". How would I zero out the value for days in such a case?
You are using Python 3 so the operator / is true division, not integer division.
You can either use floor division which is similar to Python 2's integer division:
days = min//1440
Or use divmod to get both with a single command:
days, remaindays = divmod(min,1440)
You can use floor division (using a double // instead of a single / when dividing), which rounds down to the nearest integer:
min = int(input("Enter a whole number of minutes: "))
# Example input: 1000
days = min // 1440
remainday = min%1440
print (days)
# Output:
# 0
You essentially want to round down the result of the division (quotient) to the nearest integer.
This can be done in many ways:
days = int(min/1440)
Or
days = min//1440 # // is the integer division in Python 3, while / is float division`
Or
days = math.floor(min/1440) # after importing "math" module, using "import math"

Categories

Resources