简体   繁体   中英

Can anyone please tell me why I'm getting an invalid syntax error with my else statement?

I am trying to test for prime numbers between 2 and 100, but I am getting an error with my code and I don't know why. (I am a newbie to python)

def function():
  mylist = [1,2]
  count = 0
  for i in range(2,100):
    for j in range(2,i):
      if i % j == 0:
        count += 1
      if count > 0:
        count += 0
        else:
          mylist.append(i)
      count = 0
  return mylist

It looks like an indentation problem, try this:

if count > 0:
  count += 0
else:
  mylist.append(i)

In Python, it's very, very important that the code is correctly indented. You see, the else keyword has to appear at the same level that the if keyword. Use a good IDE or text editor to help you catch this kind of errors!

Python indicates code blocks with whitespace in the same way that some languages use braces. Your innermost code block would look like this in a language with braces, which might make it easier to see where syntax error is:

if (count > 0) {
  count += 0;
  else {
    mylist.append(0);
  }
}

Else should be indented along the same line as your if statement. Otherwise the else is considered to be inside if condition.

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