Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Few Python questions

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?

like image 431
mowwwalker Avatar asked Feb 22 '23 23:02

mowwwalker


1 Answers

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:

def LCM(n,d):
    while n%d != 0:
        d += 1
    return d-1
print(LCM(99,12))

Python's is tests for two objects being the same object instead of just equal. Consider the following:

d = {}
e = d
assert d == {}     # Empty dictionaries equal each other
assert d is not {} # .. but are not identical
assert d is e      # d and e refer to the same object

There is no equivalent operator to is in 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 : c in JavaScript) is written out in Python as:

 b if a else c
like image 129
phihag Avatar answered Feb 25 '23 15:02

phihag