-2

I am very very new to programming and I understand this is quite a dumb question but I'm not sure how to search for the answer to it.

For an assignment, we have been limited to 2 or less global variables.

I'm trying to do this:

for x in range(0,5):
    etc, etc

I have tried printing global() and I'm pretty sure this makes x a global variable - is there a way to create a local variable in this case or do I just have to work around it?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    x is locally scoped to the loop, it's not global – OneCricketeer Sep 26 '20 at 21:49
  • What you are trying to achieve is not clear. Give a longer code sample. Local variables are not restricted to a for loop but to a function or a method. – Ben2209 Sep 26 '20 at 21:50
  • 4
    While not necessarily `global` @OneCricketeer you will find `x` still in scope after the loop -- it is not scoped to the loop. – Mark Sep 26 '20 at 21:51
  • 1
    Global variables are defined by the `global` statement when changed within a function. Challenge yourself to use *none*. In broad terms, [global variables are dangerous](https://stackoverflow.com/a/19158418/6340496).. – S3DEV Sep 26 '20 at 21:52
  • 'local' would mean local to a function. If you don't use any function, your variables will be global. – Thierry Lathuille Sep 26 '20 at 21:55

1 Answers1

0

It is not possible to have loop variables in a scope other than the loop's scope, simply because the variable is defined in the same line/indentation as the for loop. If the for loop is in the global scope, then so too will the loop variable. However, if your limitation is only on global variables, the for loop could be placed within a non-global scope, such as a function, like so:

def loop():
    for x in range(0, 5):
        ...

This workaround, however, likely goes against the spirit of your assignment, so use with care.

As a note, this approach still creates a global variable, in this case a function, but whether or not that counts would likely depend on the semantics of the assignment. "Use with care" should more likely be "don't use at all."

bbnumber2
  • 643
  • 4
  • 18