why last output also varies in this block of python code? - python

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

Related

Python incremental iterating loop [duplicate]

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('---------')

Why can't "i" be manipulated inside for-loop [duplicate]

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

How to print block before each group of 5 numbers without adding a new variable?

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")

Update list of bit using while loop in python

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

python, how to count down from 10 by using the while operator

I want to make a program that counts down from 10 by using the operator while.
This is what I have so far but it would not do what I want.
i = 10
while i < 10:
print(i)
i = i-1
This doesn't work and I'd like to know why!
You exit the loop as soon as i is less than 10. 9 is less than 10 so you leave the loop in the first run. What you need is:
i = 10
while i > 0:
print(i)
i = i-1
In this case you stay in the loop as long as i is greater than zero.
i < 10 means "i is less than 10"
i > 10 means "i is greater than 10"
The symbol is a bit like an arrow. It always points towards the smaller item. This is slightly different if you are checking for a condition.
if i < 10 is saying "if i is less than 10"
while i > 10 is saying, "while i is greater than 10"
So this is what you need:
i = 10
while i > 0: # while i is greater than zero
print(i)
i = i - 1 # i will eventually be less than zero, meaning the
# condition for the loop will return false and stop the loop
This will print i from 10 to 0
Others have shown you the way how to do it with while. My question is why do you want to do it by using while. If there are no constrains, I would suggest you to look for range:
https://docs.python.org/3.5/library/functions.html#func-range
You could implement your counting like this:
for i in range(11):
print(i)
#output
0
1
2
3
4
5
6
7
8
9
10
To count down just reverse the range function:
for i in reversed(range(11)):
print(i)
#output
10
9
8
7
6
5
4
3
2
1
0
I hope this alternative can help you.

Categories