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
JavaScript
x
20
20
1
def lagrange():
2
a=2
3
b=3
4
print('donner la fonction')
5
print ('Lagrange : a/b=',a/b)
6
7
8
9
def newton():
10
a=2
11
b=0
12
print('donner Newton')
13
print ('Newton : a/b=',a/b)
14
15
def jacobi():
16
a=2
17
b=3
18
print('donner Newton')
19
prindt ('Jacobi : a/b=',a/b)
20
I meant some prolems in the 2 functions (division by 0 and wrong syntax)
JavaScript
1
28
28
1
import ipywidgets as widgets
2
from IPython.display import display
3
button1 = widgets.Button(description="Purge",
4
layout=widgets.Layout(width="auto", height="auto"), button_style="success")
5
6
button2 = widgets.Button(description="Mise à Jour",
7
layout=widgets.Layout(width="auto", height="auto"), button_style="primary")
8
9
widgets.TwoByTwoLayout(top_left=button1, top_right=button2)
10
11
12
def on_button1_clicked(b):
13
marchands = [lagrange(),newton(),jacobi()]
14
for entry in marchands :
15
try :
16
entry
17
except :
18
print('Oops! ', entry)
19
print (entry,' is OK')
20
21
def on_button2_clicked(b):
22
mabrouk()
23
24
button1.on_click(on_button1_clicked)
25
button2.on_click(on_button2_clicked)
26
27
widgets.TwoByTwoLayout(top_left=button1, top_right=button2)
28
Advertisement
Answer
You’re calling your functions at the wrong time. In
JavaScript
1
2
1
marchands = [lagrange(),newton(),jacobi()]
2
you execute the 3 functions, and store their outputs in the list.
What you want to do is store the functions themselves:
JavaScript
1
2
1
marchands = [lagrange ,newton ,jacobi]
2
and call them in your try: ... except:
block:
JavaScript
1
7
1
for entry in marchands :
2
try :
3
entry() # note the parenthesis to call the function
4
except :
5
print('Oops! ', entry.__name__)
6
print (entry.__name__,' is OK')
7