Python Invalid Syntax after __main__:

Question:

Why am I getting this error on the colon when it worked previously?

#!/usr/bin/python
# My Name hw 11

def maxArray(a):
    max = a[0]
    for element in a:
        if element > max:
            max = element
    return max
if__name__=="__main__":

array = [3,1,6,2,4,9,0] 
maxArray(array)
print max

I’m getting a syntax error pointing to the colon after "__main__":

Asked By: c3ad-io

||

Answers:

There are four issues here:

  1. You need a space after the if. Otherwise, Python sees if__name__, which it treats as one word. This is what is causing the error.
  2. You need to indent the lines under this one so that you do not get an IndentationError.
  3. You need to assign the return value of maxArray to a variable and then print that. Otherwise, the last line will throw a NameError saying max is undefined.
  4. You should not name a variable max. Doing so overshadows the built-in.

Here is how your code should look:

#!/usr/bin/python
# My Name hw 11

def maxArray(a):
    max_ = a[0]
    for element in a:
        if element > max_:
            max_ = element
    return max_


if __name__=="__main__":
    array = [3,1,6,2,4,9,0] 
    max_ = maxArray(array)
    print max_
Answered By: user2555451
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.