1

我试图编写一个简短的程序来计算著名的 Drake 方程。我让它接受整数输入、十进制输入和小数输入。但是,当程序尝试将它们相乘时出现此错误(在我输入所有必要的值后立即发生错误):

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'

我的代码如下:

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 

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

4

4 回答 4

5

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

r = float(input())

(注意:在小于 3 的 Python 版本中,使用raw_input代替input.)

其他变量依此类推。否则,您会尝试将字符串乘以字符串。

编辑:正如其他人指出的那样,calc也不能使用+运算符将​​其连接到周围的字符串。为此使用字符串替换:

print('My estimate of the number of detectable civilizations is %s.' % calc)
于 2012-07-28T04:44:33.100 回答
1

与断言问题在于没有将输出input转换为正确类型的答案相反。真正的问题是

  1. 未正确验证程序的输入,以及
  2. 尝试将 str 与此行上的数字连接:

    print('My estimate of th..." + calc + ' .')
    

给定整数、浮点数和小数值作为输入,您的程序对我来说运行良好。给定'1''1'(引用)作为前两个输入,它会返回您看到的错误。

于 2012-07-28T04:56:03.233 回答
0

您已将某些值转换为适合算术的类型,但未将其他值转换为合适的类型。应该传递真实值,float()并且应该解析和计算比率(或使用Fraction类型,或强制用户输入真实值)。下面发布了后者的示例:

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())
于 2012-07-28T04:47:49.703 回答
0

输入([提示])-> 值

等效于 eval(raw_input(prompt))。

所以,我建议你使用它raw_input来避免潜在的错误。

于 2012-07-28T04:48:55.990 回答