Search code examples
pythonwhile-loopintegertypeerror

writing a while loop statement in python while eliminating Type error


For the following exercise: Write a program to keep asking for a number until you enter a negative number. At the end, print the sum of all entered numbers.

I can do this using a while loop and the 'if/ else statement' which works well.

num = 0
v = int

while True:
print('please enter number')
v = int(input())
if v > 0:
    num = num + v
else:
    print('you have entered a negative number')
    num = num + v
    break

print('total number is ' + str(num))

But if i want to write the program using only while loop i.e. no if/else statement attached i get a TypeError: '>=' not supported between instances of 'type' and 'int' See my code below:

num = 0
v = int

while v >= 0:
    print('please enter number')
    v = int(input())
    num = num + v

print('you have entered a negative number')
num = num + v
print('total number is ' + str(num))

I think the issue might have to do with the way i've initialised the variables here. Please help.


Solution

  • v = int is assigning v to a type, therefore when while check for v >= 0 it will raise a TypeError: '>=' not supported between instances of 'type' and 'int'

    If you didn't want to assign v = 0, you can use walrus operator (:=) to assign a value to a variable and return that value in the same expression (Python 3.8+)

    num = 0
    while (v := int(input('please enter number\n'))) >= 0:
        num += v
    print('you have entered a negative number')
    print('total number is ' + str(num))