Multiplying floats (Python 3.7) - python

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.

Related

Wont show result of calculation

i am very new to coding and stumbled upon my first problem I don't know how to solve:
weight_in_pounds=(input('How much pounds do you weigh? '))
weight_in_kilograms=weight_in_pounds*int(0.45)
print('You weigh '+ weight_in_kilograms +' kg.')
This is what I typed in and this is the result if I run it:
How much pounds do you weigh? 213
You weigh kg.
I have no idea why it doesn't show the answer. For this example I typed in 213 but instead of the result it just shows a space. What did I do wrong?
You're converting 0.45 to an integer. 0.45 as an integer is 0. weight_in_pounds*0 = 0.
You're inputting weight_in_pounds, which makes it a string. Python is a bit weird with types, so a string * 0 is just an empty string.
You should first remove the conversion to an integer on the 2nd line and add a conversion to a float (decimal) to the first. I.E: weight_in_pounds=float(input('How much pounds do you weigh? '))
With very minimal changes you can get it to work:
weight_pound = int(input('How much do you weigh in pounds? '))
weight_kg = weight_pound*0.45
print('You weigh {0} kg.'.format(weight_kg))
The problem is as Brian mentioned. It's a matter of types.
Also you can only concatenate strings and so you'll have to use such formatting to get it to display.
* Repetition - Creates new strings, concatenating multiple copies of the same string
Explaination of operations on strings
You are repeating the same string zero times.

Not understanding why my program doesnt work

I am pretty new to programming and python. My question is I had these lines running but first I'll explain. I wanted to write a program that would ask your weight in pounds and my program would convert it to kgs. Now here is the correct answer:
weight = input ("What is your weight in pounds? ")
converter = int(weight) * 0.45
print (converter)
Now I wanted it to work for decimals (lbs in decimals). So I wrote this:
weight = input ("What is your weight in pounds? ")
converter = int(0.45) * weight
print (converter)
But the second program doesn't work. Can anyone explain why? Thank you
int(0.45) converts the 0.45 to an integer (whole number) which is truncated to 0 so you are effectively multiplying any input by 0.
In the original program you were taking the input as a string with the input command and then converting that string to an integer with int(weight). If you want to have the program work with decimals then you would want to use float(weight)
In your second program you are casting to int the number 0.45 which evaluates to be 0 In order for this to work with float, just remove the int() before the 0.45 , because it's a floating number the whole expression will be float.
weight = input ("What is your weight in pounds? ")
The above code always returns a string.
If you try running the following after the above line you will notice it prints str, which means its a string data type.
print(type(weight))
Now that we know the type of data store in the variable weight is of str, we need to ensure that we convert it into a number before using it in a mathematical equation.
In your case i understand that, in your second program you want to have your output of the variable converter in decimals.
hence you have to rewrite the line as follows:
converter = 0.45 * float(weight)
In order to ensure that the converter variable holds a decimal value, you can try:
print(type(converter))
if the above line gives the output as float, you have got your intended output.
For future reference, you may refer this link which shows all the data types available in Python: https://docs.python.org/3/library/datatypes.html

Python how to multiply results from input strings [duplicate]

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.

Error in Python program when multiplying integers by fractions and decimals

I tried to make a short program that works out the famous Drake equation. I got it to accept integer inputs, decimal inputs, and fractional inputs. However, I get this error when the program attempts to multiply them (right after I input all necessary values the error happens):
Traceback (most recent call last)
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 24, in <module>
calc() #cal calc to execute it
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 17, in calc
calc = r*fp*ne*fl*fi*fc*l
TypeError: can't multiply sequence by non-int of type 'str'
My code is as follows:
def intro():
print('This program will evaluate the Drake equation with your values')
def calc():
print('What is the average rate of star formation in the galaxy?')
r = input()
print('What fraction the stars have planets?')
fp = input()
ne = int(input('What is the average number of life supporting planets (per star)?'))
print('What fraction of these panets actually develop life')
fl = input()
print('What fraction of them will develop intelligent life')
fi = input()
print('What fraction of these civilizations have developed detectable technology?')
fc = input()
l = int(input('How long will these civilizations release detectable signals?'))
calc = r*fp*ne*fl*fi*fc*l
print('My estimate of the number of detectable civilizations is ' + calc + ' .')
if __name__=="__main__":
intro() #cal intro to execute it
calc() #cal calc to execute it
What do I need to change in order to fix this problem?
You need to convert your input values to floats.
r = float(input())
(Note: in Python versions less than 3, use raw_input instead of input.)
And so on for the other variables. Otherwise you're attempting to multiply a string by a string.
Edit: as others have pointed out, calc additionally cannot be concatenated to the surrounding strings using the + operator. Use string substitution for that:
print('My estimate of the number of detectable civilizations is %s.' % calc)
Contrary to the answers asserting that the problem's with not casting the output of input to the correct type. The real problem is
Not properly validating the input to the program, and
Trying to concatenate a str with a number on this line:
print('My estimate of th..." + calc + ' .')
Your program runs fine for me given integers, floats and fractional values as input. Given '1' and '1' (quoted) as the first two inputs, it returns the error you're seeing.
You have converted some values into appropriate types for arithmetic but not the others. The real values should be passed to float() and the ratios should be parsed and computed (or use the Fraction type, or force your user to input a real). An example of the latter is posted below:
print('What is the average rate of star formation in the galaxy?')
r = float(input())
print('What fraction the stars have planets?')
fp = float(input())
ne = int(input('What is the average number of life supporting planets (per star)?'))
print('What fraction of these panets actually develop life')
fl = float(input())
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
So, I suggest you to use raw_input to avoid potential errors.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
I'm getting a TypeError. How do I fix it?
(2 answers)
Closed 6 months ago.
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).
I run into this error. Anyone know what could be wrong or have any suggestions?
salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.
For example:
import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha
coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C
The error:
coff *= C
TypeError: can't multiply sequence by non-int of type 'float'
The solution - convert the list to numpy array:
coff = np.asarray(coff) * C
The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:
>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!
You can't multiply string and float.instead of you try as below.it works fine
totalAmount = salesAmount * float(salesTax)

Categories

Resources