0

How can I assign a value to global variable inside an 'except' block?

x = 5
error_qty = 0

def calcSomething(x):
    try:
        calc(x)
    except ValueError:
        print("Something went wrong!!!")
        error_qty += 1

In my code error_qty += 1 doesn't work. Python 2.7.5.

I got an exception:

UnboundLocalError: local variable 'processingErrors' referenced before assignment

Thx in advance - I'm out of ideas so far ;)

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
  • Welcome to Stack Overflow! Could you please specify what language you are using? It appears to be python by your tag, but it would help to specify it in the question as well. You may want to check out help --> site tour to see what this site is about, and you get a badge for doing it! – Jonathan Dec 14 '14 at 20:45
  • 1
    you can just add ```global error_qty``` at the top of your function – QuinnFTW Dec 14 '14 at 20:46
  • 1
    @Jonathan - Actually, it is redundant to specify the language in the question if the OP already tagged his question with the language. That's what tags are for. –  Dec 14 '14 at 20:47
  • 1
    @Jonathan - it definitely says Python in the body as well as the tag. There's no ambiguity here. @OP - as Quinn says, it's the same as using a global anywhere else. Just use the `global` keyword. – Useless Dec 14 '14 at 20:47
  • @krzychusss: as in any other situation, it's not a good idea, to have a global state, what's the purpose of a function `calc` if it doesn't return anything? – Daniel Dec 14 '14 at 20:56
  • @Daniel: it's just an example. In real scenario there is some strings stripping and comma-to-dot replacement for a big data set imported from DAQ. And thank you, guys - 'global' worked fine for me! Still learning... – krzychusss Dec 14 '14 at 22:03
  • @krzychusss, if you have more questions, please ask a new question - don't edit the existing one. I have rolled back your edit. – Simon MᶜKenzie Dec 14 '14 at 22:33

0 Answers0