Ghanshyam Bhat
Ghanshyam Bhat

Reputation: 3

Use of function inside a for loop

I am trying to call functions inside a for loop, but I am not successful. Is it possible to call functions in Python 3.x like you call subroutines in Excel?

Here is the code I tried but I do not get any output.

def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

Upvotes: 0

Views: 77

Answers (2)

AzyCrw4282
AzyCrw4282

Reputation: 7744

Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.

def my_fun1(i):
    x=+i#I am assuming you want this x+=i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

Upvotes: 1

norok2
norok2

Reputation: 26886

Yes, it is possible but your code would not work because x inside the loop will be unknown:

for i in test_rng:
    my_fun1(i)
    print(x)
    my_fun2(x)

Possibly, you want to do something like:

for i in test_rng:
    x = my_fun1(i)
    print(x)
    my_fun2(x)

You may also want to double-check the code in my_fun1():

def my_fun1(i):
    x=+i
    return x

as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i

Upvotes: 2

Related Questions