简体   繁体   中英

Could someone please help me with why is this happening? Python invalid syntax error

list1 = []
if x in range(100):
    for (x % 5) == 0:
        list1.append(x)
    return list1

I get an invalid syntax error for "=". I don't understand why...

You've got your if and for mixed up, you need :

list1 = []
for x in range(100):
    if (x % 5) == 0:
        list1.append(x)
return list1

for is for iterating and if is for checking the conditions.

PS - Since, I can't seem to be sure of the indentation, if the return list1 is indented one step further, you would return from the first iteration of the for loop (hence returning either an empty list or a list with a single element), I fixed that since that is not what most programs are looking for.

pythonic版本;)

list1 = [x for x in range(100) if x % 5 == 0]

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