1

I have this little piece of code that causes a trouble:

counter = 0

def F(n):
    counter += 1 # Problem is in this line
    ...

Why do I get this error?

P.S.: I've seen similar questions on SO, but none of them solved my issue. PLEASE DO NOT CLOSE THE QUESTION

Coder4Fun250
  • 207
  • 1
  • 6
  • It's best not to use a function to modify global variables as a way of communicating with the caller (it's better to `return` information from your function so the caller can decide what to do with it), but if you're absolutely bent on doing this, you need to use the `global` keyword to declare that you're assigning to the global variable rather than shadowing it with a local variable. – Samwise Oct 22 '22 at 16:36
  • also: if you've found similar questions that you already know your question is going to get closed as a duplicate of, but the similar questions somehow didn't solve your problem, I suggest clarifying your question in the context of those earlier questions. Link to the existing question(s), and then explain: what specifically didn't you understand about all the existing answers, or how do you think your version of the question is subtly different in such a way that none of those answers apply to your situation? – Samwise Oct 22 '22 at 16:41
  • @Samwise thank you for your answer. But it's kind of weird for me that in Python I need to specify that the variable is global. In C++ for example, there's no need to do that – Coder4Fun250 Oct 22 '22 at 16:44
  • @Samwise why do I have to do this extra work? Maybe I don't have time for that... I asked not to block the question. Why to create troubles out of nowhere... – Coder4Fun250 Oct 22 '22 at 16:45
  • Python and C++ are different languages. Having worked with both for many years (I coded almost exclusively in C++ for about 15 years before learning Python), I'd say I find Python's semantics generally better-thought-out and easier to reason about, but going from one language to another always has a bit of an initial learning curve. – Samwise Oct 22 '22 at 16:46
  • @Samwise yeah, agree 100% – Coder4Fun250 Oct 22 '22 at 16:48
  • Asking a clear question isn't "extra" work, because it's the only way to get a useful answer. Other people can't read your mind! In any case it sounds like the existing answers already solved your problem, so maybe you just weren't looking at the right ones. :) – Samwise Oct 22 '22 at 17:05

0 Answers0