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.
Related
So I am stuck, I know the error is a ValueError unable to convert string to float. I just don't understand why. This is the lab I am working on:
Output each floating-point value with two digits after the decimal
point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
20.0
3.1599
the output is:
1.58
7.90
63.20
Your program must define and call the following driving_cost()
function. Given input parameters driven_miles, miles_per_gallon, and
dollars_per_gallon, the function returns the dollar cost to drive
those miles. Ex: If the function is called with: 50 20.0 3.1599 the function returns: 7.89975 def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon)
Your program should call the function three times to determine the gas
cost for 10 miles, 50 miles, and 400 miles.
Here is my code:
def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon):
cost = (driven_miles/miles_per_gallon)*dollars_per_gallon
return cost
if __name__ == '__main__':
driven_miles = int(input())
miles_per_gallon = float(input())
dollars_per_gallon = float(input())
for i in range(len(driven_miles)):
cost = driving_cost(driven_miles[i], miles_per_gallon, dollars_per_gallon)
print('{:.2f}'.format(cost))
As I stated above, I am extremely new to this, just trying to understand why I am getting a ValueError: could not convert string to float: when entering the input like this (50, 20.0, 3.1599). But if I enter the other value with the breaks in it like:
20.0
3.1599
it goes through for me. I am definitely missing something.
input() reads one line from standard input. Your code takes that line and tries to convert it to an int or float. But python can't interpret (50, 20.0, 3.1599) as an int or float.
You can write your program to parse (50, 20.0, 3.1599) as an input string. Or you can write your program to read 3 lines of input an parse each as one of those values. Or you could write your program to support both. But you can't write your program to read 3 lines of input and then expect it to successfully parse alternative formats of input data.
If you are trying to input all 3 of those inputs to the program in the format the program currently expects, separate each line with the line terminator. In a Posix flavored shell that could look something like:
python myprogram.py <<<"1
2
3
"
It's a much better technique than individually typing in every input as you test your program!
As an aside, in the real world, input() is very rarely used. In fact interactive program input is very rare in everywhere except computer programming coursework. In the real world user input is more often provided as command line arguments. If standard input is the source of data it's often formatted with a spec like Json or Yaml (etc) that doesn't leave ambiguity in how the data should be formatted.
Even if your coursework requires you to collect ostensibly interactive user input, try to remove it from SO questions whenever possible. Instead hard code the input data into the code you post to make your code more reproducible. input() is a common tripping point so if you can take it out of the equation, do so. I suspect if you would have tried to do that here, you would have quickly realized that no single variable in your program was a proper place to store the input (50, 20.0, 3.1599).
Good luck with your studies!
Since you're trying to use a loop, it sounds like you want to use a List:
def driving_cost(distance, miles_per_gallon, dollars_per_gallon):
print('{:.2f}'.format(distance/miles_per_gallon*dollars_per_gallon))
MPG = float(input('Enter miles per gallon (eg 20.0): '))
DPG = float(input('Enter dollars per gallon (eg 3.1599): '))
driven_miles_list = [10, 50, 400]
for distance in driven_miles_list:
driving_cost(distance, MPG, DPG)
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
I'm totally new to programming. Picked up a PDF and I'm trying out Exercises given. But now I'm stuck with the following task:
Write a Python program that allows the user to enter any integer
value, and displays the value of 2 raised to that power. Your program
should function as shown below
What power of two? __
Two to power of __ is __
I think it should start something like this:
x=input("What power of two? ")
but what's next? or is it right at all?
If you get an error with pow(2, x) it's probably because of typing, you should convert the string from input to a number, like int or float
>>> e = float(input('What power of two?'))
What power of two?1.2
>>> pow(2, e)
2.2973967099940698
It's pretty simple, really.
Python has this operator for Powers: **
e.g. print(2**10) will print 1024.
One more thing- you'll have to type x = int(input("*Whatever you want to enter*")), as input() returns a String.
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.
I'm just starting to get into learning Python (Sorry, don't claim homework on this one, because it's not). Just to give myself some meaningful exercises to do to get better with the syntax and features, I've been following this URL: http://www.cs.washington.edu/homes/stepp/bridge/2007/exercises.html
This particular 'Overflow' issue I'm receiving with some floating point calculations is just mystifying me.
This is the error message I get:
Traceback (most recent call last):
File "./lab0102.py", line 28, in <module>
payment = PMT(r, n, P)
File "./lab0102.py", line 19, in PMT
return round(P * ((r *((1+r)**num_pmts)) / ((1+r)**num_pmts)))
OverflowError: (34, 'Numerical result out of range')
Here's my code:
import math
#from decimal import Decimal
def PMT(r, n, P):
rate = (r/100)/12
print "rate:", rate
num_pmts = n*12
payment = P * ((r *((1+r)**num_pmts)) / ((1+r)**num_pmts))
return payment
print "This program computes monthly loan payments."
P = input("Loan Amount? ")
n = input("Number of Years? ")
r = input("Interest Rate? ")
payment = PMT(r, n, P)
print "You payment is", payment
I've done everything by trying to typecast input, to use some of the wrapper operations to round or specify decimal point precision. I've even used the Decimal module to try and print out the decimal in string format to see where my logic flaw is.
Any takers on this one to educate me in the realm of floating point calculations in Python?
input() only gives you a float if it actually sees something that looks like a float; if it looks like an integer then you will get an integer. Use float(raw_input()) instead.
Now, as to the overflow.
Older versions of Python did not promote int to long automatically, meaning that the maximum integer you can have is signed 32- or 64-bit; any higher than that results in an overflow. Since you have integers in your expression (see above), you can potentially breach the maximum value for the type, resulting in the exception you're seeing.