r/learnpython • u/[deleted] • May 13 '17
What's the Python way of doing: while (x /= 10):
What's the Python way of doing:
while (x /= 10):For the above the Python compiler gives:
SyntaxError: invalid syntaxWhat I want to do is that the x /= 10 should do:
x /= 10and then evaluate x through bool to decide for the while-statement.
6
u/Derp07 May 13 '17
Has anybody successfully answered your question?
If not, perhaps explain what your code is actually trying to accomplish, as opposed to what you think it should be doing?
-7
4
u/dionys May 13 '17
It's
while x != 10:-4
May 13 '17
Nope that's not what I'm asking. What the code should do is x /= 10 and then x evaluates to 0 if x == 0 and 1 if x is some other integer value. Try bool(someint) to see this.
7
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 May 13 '17
So let me get this straight; you just want the loop to continue as long as x is not 0?
If that's the case:
while x: #whatever-3
May 13 '17 edited May 13 '17
Yeah, or I also figured that I could do:
while True: x /= 10 if not x: breakYour answer also suits.
10
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 May 13 '17
Also, what exactly are you trying to accomplish with this? I could give better answers if I knew the problem you were trying to solve. ;)
7
u/NSNick May 13 '17
Why not use what Diapolo said?
while x: x /= 10 # whatever other stuff1
u/thatguy_314 def __init__(ely) May 13 '17
If it matters, that is a bit different as on the last loop the
other stuffwill get a0.0.1
u/NSNick May 13 '17
This is true, the
#other stuffshould be moved to before the assignment line if that's not intended.1
u/thatguy_314 def __init__(ely) May 13 '17
Yeah, but then you would get the value prior to the first division.
1
u/thatguy_314 def __init__(ely) May 13 '17
From there, you can also make it into a generator function if you want:
def divide_by_10_a_bunch(x): while True: x /= 10 if not x: break yield xThen you can do
for x in divide_by_10_a_bunch(100): ...Using a generator like this lets the loop where you are actually doing stuff be cleaner as you can see.
But, echoing what others have said, why are you trying to do this? Mathematically, it seems a bit weird, as the loop only stops because of the limited precision of floats.
1
1
8
u/zemuse_sound May 13 '17 edited May 13 '17
I think you are after the modulus operator: