3

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!

0

4 Answers 4

6

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)):
Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

1

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.

Comments

1

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)

Comments

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.