1

I'm currently creating a program that sums the input from the user and returns it as a float.

When I try to run the code below with inputs such as "20.1", I receive ValueError: could not convert string to float: '.'

Shouldn't 20.1 be accepted as a float value?

abc = []
i = 0
while True:
    i += 1
    item = input("Transaction " + str(i) + ": ")
    if item == '':
        break
    abc.extend(item)
abc = [float(k) for k in abc]
print(sum(abc[0:len(abc)]))
0

3 Answers 3

2

When you do abc.extend('20.1') you get ['2', '0', '.', '1'] and the issue is that you can't convert . to float, as the error message suggests. You want to use abc.append(item) instead.

This is because extending a list by an iterable object means appending each element of the iterable to the list. A string is iterable over its characters.


For what it's worth, you can also do sum(abc) straight up, you don't need to do do sum(abc[0:len(abc)]).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Really should've played around a bit more.
0

you should use append instead of extend.

abc = []
i = 0
while True:
    i += 1
    item = input("Transaction " + str(i) + ": ")
    if item == '':
        break
    abc.append(item)
abc = [float(k) for k in abc]
print(sum(abc[0:len(abc)]))

Comments

0

There are specific inputs for specific things. You want to use the float input

    float(input()) 

raw_input and input are for strings

    int(input)

Are for integers

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.