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
Related
This is probably a really easy question but it's 2am and my brain is fried trying to figure out why they won't multiply together:
Prate2 = float(input("Please input the hourly rate of the plumber you would like to calculate: \n"))
Pfee2 = float(input("Please input the callout fee of the plumber you would like to calculate: \n"))
multiply = float(amountHours * Prate2)
total = (multiply) + (Pfee2)
print("The total cost of service:" ,(multiply) , "With a callout fee of",(Pfee2) , "to give a total of:", total)
It gives me an error message of "TypeError: can't multiply sequence by non-int of type 'float'"
Any help would be greatly appreciated, thanks!
Your amountHours is of type sequence (probably string). What you are looking for probably something like this:
multiply = float(amountHours) * Prate2
The above line cast amountHours to float, then the result of the cast is multiply with Prate2, which is also a float.
Your original code applies multiplication first, which causes the error.
amount = input ("enter amount: ")
hundredDollar = amount / 100
amount = amount % 100
fiftyDollar = amount / 50
amount = amount % 50
twentyDollar = amount / 20
amount = amount % 20
tenDollar = amount / 10
amount = amount % 10
fiveDollar = amount / 5
amount = amount % 5
oneDollar = amount / 1
amount = amount % 1
quarter = amount / .25
amount = amount % .25
dime = amount / .10
amount = amount % .10
nickel = amount / .05
amount = amount % .05
penny = amount / .01
amount = amount % .01
print(int(hundredDollar) + " hundred dollar bills")
print(int(fiftyDollar) + " fifty dollar bills")
print(int(twentyDollar) + " twenty dollar bills")
print(int(tenDollar) + " ten dollar bills")
print(int(fiveDollar) + " five dollar bils")
print(int(oneDollar) + " one dollar bills")
print(int(quarter) + " quarters")
print(int(dime) + " dimes ")
print(int(nickel) + " nickels")
print(int(penny) + " pennies")
So the objective of this program is to output maximum number of dollar bills that fit in the amount, then the maximum number of hundred, fifty, dollar bills,
then 20, then 10, 5 and 1. After that, display the maximum number of quarters, number of dimes, nickels, and pennies.
For example $100 could be displayed as 10000 pennies, or 2 fifty dollar bills or 5 twenty dollar bills. But the correct answer is the maximum number of 100 dollar bills first: 1 one hundred dollar bill. Display only the amount of a denomination if it is not zero.
This issue I'm having is my input keeps reading as a string instead of an int how can I solve this issue
You can use the built-in functions int() or float() to return the string as an int or float respectively and where appropriate.
For example:
amount = float(input("Enter amount:"))
Will set amount to a float constructed from the user input.
Other Improvements
Looking at the code you have provided, the other improvements you can make are as follows:
Use // to divide and floor a number.
For example:
hundredDollar = amount // 100
Will set hundredDollar to a whole number indicating the maximum number of times 100 goes into amount. So, if the amount is 150, hundredDollar will be set to 1 as the amount is composed of one whole hundred dollar bill.
Use str() when concatenating a number with a string
When you concatenate (combine) a number with a string and the number comes first, you will need to first cast the number as a string. For example:
str(hundredDollar) + " hundred dollar bills."
When a float is used and you want the output to display as an int i.e. 2 instead of 2.0 then you can either use the int() function or format the output. For example:
print( int(hundredDollar), "hundred dollar bills." )
Add validation for user input
When receiving input from the user it is advisable to add some validation to check if the data entered by the user is as expected - in this case, is a valid amount. This can be done using a try and except block for the data type and if statements to check if the data is within a valid range or meets additional requirements.
The reason why your input keeps reading as a string instead of an int is because input() returns a string object (this has been so ever since they removed the raw_input() function from Python 2 and made the input() function take its place).
Use the int() function to change the string to an integer, like so:
amount = int(input("Enter amount: "))
(This will also work with the float() function.)
However, if the user enters a string, this will produce an error. To avoid this, wrap the conversion to an integer in a try...except block:
try:
amount = int(input("Enter amount: "))
except ValueError:
#Perhaps prompt the user to try again here
(Once again, this will work with the float() function)
use this
amount = eval(input ("enter amount: "))
It converts string from input to int
if you want float
amount = float(input ("enter amount: "))
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.
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))
print("enter start() to start the program")
def start():
print("This script converts GBP into any currency based on the exchange rate...")
print(" ") #enters a line
exchangeRate = int(input("Enter the exchange rate (Eg: 0.80)"))
print("how much would you like to convert???")
gpb = int(input())
print(gpb*exchangeRate)
If I put the exchange-rate at 0.81 and I enter £1 it always returns 0.
Use float() instead of int() with your input() call. I.e.,
gpb = float(input())
otherwise if the user enters 0.81, int() will truncate this to 0 during the conversion.
By using float() you'll keep the decimal value supplied as input and your computation should yield the result you expect.
You specified type as int.....those are whole numbers (0,1,2,3,4,5,6,7,8....) when you multiply 1 by 0.81 you get 0.81.....key number for integers is the one before dot,in this case zero.So like previous answer shortly said just change type of variable.