我是Python的新手,我想将float值存储在列表中,然后使用列表中的值进行处理,直到我将其重置为空为止。我正在抛出此错误:
python TypeError: can't multiply sequence by non-int of type 'list' >>>
该程序是一个基本的距离,速度和时间计算器,我还没有添加类似单位的内容,但是遇到了这个障碍。如何在equate()
函数中正确乘法?
import math
import random
import os
distance = []
speed = []
time = []
result = []
def di():
while True:
try:
di = float(input('Enter Distance:> '))
distance.append(di)
print('You entered', distance)
sp()
except ValueError:
print('Thats not a number')
pass
def sp():
while True:
try:
sp = float(input('Enter Speed:> '))
speed.append(sp)
print('You have entered', speed)
ti()
except ValueError:
print('Thats not a number')
pass
def ti():
while True:
try:
ti = float(input('Enter Time:> '))
time.append(ti)
print('You have entered', time)
equate()
except ValueError:
print('Thats not a number')
pass
def equate():
print('What do you want to calculate?')
option = input('1.Distance, \n2.Speed, \n3.Time, \n4.Exit Program, \n:>')
if option == '1':
res = speed * time
result.append(res)
print(result)
elif option == '2':
res = distance / time
result.append(res)
print(result)
elif option == '3':
res = distance / speed
result.append(res)
print(result)
elif option == '4':
sys.exit('Goodbye')
else:
print('Thats not an option')
pass
def running():
input('Distance Speed and Time Caluclator \nPress any key to enter the values')
di()
running()
编辑:完全错误
win32上的Python 3.4.4(v3.4.4:737efcadf5a6,2015年12月20日,20:20:57)[MSC v.1600 64位(AMD64)] 输入“版权”,“信用”或“ license()”以获取更多信息。
===================== RESTART: C:\Python34\equations.py =====================
Distance Speed and Time Caluclator
Press any key to enter the values
Enter Distance:> 30
You entered [30.0]
Enter Speed:> 20
You have entered [20.0]
Enter Time:> 10
You have entered [10.0]
What do you want to calculate?
1.Distance,
2.Speed,
3.Time,
4.Exit Program,
:>1
Traceback (most recent call last):
File "C:\Python34\equations.py", line 69, in <module>
running()
File "C:\Python34\equations.py", line 67, in running
di()
File "C:\Python34\equations.py", line 16, in di
sp()
File "C:\Python34\equations.py", line 27, in sp
ti()
File "C:\Python34\equations.py", line 38, in ti
equate()
File "C:\Python34\equations.py", line 47, in equate
res = speed * time
TypeError: can't multiply sequence by non-int of type 'list'
答案 0 :(得分:0)
在equate
函数中进行乘法运算时似乎发生了错误。我认为您正在尝试将列表乘以列表,如@ TigerhawkT3所说。相反,我建议每当在speed[-1]
中引用time[-1]
,distance[-1]
和equate()
(以获取最后一个项目,因为这是用户刚刚输入的内容)时,功能。例如,乘以:
if option == '1':
res = speed[-1] * time[-1]
result.append(res)
print(result)
编辑:感谢您使问题更加简洁
答案 1 :(得分:0)
首先,您不需要在每个函数上进行while
循环,一次就足够了。
其次,您要计算列表中每个项目的值。就您而言,选项示例:
if option == '1':
#it would be nice to check if arrays are the same size etc.
for i in range(len(time)):
result.append(speed[i] * time[i])
print(result)
请记住,结果就是错误。