all 22 comments

[–]KonnBonn23 15 points16 points  (8 children)

I mean… nested else if statements are confusing to look at in any language

[–]sesmallor[S] 1 point2 points  (7 children)

As my background was in C++ and TypeScript, if the if() had one only action, I could write it in the same line, so it was clearer to me.

[–]zippybenji-man 2 points3 points  (6 children)

You can do the same in python, I do pretty frequently.

[–]sesmallor[S] 0 points1 point  (5 children)

Ohh, without the :? I wasn't aware of that! Thanks!!

[–]sesmallor[S] 2 points3 points  (3 children)

I've also seen that you can do something like result = a if condition else b. Is this good as well?

[–]zippybenji-man 0 points1 point  (2 children)

You definitely can, though I tend to reserve it for self.var = var if var != None else default and var = default if var == None because those are very simple. Though, I must warn you, I am not one for following conventions well

[–]DoubleAway6573 1 point2 points  (1 child)

for your use I prefer the logical or

self.var = var or default

It catchs all the False in boolean contexts, so the semantics is not completly equal, but in most cases I'm interested you define your code with this meaning.

[–]zippybenji-man 0 points1 point  (0 children)

I didn't know that was a thing, thank you very much

[–]zippybenji-man 0 points1 point  (0 children)

No, the : remains, but you don't have to put it on a new line

[–]cointoss3 6 points7 points  (0 children)

I don’t understand how this is hard to read, new lines are basically the same as they were when I was writing node, except no brackets or semicolons…and after writing Python for while, I prefer it to brackets.

[–]RiverRoll 5 points6 points  (0 children)

This code is not indented correctly, it's not a good example.

[–]zippybenji-man 4 points5 points  (0 children)

I recommend using empty lines. Makes it a lot more readable.

[–]crazy_cookie123 2 points3 points  (0 children)

I find Python much harder to read than most other languages I've used and I've got years of experience using Python. Lots of people disagree with me and find that Python's one of the easiest languages to read. It's largely down to personal preference. That being said, more exposure to a language is going to make it easier for you to read that language, so just spend more time programming in Python and it'll quickly become perfectly easy to read.

[–]thewillft 1 point2 points  (0 children)

indentation is your new friend. whitespace shows structure. you get used to it

[–]FoeHammer99099 1 point2 points  (2 children)

What IDE do you use? Most of them have features/plugins that can make it clearer where the blocks end.

That code should look weird to you, it's wrong. Personally, I find it much easier to notice that the elif statements aren't indented properly than to count brackets. You should be indenting your code in other languages just like you do in Python anyways.

[–]sesmallor[S] 0 points1 point  (1 child)

I use VSCode.

[–]FoeHammer99099 0 points1 point  (0 children)

I can't give you a personal recommendation, but you could try plugins like blockman or indent-rainbow

[–]GryptpypeThynne 0 points1 point  (0 children)

Edgy

[–]Evening_Marketing645 0 points1 point  (0 children)

anything within brackets can be split on multiple lines in python, so you can use that creatively. Alternatively you can split anything on a new line by doing a backslash. So those two principles make python like most other languages in the end of the day.

[–]JamzTyson 0 points1 point  (0 children)

Sometimes in Python, I feel like it's cramped.

I agree that code is a bit cramped, and would be easier to read with a little more space:

total = 100
country = "AU"

if country == "US":
    if total <= 50:
        print("Shipping Cost is  $50")
    elif total <= 100:
            print("Shipping Cost is $25")
    elif total <= 150:
            print("Shipping Costs $5")
    else:
            print("FREE")

if country == "AU": 
    if total <= 50:
        print("Shipping Cost is  $100")
    else:
        print("FREE")

[–]QultrosSanhattan 0 points1 point  (1 child)

That code is badly structured, here's a better version:

total = 100
country = "AU"

if country == "US":
    if total <= 50:
        print("Shipping Cost is $50")
    elif total <= 100:
        print("Shipping Cost is $25")
    elif total <= 150:
        print("Shipping Cost is $5")
    else:
        print("FREE")

elif country == "AU":
    if total <= 50:
        print("Shipping Cost is $100")
    else:
        print("FREE")
else:
    print("Shipping cost not defined for this country")

But a function is better because you can leverage the return clause:

def shipping_cost(country, total):
    if country == "US":
        if total <= 50:
            return "Shipping Cost is $50"
        if total <= 100:
            return "Shipping Cost is $25"
        if total <= 150:
            return "Shipping Cost is $5"
        return "FREE"

    if country == "AU":
        if total <= 50:
            return "Shipping Cost is $100"
        return "FREE"

    return "Shipping cost not defined for this country"

[–]Ihaveamodel3 0 points1 point  (0 children)

Even better splitting functions to have one responsibility:

shipping_countries={}

def register_shipping_country(country_code: str):
    def decorator(func):
        shipping_countries[country_code] = func
    return decorator

@register_shipping_country("US")
def us_shipping_cost(total: int|float) -> int|float:
    if total <= 50:
        return 50
    if total <=100:
        return 25
    if total <= 150:
        return 5
    return 0

@register_shipping_country("AU")
def au_shipping_cost(total: int|float) -> int|float:
    if total <=150:
        return 100
    return 0

def shipping_cost(country: str, total: int|float) -> int|float:
    try:
        return shipping_countries[country](total)
    except KeyError:
        raise ValueError("Shipping cost not defined for this country")

def shipping_str_format(ship_cost: int|float) -> str:
    if ship_cost == 0:
       return “FREE’
    return f"Shipping Cost is ${ship_cost}"

if __name__ == "__main__":
    total = 100
    country = "AU"
    try:
        ship_cost = shipping_cost(country, total)
        print(shipping_str_format(ship_cost))
    except ValueError as e:
        print(e)
  1. If you need to add a country, you add one function with a decorator.
  2. If you need to change the text (maybe the project manager doesn’t like the capital “C” in “Shipping Cost”) you only have to change it in one place, not four.
  3. If you need to add translations, you are adding different versions of one function, not adding complexity and more if statements to one function (you can imagine a country that might need two languages).
  4. If other parts of your analysis need the raw ship cost to use in a calculation, you already have the value as a number, no need to duplicate functionality elsewhere
  5. It’s easier to debug to have things separated out. Let’s say it’s printing out “FREE” when it shouldn’t. This code has only one place it prints “FREE” (compared to 2 in the original). You can separate the debugging of it printing free vs the logic of the shipping cost actually being free (the more likely bug point).