Python coding newbie here. I know there might be other instances of this error popping up and I’ve tried reading them on stack overflow but it seems too technical for me to decode at my level of experience. Could someone help explain why this doesn’t work? I’m trying to use a while loop to ask the user to enter a number. Print a running total of all the numbers that the user enters and if the user enters 0, break from the while loop.
total = []
i = 1
total = int(input('enter a number:'))
while i in total > 0:
total = int(input('enter a number:'))
total = total + i
if i == 0:
break
>Solution :
while i in total > 0:
is parsed using operator chaining rules, which makes it equivalent to:
while i in total and total > 0:
The problem is that total > 0 test; total is a list, and it’s trying to do lexicographic comparison. Your other problem is doing:
total = total + i
list‘s can’t be added with an int.
The fixed code would look like:
total = 0 # total should be an int, not a list to accumulate the sum
while True: # The if check at the end makes it pointless to test or initialize i up front
i = int(input('enter a number:'))
total += i
if i == 0:
break