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('---------')
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:
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
...
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
I am stuck in a program where I have to print "Block" before every 5 numbers without using an additional variable.
This is the code:
for index,i in enumerate(range(1,11)):
print(i)
expected output:
Block
1
2
3
4
5
Block
6
7
8
9
10
Please help new to python.
The expression x % 5 will give you zero if and only if x is a multiple of five.
So, if you wanted to output "Block" before 1, 6, 11, ..., you could use:
if (i - 1) % 5 == 0: print('Block')
before printing the number.
In other words, it's as simple as:
for i in range(1, 11):
if (i - 1) % 5 == 0: print('Block')
print(i)
Running that program gives your expected output of:
Block
1
2
3
4
5
Block
6
7
8
9
10
Note that this will only work if you start at one (as it appears you do). Any other start point will require a slightly modified solution.
In python this can be done by
For index,I in enumerate (range(1,21)):
Print(i)
if(i%5==0):
Print("block")
I have a list of bit. The problem is I need to update the value of the bit according to the new bit that I have. This is the example of my code:
count=1
cycle=3
bit_list = ['1','0','1','0']
new_bit=['1','0','1']
no=''.join(bit_list)
bit=''.join(new_bit)
while (count<=cycle):
for b in no:
print (b)
print ("end of cycle", count)
def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]
update=bin_add(no,bit)
count=count+1
print ("updated list",update)
I need the following output:
1
0
1
0
updated list 1011 #1010 + 1
end of cycle 1
1
0
1
1
updated list 1011 #1011 + 0
end of cycle 2
1
0
1
1
updated list 1100 #1011 + 1
end of cycle 3
Please help me to solve this problem. Thank you.
You want the output to be in the variable update and yet your loop keeps using no and bit for operations, so update doesn't evolve after each iteration. You should also add only the bit of the current index to the output. You should also output your "end of cycle" messages at.. the end of the iteration, not in the beginning:
count=1
cycle=3
bit_list = ['1','0','1','0']
new_bit=['1','0','1']
no=''.join(bit_list)
bit=''.join(new_bit)
while (count<=cycle):
def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]
no=bin_add(no,bit[count - 1])
for b in no:
print (b)
print ("end of cycle", count)
count=count+1
print ("updated list",no)
This outputs:
1
0
1
1
end of cycle 1
1
0
1
1
end of cycle 2
1
1
0
0
end of cycle 3
updated list 1100