1

So I am making a program to print the max element of a list,

arr=[1,2,41,6,9,8,5]
c=0
def findmax(x,y):
    if(x>y):
        global c=x
    else:
        global c=y

for x in range(0,len(arr)):
    findmax(c,arr[x])

print(c)

When I try to run the program, it says error: invald syntax line 5 global c=x pointing to the = sign How do I fix it?

3
  • 1
    You can not write global x = y, you can only write global x and then later x = y. Commented Oct 25, 2017 at 19:57
  • why not simply do: max(arr) ? you should declare a global in the beginning of the function and then you can use it later on. Plenty of examples over the web. Commented Oct 25, 2017 at 19:57
  • Except for that, using a global us usually a huge antipattern. If you see it, you should definitely put some effort in rethinking your code. Commented Oct 25, 2017 at 19:58

2 Answers 2

2

Before using a global variable, you have to declare that the variable is global

arr=[1,2,41,6,9,8,5]
c=0
def findmax(x,y):
    if(x>y):
        global c
        c=x
    else:
        global c
        c=y

for x in range(0,len(arr)):
    findmax(c,arr[x])

print(c)

or you can just declare a global variable once as

arr=[1,2,41,6,9,8,5]
c=0
def findmax(x,y):
    global c
    if(x>y):
        c=x
    else:
        c=y

for x in range(0,len(arr)):
    findmax(c,arr[x])

print(c)
Sign up to request clarification or add additional context in comments.

4 Comments

Why do you declare global c twice?
Because every time it calls a function, only one of the code block will be executed (either if or else).
If you're going to do it anyways (regardless if the if/else is getting executed) why not do it once in the beginning? do you like duplicated code ? if the variable name changes later, now you have to change it in two places instead of one (just an example of why it's bad practice).
True @alfasin. I agree it's a bad practice. that's why I added the modified code snippet after your first comment
1

The following line is not correct:

global x = y

instead you have to first write

global x

then you are allowed to assign x.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.