Python Forum

Full Version: try catch question ,get data from main code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello
I want to learn and understand what am I doing wrong
I wrote a simple code that use try - catch

import time

i = 0
How_Many_False = 0


def test():
    print("number i is : %3.2f  " % i)
    print(f"result is : {i / 10:3.3f}")

    if i > 5:
        try:
            temp = i / 0
            print(temp)

        except Exception as e:
            print(e)
            print(How_Many_False)
            How_Many_False += 1

    print("false times is : " % How_Many_False)


while 1:
    i = (i + 1)
    test()
    time.sleep(1)
but when I try to run it I get error - in the "catch" section
when I open the code in PyCharm I see this error

Quote:Unresolved reference 'How_Many_False'

why ?
the code is meant to fail on 5
this is just so I can understand the links between the variables on the code

Thanks ,
you need to learn about scope. You try to use How_Many_False as global variable, but because you assign to it inside your function what you get is 2 different variables.
The one inside the function has local scope and is different from the one you initialize outside the function .
one way to remedy this is to declare it global inside the function, e.g. global How_Many_False at the top of the function
However using globals is discouraged . the better way is to pass variables as argument to function.

Then there will be other error, but I will let you try to fix it yourself
OK
but something isn't adding up
Why I didn't have the same problem using "i"?

does it something to do with the "try - catch "?
(Nov-03-2020, 08:15 AM)korenron Wrote: [ -> ]Why I didn't have the same problem using "i"?
because you don't change i inside the function (i.e. no assignment/binding)

(Nov-03-2020, 08:15 AM)korenron Wrote: [ -> ]does it something to do with the "try - catch "?
no, this is pure scope issue - using name inside/outside the function
I see
so if I will increase i at the end of the function - I will get the same error?

SO for more smart and better use (more complicated functions)
it will be best to make the function get 2 valuse and return 2 values(of running , fails)?

Thanks ,
(Nov-03-2020, 08:26 AM)korenron Wrote: [ -> ]so if I will increase i at the end of the function - I will get the same error?
yes.

(Nov-03-2020, 08:26 AM)korenron Wrote: [ -> ]it will be best to make the function get 2 valuse and return 2 values(of running , fails)?
this is one possible approach
another is to go into OOP - i.e. class and work with instance/class variables
Something like
class MyTest:
    def __init__(self, value=0, errors=0):
        self.value = value
        self.errors = errors


    def test(self):
        print("number is : %3.2f  " % self.value) # this is oldest string formatting
        print(f"result is : {self.value / 10:3.3f}") # f-strings - the newest and the best

        if self.value > 5:
            try:
                temp = self.value / 0
            except ZeroDivisionError as e:
                print(e)
                print(self.errors)
                self.errors += 1

        print("false times is : {}".format(self.errors)) # example of str.format() to show all string formatting options

spam = MyTest()
while True:
    spam.test()
    spam.value += 1
    user_input = input('press key or enter "q" to quit: ')
    if user_input == 'q':
        break
now I understand
I will tyr to run some examples of my own and see I understadn it correctly

Thank you very much!