yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

Calculating weights on Mars with if-elif-else | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

Let's design a program with chain conditionals. We want to build a program that calculates an object's weight on different planets. We have the formula for this already: weight equals mass times gravity.

So, if we know an object's weight on Earth, we can divide by Earth's gravity to get the mass. Then, once we have the mass, we can just multiply by the gravitational force of whatever planet we're interested in. Our starter code here calculates an object's weight on Mars. We take the gravitational force on Mars, which is 3.7 m/s².

Then we ask for the weight of the object on Earth and plug those two numbers into our formula to get the weight on Mars. I'm thinking I want to round this number, though, so it's a bit easier for the user to look at. There's definitely a built-in function for this.

Okay, looks like it's just called round, and it takes two arguments: the number to be rounded and the number of decimal places to round to. That's looking a lot cleaner now. I want to make this work for other planets too, not just Mars.

So, we're going to want an input function call that asks the user to enter a planet name. We'll assign that to the variable planet and then use a conditional to assign the value of gravity. Let's start with the Mars case that we already had before. Before I start my conditional, I want to make sure to initialize my variable gravity to a default value. Let's say zero here; that probably makes sense.

We'll want our condition to be planet == "Mars." If this evaluates to true, then we want to set gravity to 3.7, which is the gravitational force on Mars. So, we indent that assignment statement inside that if branch. There are a lot of planets, so let's just start with a few of them. We'll do Mars, Mercury, Venus, and Jupiter.

Mercury's gravitational force is also 3.7, so we can just use the or operator to turn this into a compound condition that checks if the planet is Mars or Mercury. Next, we want to check if the planet equals Venus. This is related to the previous condition and is mutually exclusive with it; the planet can't both be Mars and Venus. So, it makes sense to use an elif branch here.

If the planet == "Venus," then we want to set gravity to Venus's gravitational force. Then we have the Jupiter case, which is another branch. Now, let's test that conditional. If I enter Mars, it's giving the same weight that I had before, so that must be correct.

Mercury should give the same answer, and then Venus's gravitational force is bigger, so its weight should be bigger. Jupiter should be even bigger still. Oh wait, that's a zero. Maybe that means gravity still has this default value zero when we do the calculation, and maybe this branch isn't actually executing.

Let me test that hypothesis by adding some temporary debugging print statements. I'll add one inside this Jupiter elif branch so I can see if this branch is actually getting executed. Then maybe I'll print down here what the value of gravity is right before I calculate the weight.

Interesting, so it is hitting that branch because it's executing this print statement, and it says that the value of gravity is zero. That's bizarre because if it's executing this branch, it should be executing this assignment statement, which means gravity should be 23.1.

Oh wait, I see the bug. I used the equality operator, not the assignment operator, so this is checking if gravity == 23.1 instead of assigning 23.1 to gravity. Okay, but I need to go in and clean up those debugging print statements.

I don't want my users to see them. What do we want to happen if they enter something that's not a planet at all, or is a typo, or is a planet we just don't support yet? This case is a catchall; it's any string that's not Mars, Mercury, Venus, or Jupiter, which could be any of infinite possibilities.

So, we can't really express that with a separate condition; we need an else branch. Let's just give the user an informative error message and tell them that we don't recognize that planet name. So, we make sure to indent this print statement inside the else branch.

Let's test that else case. It prints "unrecognized planet," but then it prints it would weigh zero kilograms on potato. If the user enters an unrecognized planet, I don't want to print out what it would weigh because it doesn't make sense.

Actually thinking about it, I don't need to do any of these calculations at all. I don't even need to ask them what the weight on Earth is because I'm not going to do anything with it. So, if I want to skip all these lines of code, I'm going to need another conditional.

I don't want to chain it with the existing conditional because it's not mutually exclusive with all those cases. It should run if the planet is Mars, Mercury, Venus, or Jupiter. So, we use an if to start a new conditional, and then I want to indent all of these lines of code inside it.

What should my condition be, though? How do I know if I was in the else case before? Well, if none of these three branches executed, then the value of gravity would still be zero. So I can have this condition be if gravity != 0. But I can actually use a shortcut here because zero cast to a Boolean is false, and any other float cast to a Boolean is true.

So, I can just shorten this condition to if gravity, which checks that gravity has some value that's not zero. Now if I enter some unrecognized planet name, it just gives me that error message and then skips all of the calculations.

Break time! I'm going to add a quick comment here so I remember where to pick up later. I'll note down the gravitational forces of the remaining planets in case you want to give it a try.

More Articles

View All
Farming for the Planet | Podcast | Overheard at National Geographic
[Music] I’m going to tell you about this place that 10 years ago didn’t even exist. And what created this wasn’t brilliance; it was freedom to allow nature to show us a better way. That’s exactly how my wife Molly and I rebuilt this whole farm over the la…
Robert Thurman: Love Your Enemy | Big Think
The Buddhist psychology tradition, in particular, and the Asian psychologies in general, and actually the ancient Christian monastic psychologies do have a strong theory and a strong practice really of overcoming bitterness, hatred, resentment, vengefulne…
Coexisting With the Lions of Botswana | National Geographic
[Music] Lions are an iconic species of Africa, and to have the opportunity to work in a wild place like this and to actually be able to make a difference, it’s hard to describe how important it is to me. In northern Botswana, lions move out of the delta …
Marcus Aurelius and the Guiding Principles of Stoicism
In the year 165 CE, a black wave of death rose from the East and quickly spurred across the globe faster than anyone could have ever imagined. They called it the Antonine Plague after the reigning Roman Emperor at the time, Caesar Marcus Aurelius Antoninu…
Interpreting expressions with multiple variables: Cylinder | Modeling | Algebra 2 | Khan Academy
We’re told that given the height h and volume v of a certain cylinder, Jill uses the formula ( r ) is equal to the square root of ( \frac{v}{\pi h} ) to compute its radius to be 20 meters. If a second cylinder has the same volume as the first but is 100 t…
15 Investments You’ll Regret Not Making Today (20 Years from Now)
20 years ago. You should have invested in Amazon but didn’t. $10,000 invested in Amazon. That would have been $1.8 million today. You’ve seen these stories before. 15 years ago, you should have bought a cheap apartment or house but didn’t. Property prices…