Python for Beginners 12: Nesting

This post’s heading may once again confuse you if you’re new to programming and/or not an English native speaker. It would not make sense for this series if we were going to talk about birds or pregnant women preparing for childbirth. Instead, we’re basically just going to continue the last lesson and learn about the nesting of conditional statements in Python.

In this context, nesting just means that you have one or more conditionals interwoven into one another. You can easily distinguish it from a list of ifs because a nested if is indented, i.e. the if itself is already indented. Therefore, you have to be very careful to still indent the instruction after the if and to not lose track of how many indentions you require.

Remember that indention errors were one of the three most frequent errors in conditionals? Do you know the other two? If not, I recommend you go back to the last lesson before trying the exercise.

If you are a very attentive reader, you may even remember the term nested from principle 5 of The Zen of Python, which states “Flat is better than nested.” This is actually quite obvious: As you can probably guess from all the talk about indention, nesting might make things confusing soon. So if you can separate the ifs in a way that makes sense and it is not much more work, avoid nesting.

After many exercises dealing with temperature conversion, it is time for a new topic. This time, we are going to write a program where clients can select the cheese for their pizza.

  1. First, you ask whether they want cheese.
  2. If yes – and only in this case, you give them the options mozzarella (1), gouda (2) and goat cheese (3). I recommend using numbers in brackets so your client can just type the number to select. If you want to use letters, you would have to use the data type string and it is more prone to mistakes as your client may just type capital letters, which Python would not recognize as correct.
  3. As output, you should repeat the client’s choice (e.g. You chose a pizza with gouda.).
  4. At the very end (outside of any if), you indicate the price. Each pizza costs USD 7, goat cheese costs USD 1 extra.

Of course, you could customize much more than just your cheese, but I didn’t want to make this exercise too difficult. If you want to, you can add some more ingredients.

Your result may look like this:

Congratulations, you have completed more than half of this Python for Beginners course! #mastery12

Leave a comment