+ 3
Code Solution:
How does this print abc? it = iter('abcdef') for i in range(3, 6): print(next(it), end = ")
5 Respuestas
+ 8
𝓤𝓶𝓮𝓻 ,
here some more informtion about the mentioned code:
# this is the code correctly formatted: (i suppose this code is for *practicing purpose* or from a *challenge*, since the result could be achieved in a more simple way)
it = iter('abcdef') # (1)
for i in range(3, 6): # (2)
print(next(it), end = '') # (3)
> (1) iter() is a built-in function and creates an iterator object from the string.
> (2) range(3, 6) creates 3 loop iterations, the same could also be achieved by using:
for i in range(0, 3): or for i in range(3):
> (3) end = " uses wrong quotes, the code currently uses 1 double quote, but should be 2 double quotes or 2 single quotes
next() is retrieving the next item from the iterator, then it is printed out in the same line.
the probably shortest way to achieve the same could be:
print('abcdef'[:3])
+ 7
There is created an iter object, which will be iterated in for loop.
This is similar to:
it = iter('abcdef')
print(next(it), end = '')
print(next(it), end = '')
print(next(it), end = '')
+ 4
Bob_Li
I think most likely the code is from a challenge. The part of <range(3, 6)> is to make thing confusing.
+ 2
you can just use
s1 = 'abcdef'
for i in range(3):
print(s1[i], end='')
unless it's a really big string, using iter is just overkill.
0
Use same it as it is
s1 = 'abcdef'
for i in range(3):
print(s1[i], end='')
unless it's a really big string, using iter is just overkill.