将整数乘以分数和小数时,Python程序出错

Stu*_*e75 1 python math equation

我试图制作一个简短的程序来解决着名的德雷克方程.我让它接受整数输入,十进制输入和小数输入.但是,当程序试图将它们相乘时,我收到此错误(在我输入所有必要值之后,错误发生):

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'
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

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 
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我需要更改什么?

Fra*_*til 5

您需要将输入值转换为浮点数.

r = float(input())
Run Code Online (Sandbox Code Playgroud)

(注意:在小于3的Python版本中,请使用raw_input而不是input.)

等等其他变量.否则,您尝试将字符串乘以字符串.

编辑:正如其他人所指出的,calc另外不能使用+运算符连接到周围的字符串.使用字符串替换:

print('My estimate of the number of detectable civilizations is %s.' % calc)
Run Code Online (Sandbox Code Playgroud)