im learning Python and im trying to come up with a for loop (or any other method) that can return multiples of 100 but rounded to the nearest thousand, here's what i have right now:
huneds = [h * 100 for h in range(1,50)]
for r in huneds:
if r % 3 == float:
print(r)
else:
break
CodePudding user response:
The built-in round()
function will accept a negative number that you can use to round to thousands:
for r in huneds:
print(round(r, -3))
Which prints:
0
0
0
0
0
1000
1000
1000
1000
1000
1000
1000
1000
1000
2000
...
4000
4000
5000
5000
5000
5000
CodePudding user response:
You can see use
for n in range(0,2500,100):
print(n, ' -> ',1000 * round(n / 1000))
CodePudding user response:
For any number m
, m
is a multiple of n
if the remainder of n / m
is 0
. I.e. n % m == 0
or in your case; r % 100 == 0
, as the modulus operator (%
) returns the remainder of a division. Use:
for r in huneds:
if r % 100 == 0:
print(r)
But every number is already a multiple of 100
, as you multiplied all of them by 100
.
You may be after something like:
# Range uses (start, stop, step) params
# print(list(range(0, 200, 10))) --> [0, 10, 20, ... 170, 180, 190]
for r in range(0, 200, 10):
if r % 100 == 0 and r != 0:
print(r)
Outputs
100
But you would like to round to the nearest 1000
. The round()
function can do that.
for r in range(0, 2000, 10):
if r % 100 == 0 and r != 0:
print(f"{r} | {round(r, -3)}")
100 | 0
200 | 0
300 | 0
400 | 0
500 | 0
600 | 1000
700 | 1000
800 | 1000
...
- The
f
string does the same asr ' | ' round(r, -3)
- This shows the number that is a multiple of
100
which isr
, and then it rounded to the nearest1000
- This shows the number that is a multiple of
round()
's second argument is the amount of digits to round too, as we are going to the nearest1000
, we use-3
as you are going on the left side of the decimal
I suggest having a read of:
And I highly reccomend: this site (python principles) for learning python. Pro membership is currently free
CodePudding user response:
Simply do this,
list(map(lambda x: round(x/1000) * 1000, huneds))
It'll return you a list of rounded values for all the items of the list huneds
.