I’m trying to learn Python from a background in javascript. I saw someone make a recursive function to find the least common denominator and wondered why they didn’t just use a loop, so, both for the experience and to amuse myself, I wrote a simpler one:
I came up with:
def LCM(n,d):
while(n%d++ != 0 ):
continue
return d-1
print(LCM(99,12))
Needless to say, for those of you that know Python, ++ isn’t a valid operator. I also tried
def LCM(n,d):
while(n%(d+=1) != 0 ):
continue
return d-1
print(LCM(99,12))
To make sure it wasn’t my thinking that was off, I tried the same thing in javascript:
function LCM(b,d){
while(b%d++ != 0){
}
return d-1;
}
So does Python not allow expressions like in javascript? Also, is indentation the only way to define something? I know semicolons aren’t required but can be used, is there anything like that in terms of closing a loop or function definition?
Finally, are is and is not the Python equality-without-type-coersion operator?
P.S. I realize the function isn’t practical without checking the input for various things, but that wasn’t the point in writing it.
P.P.S Also, is there a Python equivalent of the javascript evaluation ? on true : on false if statement abbreviation?
Python does not allow assignments (such as
i+=1) in expressions since those can lead to confusing code, and Python is designed to make it hard to write confusing code, and make it simple to write obvious code.You can simply write this:
Python’s
istests for two objects being the same object instead of just equal. Consider the following:There is no equivalent operator to
isin JavaScript, and there is no equivalent to JavaScript’s==in Python. Python’s==does type checking for the built-in types.The conditional operator (
a ? b : cin JavaScript) is written out in Python as: