How to Auto-Increment in Python
I Am New to Python. I Want to Print All Available Functions in Os Module as: 1 functionName 2 functionName 3 functionName and So On. Currently I Am Trying to...
I am new to python. I want to print all available functions in os module as:
1 functionName
2 functionName
3 functionName
and so on.
Currently I am trying to get this kind of output with following code:
import os
cur = dir(os)
for i in cur:
count = 1
count += 1
print(count,i)
But it prints as below:
2 functionName
2 functionName
2 functionName
till end.
Please help me generate auto increment list of numbers, Thanks.
2 Answers
Its because you've re-defined the count variable or reset it to 1 for each loop again. I'm not into python but your code doesn't make sense since everytime the count variable is first set to 1 and then incremented. I'd simply suggest the following.
import os
cur = dir(os)
count = 1
for i in cur:
count += 1
print(count,i)
The pythonic way to do this is enumerate. If we pass the keyword argument start=1, the count will begin at 1 instead of the default 0.
import os
cur = dir(os)
for i, f in enumerate(cur, start=1):
print("%d: %s" % (i, f))