Git Product home page Git Product logo

Comments (3)

ehmatthes avatar ehmatthes commented on July 29, 2024

Hi. This isn't really a scope issue, it's more a matter of how we're modeling the possible battery sizes for the car. Here's the get_range() method I've shown:

    def get_range(self):
        """Print a statement about the range this battery provides."""
        if self.battery_size == 40:
            range = 150
        elif self.battery_size == 65:
            range = 225

        print(f"This car can go about {range} miles on a full charge.")

First, range is a local variable here, because it's only used to report the range from this method. If you want to make it an attribute by attaching it to self, that's perfectly reasonable. But the main thing to see here is the structure of the conditional block. We only have an if-elif chain. There are only two battery sizes that work for this car: 40kWh and 65kWh.

I'm guessing your updgrade_battery() method included an option to upgrade to 100kWh. In that case, you would have to add an additional elif block to get_range() to report the range for that battery.

The main thing I don't like about initializing range to 0 is that it's not really meaningful. Electric cars with a functioning battery don't have a range of 0. If the owner has upgraded the battery to a size that's not recognized, the range would be unknown, not 0. That would be implemented by adding an else block that reports an unrecognized battery size.

Looking at this example again, an interesting solution gets away from if blocks. We could use a dictionary for this method:

    def get_range(self):
        """Print a statement about the range this battery provides."""

        # battery_ranges = {battery_size: range}
        battery_ranges = {
            40: 150,
            65: 225
        }

        range = battery_ranges[self.battery_size]
        print(f"This car can go about {range} miles on a full charge.")

I wouldn't say this is better or worse than the if-block approach. Some people like conditional statements, others prefer dictionary lookups. With a long set of options, the dictionary approach is probably better. Adding support for a new battery is as simple as adding a single new entry in the dictionary.

One last note; if you're staying with the conditional approach, it's good to use if-elif-else when only one of the conditions can be true. In that structure the blocks stop executing as soon as the correct match is found. In a series of simple if blocks, every check is made even if the correct one has already been found.

Does that help?

from pcc_3e.

svenikea avatar svenikea commented on July 29, 2024

Hi Eric,

Thank you for your wonderful analysis, yes of course using a dictionary in this scenario is wayyy better. And you were right I don't know why I declared range = 0 in the first place it doesn't mean anything when we are trying to model a real-world object using class.

Sorry for wasting your time.

from pcc_3e.

ehmatthes avatar ehmatthes commented on July 29, 2024

This wasn't a waste at all, it's a really interesting question that comes up when you implement an upgrade option that doesn't match what was originally written. I write a weekly newsletter about Python, and I'm going to write a post about some of the things this question raises.

I wrote this example years ago, and this is the first time I've thought to use a dictionary for the range lookup. I grew up on if statements, and didn't come across dictionaries until I started learning Python. I'm just starting to use them in place of short if-elif-else blocks.

Thanks again for reaching out!

from pcc_3e.

Related Issues (9)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.