I would like to write something which looks a bit like what I currently have in the following definition:
def rounding( sp1, sp2, sp3, sp4 ):
if () <= 700.:
elif () <= 1000.:
elif () <= 10000.:
elif () > 10000.:
return [ sp1, sp2, sp3, sp4 ]
I am really a beginner to all of this and I've probably made some horrendous mistakes in the above code. What I basically have is previously calculated these 4 values sp1, sp2 etc. I then want to be able to round these values all at the same time but depending on their individual value, they must be rounded by different amounts.
If 'sp' <= 700 : rounded to nearest 10
700 < sp <= 1000 : rounded to nearest 50
1000 < sp <= 10000 : rounded to nearest 100
10000 < sp : rounded to nearest 1000. (not code)
If something could help me I would be very grateful, thank you!
The tricky part is rounding to the nearest 50. That can be achieved by doubling the number, then rounding to the nearest 100, then halving the number again. At least that's the easiest way I can think of.
def nearest_50(n): return round(n*2, -2)/2
As for the rest, your code is not that far away from a correct solution. As Ignacio suggested, you should only round one value at a time
def my_round(n): if n <= 700: return round(n, -1) elif n <= 1000: return nearest_50(n) elif n <= 10000: return round(n, -2) else: return round(n, -3)
Then round a list of numbers like this
mylist = [... some numbers ...] rounded = [my_round(n) for n in mylist]
Write a function that rounds a single value, then use a list comprehension to pass all the values through it one at a time.