azbc azbc -4 years ago 46
Python Question

How to use an imported function in a loop with the loop variable inside that function ?

In bash I have a file "

function.sh
":

_bash_function_() {
echo $i
}


and a file "
exec.sh
"

#!/bin/bash

. ./function.sh

range=(1 2 3)

for i in ${range[@]}; do
_bash_function_
done


That gives the output:

1
2
3


In python I have a file "
function.py
":

def py_function():
print (i)


And a file "
exec.py
":

#!/opt/local/bin/python3

from function import *

list = ['1','2','3']

for i in list:
py_function()


This gives an error:

NameError: name 'i' is not defined


However if I have the function and the loop in the same file:

#!/opt/local/bin/python3

def py_function():
print (i)

list = ['1','2','3']

for i in list:
py_function()


The output is:

1
2
3


How can I have this output in Python, with the function in one file, and the loop in the other ?

Answer Source

One of the main points of functions is that they accept arguments. In your case, you should define the function so that it accepts i as an argument:

def py_function(i):
    print (i)

and pass it when you call it:

for i in list:
    py_function(i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download