Python Forum
try catch question ,get data from main code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try catch question ,get data from main code
#1
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 ,
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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 "?
Reply
#4
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
You can read more here
https://docs.python.org/3/reference/exec...nd-binding
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
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 ,
Reply
#7
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
now I understand
I will tyr to run some examples of my own and see I understadn it correctly

Thank you very much!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Filter data into new dataframe as main dataframe is being populated cubangt 8 922 Oct-23-2023, 12:43 AM
Last Post: cubangt
  Python 3.11 data import question love0715 2 771 Mar-05-2023, 06:50 PM
Last Post: snippsat
  try catch not working? korenron 2 811 Jan-15-2023, 01:54 PM
Last Post: korenron
  Multiprocessing queue catch get timeout Pythocodras 1 2,238 Apr-22-2022, 06:01 PM
Last Post: Pythocodras
  twisted: catch return from sql wardancer84 0 1,500 Sep-08-2021, 12:38 PM
Last Post: wardancer84
  how to catch schema error? maiya 0 1,808 Jul-16-2021, 08:37 AM
Last Post: maiya
  is this a good way to catch exceptions? korenron 14 4,593 Jul-05-2021, 06:20 PM
Last Post: hussaind
  pool mysql error - not catch by try\except? korenron 1 2,101 Jul-05-2021, 11:26 AM
Last Post: ibreeden
  Integrate/import a gui code to my main.py penahuse 6 3,043 Feb-03-2021, 08:49 PM
Last Post: deanhystad
  Early data import question VorpalPirate 2 2,221 Dec-09-2019, 10:52 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020