How would pythonista code the equivalent of the increment ++ operator in Python 3?

I am trying to find the correct path in Python to perform the following task (which does not work as it is written):

myList = ["a", "b", "c"]
myCounter = 5

for item in myList:
  print("""Really long text 
in which I need to put the next iteration of myCounter (""", myCounter++, """) followed 
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter++, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')

Unfortunately (for me at least) the ++ operator or the ++ operator does not exist in Python as a way to increase the variable by 1, but using

myCounter += 1

instead it doesn't work if I want to print a variable and increase it at the same time. I want it to print 5 and 6 for the first time through a for loop, then 7 and 8 the next time, and then 9 and 10 for the last time. How to do this in Python 3?

+4
source share
2 answers

I could use itertools.count:

import itertools

myCounter = itertools.count(5)
for item in myList:
    print("la la la.", next(myCounter), "foo foo foo", next(myCounter))

, , :

def counter(val=0):
    while True:
        yield val
        val += 1
+4

myCounter + 1 myCounter + 2 , myCounter 2. -

myList = ["a", "b", "c"]
myCounter = 5

for item in myList:
  print("""Really long text 
in which I need to put the next iteration of myCounter (""", myCounter + 1, """) followed 
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter + 2, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')
  myCounter += 2
+3

Source: https://habr.com/ru/post/1607334/


All Articles