pythonfor-loopconditional-statementsinterpretation

Does python have conditional code interpretation?


I was wondering if python has something like conditional code interpretation. Something like this:

x = True
if x:
    for i in range(0, 10):
else:
    for i in range(0, 100):
# ------------------------------
        print(i) # this is the code inside either one these for loop heads

I know I could do this:

x = True
if x:
    for i in range(0, 10):
        print(i)
else:
    for i in range(0, 100):
        print(i)

But in my case, I have a lot of for-loop code and that wouldn't be a very good solution.


Solution

  • You can always do:

    x = True
    
    for i in range(0,10) if x else range(0, 100):
        print(i)