Skip to content
Advertisement

Perform an exception for a list of funtions

hello people (I am new to python) Question: i use ipywidgets with buttons, i want to call a list of function, sometimes there’s a problem in a function (syntax, division by zero,…), i try to put an exception to pass the error and lunch the next function, don’t work :(

I’m running in jupyter environment using python 3.8.5.final.0 and pandas 1.1.3 division by 0 problem of syntax

def lagrange():
a=2
b=3
print('donner la fonction')
print ('Lagrange : a/b=',a/b)



def newton():
a=2
b=0
print('donner Newton')
print ('Newton : a/b=',a/b)

def jacobi():
a=2
b=3
print('donner Newton')
prindt ('Jacobi : a/b=',a/b)

I meant some prolems in the 2 functions (division by 0 and wrong syntax)

import ipywidgets as widgets
from IPython.display import display
button1 = widgets.Button(description="Purge",
                    layout=widgets.Layout(width="auto", height="auto"), button_style="success")

button2 = widgets.Button(description="Mise à Jour",
                    layout=widgets.Layout(width="auto", height="auto"), button_style="primary")

widgets.TwoByTwoLayout(top_left=button1, top_right=button2)


def on_button1_clicked(b):
    marchands = [lagrange(),newton(),jacobi()]
    for entry in marchands : 
        try :
            entry
        except :
            print('Oops! ', entry)
        print (entry,' is OK')

def on_button2_clicked(b):
    mabrouk()

button1.on_click(on_button1_clicked)
button2.on_click(on_button2_clicked)

widgets.TwoByTwoLayout(top_left=button1, top_right=button2)

Advertisement

Answer

You’re calling your functions at the wrong time. In

marchands = [lagrange(),newton(),jacobi()]

you execute the 3 functions, and store their outputs in the list.

What you want to do is store the functions themselves:

marchands = [lagrange ,newton ,jacobi]

and call them in your try: ... except: block:

for entry in marchands : 
        try :
            entry()  # note the parenthesis to call the function
        except :
            print('Oops! ', entry.__name__)
        print (entry.__name__,' is OK')
Advertisement