This question already has answers here:
In a Python `for` loop, is the iteration variable a reference? Can it be used to change the underlying data?
(2 answers)
Closed 3 years ago.
Why does:
for i in range(10):
i += 1
print(i)
return:
1
2
3
4
5
6
7
8
9
10
instead of:
2
4
6
8
10
?
Here would be some details if any more were necessary.
for i in range(10):
i += 1
print(i)
is equivalent to
iterator = iter(range(10))
try:
while True:
i = next(iterator)
i += 1
print(i)
except StopIteration:
pass
The iterator that iter(range(10)) produces will yield values 0, 1, 2... 8 and 9 each time next is called with it, then raise StopIteration on the 11th call.
Thus, you can see that i gets overwritten in each iteration with a new value from the range(10), and not incremented as one would see in e.g. C-style for loop.
you should use steps in your range:
for i in range(2,11,2):
print(i)
output:
2
4
6
8
10
i is assigned at each loop iteration overwriting any changes done to its value.
for i in range(10):
i += 1
print(i)
is equivalent to:
i = 0 # first iiteration
i += 1
print(i)
i = 1 # second iiteration
i += 1
print(i)
i = 2 # third iiteration
i += 1
print(i)
# etc up to i = 9
Related
I can understand first output of first example, that is 2 as the i += 1 makes value to 2 than print calls, I also understand the second example's first output that is 1 because print calls i then increment begins. But, what about the end, as we have already defined "while i < 6:" then why first example returns last output as 6 (why don't it breaks to 5)
I'm a beginner so treat me like a kid and write the answer that is easy to understand. Thank you! :)
i = 1
while i < 6:
i += 1
print(i) # Print output after i increment, see the result
>> The output is -
2
3
4
5
6
i = 1
while i < 6:
print(i) # Print output before i increment, see the result
i += 1
>> The output is -
1
2
3
4
5
I was expecting the output should be limited to 5 but it returns to 6 (in first example)
The while condition is only checked before each iteration, not after every statement inside the loop body. So on the last iteration, i == 5 and the condition i < 6 succeeds. It goes into the loop body, increments i to 6, and then prints that value.
i = 1
while i < 6:# initially i value is 1.
i += 1 # here you are incrementing. i value becomes 2.
print(i) # print starts from 2
in the last check i value becomes 5 then it increments to 6 and prints.
so the output starts from 2 and goes till 6.
>> The output is -
2
3
4
5
6
i = 1
while i < 6:
print(i) # Print output before i increment, see the result
i += 1
here you print the i value first and increment later .
you print the i value first
initially 1
then you print it . then you are incrementing it.
in the final check 5<6. it prints 5 and in the next increment as i value equals to 6. the while statement becomes false.
>> The output is -
1
2
3
4
5
This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 2 years ago.
This is my code
for i in range(0,5):
intl = i
print(intl)
intn = i+1
print(intn)
i+=1
print("---------")
What I am getting as the output is the following.
0
1
---------
1
2
---------
2
3
---------
3
4
---------
4
5
---------
Instead of that, I need to get;
0
1
---------
2
3
---------
4
5
---------
Sorry I made a mistake. What you are looking for is the step parameter of range() like this:
for i in range(0,5,2):
intl = i
print(intl)
intn = i+1
print(intn)
print("---------")
Now, for every loop it will skip one number (so i=0, then i=2, then i=4). When modifiying the variable i within a for loop, you will change the local version of i that is active in the current loop. Python doesn't actually use i to get the next item from a itterable, and thus manually changing it doesn't do anything for your loop.
You can simply do this:
for i in range(0, 5, 2):
intl = i
intn = i+1
print(intl)
print(intn)
print("---------")
Now the range function has a step of 2. The step is the difference between each number. By default, it's 1.
for i in range(0, 5):
print(i)
Returns:
0
1
2
3
4
for i in range(0, 5, 2):
print(i)
Returns:
0
2
4
In your code, you did this:
i+=1
This doesn't work because the variable i is set by the for loop in each iteration. This means that no matter what you do with the i variable, in the next iteration it will be 1 more than last time.
This code prints '-------' whenever the next value of i is divisible by 2.
x = 5
for i in range(0, x+1):
print(i)
if (i+1) % 2 == 0:
print('---------')
This question already has answers here:
Skip multiple iterations in loop
(7 answers)
Closed 3 years ago.
I have a for loop in range(100).
Whenever I find a number that does satisfy a condition, it should skip a loop certain number of times
for i in range(2,100):
if i %2 != 0:
i = i+3
Expected results should be:
2
3
6
7
10
11
.
.
.
.
.
A for-loop does not allow you to skip multiple cycles. You can only use
continue to skip the rest of the current cycle
break to skip all remaining cycles and exit the loop
What you need is a while-loop. Where a for-loop defines a number that is incremented from a starting value up to a limit, a while-loop only needs an exit-condition.
Try this:
i = 2
while i < 100:
if i % 2 == 0:
i += 4
else:
i += 1
In my understanding this is what you want to do. But its not the output you desire. But I guess your expected output is not the output of your logic.
i = 2
while i<100:
print(i)
if i % 2 != 0:
i += 3
else:
i += 1
Outputs:
2
3
6
7
10
11
...
j = 0
for i in range(j,100):
if i%2 !=0:
j = i+3
continue
print(j)
output:
0
4
6
8
10
12
14
16
18
20
.
.
.
.
Actually i = i+3 has no effect in a for loop. you may think that i becomes 2+3=5 but in the next iteration i will be 3. You need to use a hile loop for this. This will do the trick for you:
i = 2
while i <= 100:
print(i)
i = (i + 3) if i % 2 != 0 else (i + 1)
Solution with a for loop (although I think a while loop is better for this):
skipping = 0
for i in range(2, 100):
if skipping:
skipping -= 1
continue
if i % 2 != 0:
print(i)
skipping = 2
else:
print(i)
Output:
2
3
6
7
10
11
...
(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10
I'm supposed to align some numbers in a table while using a loop inside a loop. It should look like this when it's done:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
What I've stared with is:
for i in range(1,10,1):
for c in range(1,6,1):
print(i, end='\n')
Though after running this it just prints them bellow each other. And replacing "\n" with "\t" doesn't help either. I've tried .format but with no success. Sorry if this seems very simple and that it should be stated somewhere but I can't find someone with the same problem or some chapter referring to this specific problem.
I did manage to do this table by using while like this:
i = 1
while i < 6:
print("1 2 3 4 5 6 7 8 9\n" , end='' '')
i += 1
This is of course not the best way to do it, I just don't have the knowledge to do it in a smarter way.
First, you have inverted loop ranges it should be:
for i in range(1, 6, 1):
for c in range(1, 10, 1):
Second, in the inner loop you have to print c, not i.
The full code would be like this:
for i in range(1, 6, 1):
for c in range(1, 10, 1):
print(c, end=" ")
print('')
If you want to code only one for loop you can:
for i in range(1, 6, 1):
print( " ".join(map(str, range(1, 10, 1))) )
Firstly, your loops are in the wrong order. As you write your code, you will get 10 rows with 6 numbers.
Next, you can't print in the inner loop, because you will get just 60 rows. So you can store rows in some temp value inside first loop, and on each cycle of outer loop print it. Also, for more pretty code, you can use list comprehensions.
for i in range(1, 10):
print ' '.join([str(number) for number in range(1, 6)])
Also, to perfect this, you can write it in 1 string of code, but this is more understandable.