Python - summarize try-except statement -


i want summarize following code. should check if variable in calculation assigned. if not, result zero. because have hundreds of calculations these don't want repeat try-except every calculation.

how that?

a = 1 b = 2 d = 3 f = 2  try:     ab = + b except:     ab = 0  try:         ac = - c except:     ac = 0  try:         bg = b / g except:     ac = 0 

write function it, using lambda (a one-line function) defer evaluation of variables in case 1 of them doesn't exist:

def call_with_default(func, default):     try:         return func()     except nameerror:   # names don't exist         return default  ab = call_with_default(lambda: a+b, 0) # etc. 

you might benefit using sort of data structure (e.g. list or dictionary) contain values rather storing them in individual variables; it's possible use loops these calculations instead of writing them individually.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -