I need to formulate an iteration sequence that follows the output pattern below:
0
1
2
3
4
5
6
6
7
8
However my attempts insofar are yielding an output that returns back to iteration, rather than returning to a logical sequencing:
for i in range(10):
if i==7:
i=i-1
print(i)
0
1
2
3
4
5
6
6
8
9
I feel as though I am overlooking something incredibly simple, or something that is an obvious syntactical error?!
CodePudding user response:
This is simpler
for i in range(9):
if i==7:
temp=i-1
print(temp)
print(i)
Your code is is causing you to over write your i
value.
CodePudding user response:
Maybe you could try something like this:
def print_with_condition(limit, condition):
for i in range(limit):
if condition(i):
print(i)
print(i)
print_with_condition(9, lambda x: x == 6)
The above code would produce this result:
0
1
2
3
4
5
6
6
7
8
EDIT 1
If you want a simpler approach:
for i in range(10):
if i != 9:
if i == 6:
print(i)
print(i)
CodePudding user response:
The last number is not taken into account. You need to write for i in range(9)
CodePudding user response:
In your for loop , when i=7 we temporarily make i=6 and print it. But the for loop had run till the i=7 state , hence for the next iteration 'i' will be 8 due to for loop behavior, which explains your output. You can achieve your desired output , by printing i-1 for every iteration from when i=7.
Code:
for i in range(10):
if i>=7:
print(i-1)
else:
print(i)
Output:
0
1
2
3
4
5
6
6
7
8
CodePudding user response:
Just few lines of change in your code (added print
inside if
block) gives the desired results:
for i in range(9):
if (i == 7):
print (i-1)
print (i)
OR if you still want to iterate until range(10)
, this is the code:
for i in range(10):
if (i >= 7):
print (i-1)
else:
print (i)
Output:
0
1
2
3
4
5
6
6
7
8