Max Bouzari
Max Bouzari

Reputation: 13

User input not correctly being added to a list in python

I want to specify my list type by pressing -1 then I want to add numbers to the numbers list then I want to add those numbers up when I press "F"

For some reason it doesn't listen to me and adds F to the list which gives me an error

thank you in advance.

numbers =[]
ListType = int(input())
if ListType < 0:
    while True :
        if input()!= "F":
            value = input()
            numbers.append(value)
        else:
            print(sum(numbers))

Upvotes: 1

Views: 219

Answers (1)

Kulfy
Kulfy

Reputation: 189

2 issues here:

  1. You are calling input() in while loop due to which the loop will only check the condition with the odd inputs and won't append that in the list, thus, half of the inputs will be ignored.

  2. sum() require a numeric list. But since values taken from input() aren't type-casted, therefore, are appended as string. You can confirm this by using print(type(numbers[0])) somewhere in the code.

Therefore, after correcting these issues, your code would look like:

numbers =[]
ListType = int(input())
if ListType < 0:
    while True:
        value = input()
        if value != "F":
            numbers.append(int(value))
        else:
            print(sum(numbers))

Upvotes: 1

Related Questions