Let’s Id like to assign result of 9/2 to var x. However I want to round it down.
so I did int(x) = 9/2, however it doesn’t work. How should I write it down?
better if you don’t involve floats and stick to integer operations
Just use the built-in
round() function (documentation here).
x = round(9 / 2)
That’s like converting a string to a word document and back just to convert it to lower case. (from int to float and back to float again, and float is a more complicated type than int)
The current type already supports division, this is an exact operation, there shouldn’t be rounding! Rounding suggests that there’s an error or approximation involved. There isn’t.
Fair. They asked about rounding though, so that’s the answer I gave. If they want plain integer division then they can always use the ol’
>>> 9 // 2 4
Hey, thanks for answers guys.
So how can I round always to lower value?
Tha’s exactly what floor division // is for.
a = 9 // 10 # effectively 0.9 print(a) Out: 0
You can also have a look at the math module which has a few methods of this, e.g. math.floor().
Thanks for answer. I went little bit far, I used math.floor and that seems to be fine, but I receive some error. Do You know what is wrong with that? Thank You
Check the error, there’s a problem with the indexing.
You have more than one use of a list index that uses division. If this is Python3 division will return a float.
can I not divide list index more than once? Why does list mustn’t return float? And if it cannot how can I make it right? Thanks
floats are approximations, indices are exact
you should not be approximating when doing exact computations
there should not be any floats anywhere, if you have to round at all, then it’s already wrong
stick to integer operations
so rather than patching up the mistake with bubblegum, fix the mistake
Forgive for my lack of knowledge, but Im not sure how to stick to integers. I need to receive index of the middle index. How can I do it without rounding?
use integer division, two integers go in, one integer comes out
you’ve probably done this in school, you’d get a quotient and a remainder, no approximation was involved
float does not match anything you’ve done in school. it’s very often not at all what you want
but if im gonna divide perhaps 7/2, value is always gonna be float innit?
if im gonna use function len(list) and assign it to the variable X, is this X going to be float or integer?
len returns an integer, a variable does not affect that, a variable just holds on to a reference to whatever you point it at
integer division has been shown more than once in this thread, and is googleable