Skip to content Skip to sidebar Skip to footer

Using For Loop To Define Multiple Functions In Python?

I need to create 8 functions looking like fcXX_at_this_z(r), where XX ranges from 47 to 54 in integer steps of 1. So the first function shall have its protoype: def fc47_at_this_z(

Solution 1:

Here is a possible solution using a template:

fc_template = 'def fc{0}_at_this_z(r): return upgrade_interpolator_c{0}(r)'
for i in range(47, 55):
    exec(f_template.format(i))

You can define different templates that suite your needs, depending on what exactly you're trying to do. As other users noted in the comments, dynamically creating named functions is not necessarily a good idea, so be careful.

If you need a function defined over multiple lines you can do this:

fc_template = """
def fc{0}_at_this_z(r):
    return upgrade_interpolator_c{0}(r)
"""

Post a Comment for "Using For Loop To Define Multiple Functions In Python?"