-2
q=8
def example(q):
    global q
    q=q+2
    print(q)

example()
File "<ipython-input-35-0e5cbb9ebefd>", line 2
    global q
    ^
SyntaxError: name 'q' is parameter and global

What is the syntax error here? How do I use global keyword then if I have to access q?

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 3
    You're both defining `q` *as a parameter* (`def example(q)`), *and* as `global`. You can't have both, because it makes no sense. Do one or the other. – deceze Jul 16 '23 at 14:01
  • 1
    It's telling you that you've already used `q` as a parameter to the function. Change the function line to `def example():` i.e. eliminate the parameter. – Tom Karzes Jul 16 '23 at 14:01

2 Answers2

-1

You can't declare a parameter and declare it as global. Parameters are local to the function. Change your paramter name to something else.

q=8
def example(a):
    global q
    q=q+2
    print(q)
    print(a)
example(3)
Muhammad Ali
  • 444
  • 7
-1

The syntax error in your code is occurring because you are trying to declare q as a global variable inside the function example() after already passing it as a parameter. In Python, you cannot use the global keyword to declare a variable as global within a function if it has already been defined as a parameter.

To fix this issue, you can either remove the parameter q from the function definition or choose a different name for the global variable. Here's an example:

q = 8

def example():
    global q
    q = q + 2
    print(q)

example()

In this updated code, the q variable is declared as a global variable outside the function, and then inside the function, the global keyword is used to indicate that we want to modify the global variable q. The output will be 10, which is the result of adding 2 to the initial value of q.

Remember that using global variables should be done with caution, as it can make code harder to understand and maintain. It's generally recommended to pass variables as parameters or return values from functions instead of relying heavily on global variables.