1

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.

xilpex
  • 3,097
  • 2
  • 14
  • 45

4 Answers4

3

You can always do:

x = True

for i in range(0,10) if x else range(0, 100):
    print(i)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

No, it doesn't have that syntax. You could achieve the same goal through other means, though.

For example, extract the part that varies (10 versus 100) from the common part (the for in range(...) loop):

limit = 10 if x else 100

for i in range(limit):
    print(i)

Or save one of two different ranges in a variable and loop over that:

numbers = range(0, 10) if x else range(0, 100)

for i in numbers:
    print(i)

Or extract the loop to a function that performs an arbitrary action each iteration:

def loop(limit, action):
    for i in range(limit):
        action(i)

loop(10 if x else 100, lambda i: print(i))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

If you want you could do this.

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

Here the if else statement work like this result_if_true if condition else result_if_false.

Zenocode
  • 656
  • 7
  • 19
0
if x:
    my_iter = range(0, 10)
else:
    my_iter = range(0, 100)
for i in my_iter:
     print(i) 
Błotosmętek
  • 12,717
  • 19
  • 29