简体   繁体   中英

user input list python

I am trying to get the sum of the output_values, and it is giving me a traceback error

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)

You converted user_input from str to float and assign the returning value to val_input , and yet when you append to output_values you give it user_input instead of val_input , effectively discarding your conversion.

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

Simply fix it with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM