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__":
Answers:
There are four issues here:
- 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.
- You need to indent the lines under this one so that you do not get an
IndentationError
.
- 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.
- 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_
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__":
There are four issues here:
- You need a space after the
if
. Otherwise, Python seesif__name__
, which it treats as one word. This is what is causing the error. - You need to indent the lines under this one so that you do not get an
IndentationError
. - You need to assign the return value of
maxArray
to a variable and then print that. Otherwise, the last line will throw aNameError
sayingmax
is undefined. - 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_