简体   繁体   中英

why doesn't += work in a while true loop python?

the code just doesn't work, I can not understand what is wrong with the +=

taken = 1
first = int(input("   "))
while taken <= 6:
        print(1)
        print(taken+=1)

the syntax error just pops up and the + is highlighted red, I have tried looking however the only question I found was where it did not work because of the global the person put before the thing they were += onto.

This is because variable += val is shorthand for variable = variable + val
As this is an assignment expression, and doesn't return anything, that's why this is considered to be a syntax error.

Note 1: This has nothing to do with while loop, it's universally unaccepted

Note 2: Python doesn't support ++ / -- operators as of now

So, do this instead:

taken = 1
first = int(input("   "))
while taken <= 6:
        taken+=1
        print(f"1\n{taken}")

you simply cannot do that. you can do this instead:

taken = 1
first = int(input("   "))
while taken <= 6:
        print(1)
        taken += 1
        print(taken)

This happens because you cannot reassign a variable in the print function Try to write taken += 1 in the row above and than print taken.

taken = 1
first = int(input("   "))
while taken <= 6:
        print(1)
        taken += 1
        print(taken)

why do you use first to get input without any reason?

taken = 1.0
#first = int(input("   "))
while taken <= 6:
    print(taken)
    taken += 1.0

output:

在此处输入图像描述

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