Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 211
Vlad Avatar asked Dec 07 '25 15:12

Vlad


2 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)):
like image 108
Dan D. Avatar answered Dec 10 '25 05:12

Dan D.


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
like image 37
Bakul Mitra Avatar answered Dec 10 '25 04:12

Bakul Mitra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!