用户输入列表python

时间:2018-07-18 01:58:17

标签: python arraylist while-loop

我正在尝试获取output_values的总和,这给了我一个追溯错误

output_values = []
while True:
    user_input = input('Please type in your test grades, and follow your input by typing in "done"')
    if user_input == 'done':
        print('All done, here is your average')
        break
    ### here you will insert in the traceback error to prevent your code from crashing due to invalid input
    try:
        val_input = float(user_input)
        if val_input:
            output_values.append(user_input)
    except ValueError:
        print('You have typed in an invalid input, please type in your grade as a numerical digit')
        continue
print(output_values)
summation = sum(output_values)

1 个答案:

答案 0 :(得分:1)

您将user_inputstr转换为float,并将返回值分配给val_input,但是当您附加到output_values时,您将其{ 1}},而不是user_input,有效地放弃了转化。

val_input

只需使用以下方法修复它:

    val_input = float(user_input)
    if val_input:
        output_values.append(user_input)