how to include "else" statement in "for" loop with "if" statement?

Viewed 109

I know how to make if statement inside for loop, but I don't know how to also add "else" there.

For example:

check_state = 1
for v in (v for v in range(0,10 +1, 1) if check_state == 1):
   print v

Output: It will print from 0 to 10

And I want to add "else" statement there, something like this:

check_state = 0
for v in (v for v in range(0,10 +1, 1) if check_state == 1, else v for v in range(1)):
   print v

Hoping for this output: prints 0

I don't know how to put it in correct syntax. Can somebody help?

Thank you!

4 Answers

I think you want to use the if expression to pick between two range calls:

for v in (range(0,10 +1, 1) if check_state == 1 else range(1)):
check_state = 1 
#can be given 0 or 1, if 1 then it will print '0-10' and if 0 then it will print only '0'

for v in range(0,11):
   if check_state == 1:
      print(v,end="")
   elif check_state == 0:
      print(v)
      break

Is there any particular reason you are using a generator?

You can do this in list comprehension like this:

[v for v in (range(0,11) if check_state == 1 else range(1))]

It may also be beneficial to consider this from a traditional conditional for loop perspective to understand what is happening here.

x = []
check_state = 1

for v in range(0,11):
    if check_state == 1:
        x.append(v)
    elif check_state == 0:
        x = [0]

Both of these will output a list of integers instead of printing them out like in the original code.

There are 2 possible ways in which you can do this in shorthand notation:

check_state = 0
for v in range(11) if check_state == 1 else range(1):
      print(v)

or else:

check_state = 0
for v in check_state == 1 and range(11) or range(1):
      print(v)
Related