Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

python - How to loop in the opposite order?

I am a beginner programmer. Here is my code:

n = int(input())
from math import*
for i in range(n):
    print(n, "	", log10(n))
    i = i + 1
    n = n - 1

Its output is:

10   1.0
9    0.9542425094393249
8    0.9030899869919435
7    0.8450980400142568    
6    0.7781512503836436
5    0.6989700043360189    
4    0.6020599913279624
3    0.47712125471966244
2    0.3010299956639812
1    0.0

I want it to be:

1    0.0
2    0.3010299956639812
3    0.47712125471966244
4    0.6020599913279624
5    0.6989700043360189
.
.
.
9    0.9542425094393249
10   1.0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, you don't need to increment i, because it is the loop variable and is being set to each of 0 to 9 in turn.

Then your loop is printing n first. It starts at 10, and you subtract one from it each time, so you are getting the values in descending order. Try this:

for i in range(n):
    print i+1, "	", log10(i+1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...