Kasra Najafi
Kasra Najafi

Reputation: 570

How to find out variables value in a specific step of a loop in python?

When I try to debug a code that has a loop (or recursion), how can I find out my set values in a specific step? for example in this code how to find outs values when i is 5?

s = set()
for i in range(10):
    s.add(sum(s)+i)
print(s)

Upvotes: 1

Views: 726

Answers (2)

zahra honarvar
zahra honarvar

Reputation: 122

You can step in specific step by define if on it:

s = set()
for i in range(10):
    if i == 5:
        print(s)
    s.add(sum(s)+i)
print(s)

and now you can set breakpoint on it in your IDE.

Upvotes: 1

Reetesh Kumar
Reetesh Kumar

Reputation: 289

If you want to find the values of set at any specific value of i, you can use the debug tool of the ide you are using. Through this, you'll get to know the status of every variable during the whole operation at every step.

Also, you can use if statement at any point whenever required whether it's 5 or 9. For your specific example the code can be:

s=set()
for i in range(10):
    if i==5:
        print(s)
    s.add(sum(s)+i)
print(s)

Upvotes: 2

Related Questions