Note - I am using VSCode
Sample 1: In this example my function nextSquare() is been executed, but aFunc() is not been executed, as in, i get no output for my 2nd function
def nextSquare():
i = 1
while True:
yield i*i
i = 1
for num in nextSquare():
if num<100:
print(num)
def aFunc():
print("This is inside our function")
print("This is outside of our funcion as a seperate entity")
aFunc()
Output:
Code/RoughWork.py
1
4
9
16
25
36
49
64
81
Sample 2: In this example my function nextSquare() is been executed, but aFunc() gives me output, all i did is, just shift aFunc() before nextSquare()
def aFunc():
print("This is inside our function")
print("This is outside of our funcion as a seperate entity")
aFunc()
def nextSquare():
i = 1
while True:
yield i*i
i = 1
for num in nextSquare():
if num<100:
print(num)
Output:
Code/RoughWork.py
This is outside of our funcion as a seperate entity
This is inside our function
1
4
9
16
25
36
49
64
81
so when i used the sample 1: in the above code block, i expected that both the functions will get executed, but they didn't, instead by rearranging the function's positions, i got an output, so why is that why did the position of what existed before what mattered in this scenario,and when i try the same in jupyter notebook, the cell doesn't run at all for sample 2.
CodePudding user response:
The for
loop never ends, so nothing after it is executed. When num
is more than 100 it stops printing, but it keeps looping. You need to stop the loop.
for num in nextSquare():
if num<100:
print(num)
else:
break