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, '\t', log10(n)) i = i + 1 n = n - 1 Its output is: 10 1.
Solution 1:
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, "\t", log10(i+1)
Solution 2:
Just use i
as you variable element in the loop:
n=int(input())
import mathfor i in range(1,n+1):
print(i,"\t",math.log10(i))
You can do this in one line like so:
print('\n'.join('{}\t{}'.format(i,math.log10(i)) for i in range(1,n+1)))
Lastly, it is not a great idea to get used to doing from math import *
. Using *
brings all the items in the imported module into the same namespace. Any similar object or function names in the module will overwrite other functions/objects with the same name.
Post a Comment for "How To Loop In The Opposite Order?"