2

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.

4
  • No, it does not. What you could do here though is rng = range(10) if x else range(100) then for i in rng: .. Commented May 5, 2020 at 22:33
  • How about a function? Commented May 5, 2020 at 22:33
  • Put your loop body in a function. Commented May 5, 2020 at 22:33
  • If you're going to use a variable anyway then just set it to 10 or 100, and use that variable in the range. Commented May 5, 2020 at 22:38

4 Answers 4

3

You can always do:

x = True

for i in range(0,10) if x else range(0, 100):
    print(i)
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

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.

Comments

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

1 Comment

Please add a bit of explanation and context around your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.