Python for Beginners 20: Dictionaries

This final lesson of the Python for Beginners series deals with another sequence-based data type: dictionaries. Allen B. Downey from Think Python even calls it “one of Python’s best features”.

Dictionaries are basically lists with the feature that each value is not referenced by an integer index, but by a key that can be of any (immutable) data type. As there is now a nearly infinite number of potential keys, we need to specify them when entering new values and each key must be associated with a single value. This association is called a key-value pair or sometimes an item. We say that each key “maps to” a value.

A dictionary is surrounded by squiggly brackets {}, with the individual key-value pairs being separated by commas, just like lists. Every key-value pair has a colon between the key and value. To create a new dictionary, you can just follow this syntax. Alternatively, you can create an empty one using the function dict() and then add items afterwards.

Adding items to a dictionary works just like replacing elements in a list:
myList[5] = ‘green’
myDict[‘one’] = ‘uno’

The difference is, of course, as previously mentioned, that you use a key instead of an index. What might be a bit surprising, is the fact that there is no fixed order in a dictionary. Every time you print it, the order may be different. However, as we use keys to reference the values, this does not constitute a problem.

Operations with sequence-based data types that work with dictionaries

  • the function len() returns the number of key-value pairs
  • the in operator returns True if something appears as a key in the dictionary
  • the function sorted() returns the key-value pairs in (numerical/alphabetical) order

Methods that only work with dictionaries

  • .get(key, default value): If the key appears in the dictionary, it returns the corresponding value; otherwise it returns the default value.
  • .values(): returns a collection of all the values that appear in a dictionary (you can combine it with the in operator to see whether something appears as a value in a dictionary)

When to use a dictionary?

Besides the obvious application (use a dictionary when you want to create a dictionary), there are some other cases when using the data type dictionary can be handy.

  • If you want to count several elements, for instance how often a letter appears within a sentence, you can create a dictionary with characters as keys and counters as the corresponding values.
  • Unlike lists, Python dictionaries use a data structure called a hashtable. Thus, whereas searching takes more and more time as lists grow longer, there is basically no change for dictionaries, independently from how many items they contain.
  • To improve the speed of your program, you can also store previously calculated values in dictionaries as memos.

If you want to learn more about dictionaries or about learning programming with Python, I recommend once again Allen B. Downey’s Think Python, which also inspired this post.
#mastery20

Python for Beginners 19: Validating User Input

As we’re getting to the end of our “Python for Beginners” series, we’re finally going to learn how to validate user input, i.e. how to make sure that the input corresponds to what you anticipated and that you can use it in your program.

There are basically two things that you need to validate:

  1. Does the user input have the right data type?
  2. What values can the user input take? Does a string have the correct length or is a number in the right range?

1. Does the user input have the right data type?

You may remember from previous lessons that if not indicated otherwise, user input will be considered to be in the data format of strings. Even though we have discussed the usefulness of strings just recently, there are going to be many cases when we are going to need a different data type, which is why we often converted the user input using the data type functions such as int() to take the input as an integer or float() for floating-point numbers. Considering our new knowledge on sequence-based data types such as lists and tuples, we have even more options. However, using these data type conversion functions may produce errors and stop the program, for instance if you enter a decimal number as data type integer. This is simply not going to work.

2. What values can the user input take?

To make sure that our user input does not take any values that lead to errors in our program, you should define the range of potential values of a number or the length of a string. To do this, you can just use functions that you already know such as range([start],stop) or len(string). But what should you do when the entered value is invalid?

How to implement validation

To validate the two aspects that we’ve just discussed (data type and values), you can use different methods. Usually, you either use a flag or an exception. A flag is basically a variable that changes from True to False or vice versa when the value is valid, thus allowing you to leave a while loop that otherwise keeps asking for a new entry.

Let’s do a quick example: We want to know the user’s age. We do not only want to make sure they are older than 18, but we also want a plausible entry, i.e. no more than 122 (highest age that a human being has ever reached and that was verified).

Using what we already know, we can just define the input as an integer. Then we set the allowed range and using a loop we ensure that the program continues even if there is an invalid entry.

This program is going to ask again and again for the age as long as the input is an invalid integer. However, if the input is not an integer, you get an error message from the console and the program stops executing. To avoid this, you can use the exception method that you can learn from Easy Python Docs.
#mastery19

Python for Beginners 18: Lists and Tuples

In this lesson, we are going to transfer our knowledge on operations we can do with strings to new sequence-based data types, namely lists and tuples. Both are, like the name list indicates, an enumeration of elements.

Let’s look at an example for each of them:

  • To create a list, you can simply enclose the elements in square brackets ([]). You can also create an empty list without any elements using empty brackets, [].
    myFirstList = [a, 3, “red”]
  • A tuple (pronounced like it rhymes either with “supple” or with “quadruple”) does not require brackets, but may have a round brackets and it is going to be shown in round brackets when you print it.
    myFirstTuple = a, 3, “red” To create one with a single element, you have to include a final comma (to distinguish it from being a “normal”, non-sequential variable).

Overview of sequence-based data types: lists, tuples, strings

As the sequence-based data types can seem quite similar, it’s useful to compare them.

To break a string into individual letters and convert it into a list or a tuple, you can use the list or the tuple function, respectively.

Particularities of operations with lists and tuples

The 4 general operations mentioned in the lesson on strings also work for lists and tuples: You can access elements with the bracket operator, you can use the slice operator and you can do a traversal. However, there are some peculiarities.

For the relational operators there are two things to keep in mind:

  • With lists or tuples, bigger (>) and smaller (<) are considered as “bigger or equal” (>=) and “smaller or equal” (<=), respectively.
  • Subsequent elements in a position are not considered, i.e. if one list has a 1 as an element and the other list has 10 in the position, the result would be True, because Python considers the 1 as the first element of this position and ignores the subsequent 0.

useful methods for lists:

list methods:

  • lst.append() to add elements to the end of lst
  • lst.extend(lst2) to append all of the elements of lst2 to lst
  • lst.sort() arranges the elements of lst from low to high or in alphabetical order

Most list methods are void; they modify the list and return None. Thus, they are not valid for tuples, which cannot be modified.

string methods that involve lists:

  • string_name.split([delimiter]): converts a string into a list of words, the optional argument called a delimiter specifies which characters to use as word boundaries (default: blank space)
  • delimiter.join(list_name): takes a list of strings and concatenates the elements based on the delimiter

more useful functions

  • sum(lst) to add up the elements of a list (only possible if of the same type)
  • sorted(seq): takes a sequence and returns a new list with the same elements in sorted order
  • reversed(seq): takes a sequence and returns an iterator that traverses the list in reverse order

3 ways to delete elements from a list

  • lst.pop(index): deletes the element in the position of the index from the list and returns it → if you don’t indicate an index, the default is the last element
  • del lst[index]: deletes the element in the position of the index (or a slice of indices) from the list
  • lst.remove(element): deletes the element from the list and returns None

Which sequence to choose: lists vs. tuples?

As lists are mutable, they are more common than tuples. However, in some cases, it’s better to use tuples, for instance, because …

  • … tuple assignment makes it possible to swap the values of two variables without using a temporary variable or to use the split method to separate a sequence and assign the parts to a tuple
    a, b = b, a
  • … a function can only return one value, but it can be a tuple, so basically, it’s like returning multiple values

Example exercise

Create a program that asks the user for a certain amount of numbers (floating point). Store those numbers in a list. Show to the user the total, average and standard deviation of those numbers.
At the end, convert your list into a tuple.

This is what the result could look like.

If you want to learn more, I recommend once again Allen B. Downey’s Think Python, whose chapters on lists and tuples also inspired this post.

#mastery17

Python for Beginners 17: Strings

In this lesson, we are going to learn about strings. You might think that you already know everything about them, but this is certainly not true. So far, we know that input is automatically converted into strings if we don’t indicate otherwise and that we need to use quotation marks if we want to print strings. Maybe you even remember that to convert another data type into string, you can use the function str().

But there is much more we can do and it is important to know it, as strings are the data type to represent human language, so you are likely to get lots of input in this format and of course you are going to want to work with it. So read carefully the theory to be able to solve the mini-exercise at the end. Besides learning about strings, this lesson teaches you operations that are not only valid for strings, but also for other kinds of sequence-based data types. We are going to learn more about them in the next lesson.

Operations for sequence-based data types

  • built-in function len():returns the length of a sequence, i.e. the number of characters in a string or, more generally speaking, the number of elements in a sequence
  • the + operator to concatenate sequences: creates a new sequence by combining others
  • the * operator to repeat a sequence a given number of times
  • bracket operator to index an element: You can access individual elements using the index. An index is the number of the position of the element in a sequence.
    • To access it, you write the number of the position in square brackets [] after the list’s name.
    • You count the position starting from 0 for the first element – just like the range() function. For example, to access the fifth element, you write list_name[4].
    • The index needs to be an integer, but you can define it using numbers and variables.
    • You can also use negative indices. They will start counting from the end, for instance, the index -1 will show you the last element.
  • slice operator to select a segment of a string, i.e. a range of elements:
    • Just like when you access or select a character, you indicate the position of the first element you want to include and connect it with a colon to the position of the element after the last one that you want to include. Again, this is just like using the range() function.
      Example: myString[4:7] returns the part of the string called myString from the fifth character to the seventh character. You might think that this contradicts what I just explained (including the first, but excluding the last element), but remember that this is due to the way we count in programming, i.e. starting from 0.
    • If the first index is greater than or equal to the second the result is an empty string.
    • If you leave blank either the beginning or the end of the slice operator, Python replaces the missing value either by the first or the last position, respectively. Thus, if you leave blank both of them (string_name[:]), you get the whole string.
  • relational operators to compare two sequences: bigger (>), smaller (<) and equal (==) allow for comparisons and Python will return either a True or a False as a result.
    For sequences, the response is only True if it is true for all elements included in the comparison. For instance (0, 1, 2) < (1, 3, 4) would be True.
    For strings, bigger and smaller refers to the position of the word in the alphabet. A word that is considered “bigger” comes later in the alphabetical order. However, you need to be careful, as Python puts all the uppercase letters before all the lowercase letters.
  • traversal (= processing a sequence one element at a time):  Using a for or a while loop, a program starts from some point, selects each character in turn, does something to it, and continues until the end. This can be very useful, for instance if you want to count something and or spell a string.

Particularities of strings

  • immutable: You cannot change a string. Nevertheless, you can replace it with a string with the same name that contains the changed element. Basically, you cannot use the index operator to change an element, but you can construct a new string (even with the same name) using the slice operator. For instance, writing word = word[0:2] + “z” + word[3:] replaces the current position 2 (third letter) with a z.
  • string methods: For strings, you have the possibility to use in-built methods, similar to functions. Their syntax is different from functions, though: You write the name of your string followed by a point and then the name of the method ending with round brackets (). If the method requires additional information, you enter it as an argument in the brackets. With functions, we say that we are calling them and for methods, we are invoking the method on the string.
    Examples:
    • string_name.isupper(): returns true if all letters of the string are uppercase letters
    • string_name.upper() or string_name.capitalize(): converts all letters of the string into uppercase letters
    • string_name.find(‘letter’): searches for the letter or substring that you put as the first argument (needs to be inside single quotation marks) and returns the position where it (first) appears (additionally, you can determine the beginning and/or the end of the search by entering it as the second or third argument, respectively)
    • string1 in string2: The word in is a boolean operator that takes two strings and returns True if string1 appears as a substring in string2. You can also use this to define a function that tells you which letters appear in both strings.

Mini-Exercise: Ask your user to give you a random word.

  • What are two ways you could print ONLY the last letter of the word?
  • How would you print all letters (one per line)?
  • Count how many times a certain letter appears in the word.
  • Search a string for a particular letter: In which position does it appear for the first time? Find two ways to do it.
  • Bonus question: How could you reverse the letters, i.e. print the word starting with the last one (example: small → llams)? Hint: you can use this formula t = s[∷-1].

Your solution might look like this:

For more details and longer explanations you can look at Allen B. Downey’s Think Python, which also inspired this post. #mastery18

Python for Beginners 16: Which repetition?

This lesson concludes the three previous lessons on repetition methods. Now that we know how to use both while and for loops as well as recursion, we need to decide which method to use in which case. In the lesson about for, we have already discussed when to use which loop so this lesson is going to focus on when to choose recursion over iteration (loops). Nevertheless, we are still going to look at examples for both for and while loops, just to deepen our understanding.

Today’s example problem is generating factorials. A factorial n! is defined as the product of n and the factorial of the previous integer, (n-1)!, with the factorial of 0, 0!, being equal to 1.

Maybe you noticed that this definition is indeed recursive. So let’s try to write a program:

Alternatively, you can use a for or a while loop:


Comparison: Which program works best for factorial?

Obviously, the result of all three programs must be the same. Otherwise, we would know that we made a mistake. Let’s compare how each program performs in the categories “efficient” and “easy to use”.

  • For efficiency, we just look at the amount of lines required, even though efficiency is much more than that. The reason is that for such a short and small problem the differences in execution are negligible. To define the factorial function, we needed 6 lines with recursion, 7 with the while loop and just 5 when using the for loop. Thus, the for loop wins here.
  •  “Easy to use” depends obviously on your personal preferences, but since the definition for factorials is recursive, it might be intuitive to do a program with recursion. However, if you prefer loops, these might be easier for you.

What I want you to see from this comparison, is that there is hardly ever going to be a clear winner, but rather it depends on the problem and your preferences.

But generally speaking, which repetition is better?

Still, the answer is, “It depends.” Depending on the case, one repetition may be easier to read and to understand than the other. Generally speaking, recursion tends to be shorter, but it may become slow and inefficient if the numbers used are very large – but there are ways to reduce this problem. If you want to see these pros and cons in direct contrast, you can look at Programiz.

Furthermore, there are cases when recursion can be quicker. For instance, if you want to sort a list, you can do a recursion that keeps dividing the lists into two lists of the same size and then merges these one-unit lists until you get a final sorted list. This is much quicker and thus more effective than an iterative solution that always looks for the minimum.

Fun fact: Actually, there is a fourth way to solve this problem and we have already learned it: You could just use the function math.factorial(n). If you don’t remember how to do this, you can go back to the lesson on importing functions. #mastery16

Python for Beginners 15: Recursion

In the previous lessons, we learned how to use while or for loops to repeat a part of our code. This type of repetition is called iteration, derived from the Latin verb for walking, because it just walks through your code over and over and executes it each time – until the halting condition applies. Besides iteration, programs also use recursion to perform repetitions.


What is recursion?

A recursive function is a function that contains a reference to itself, i.e. it calls upon itself. If it does not contain a valid halting condition, it may run infinitely. As this is usually not the goal, almost all recursive functions modify a variable before calling themselves again so at some point, the halting condition enters into force and the repetition stops.


How does it work?

Let’s use a simple example to illustrate recursion. You want to write a series of integers from a starting number (a) to a final number (z). How could you solve this? Assume you have never heard of while or for loops.

What you can do is define a function and call it for instance count. The function distinguishes between two cases:
a) a is equal to [or bigger than] z: the functions prints z
[Including the option of a being bigger than z prevents that the program runs forever because by incrementing a bigger value (a) by 1, it will never become equal to the smaller value (z). This is actually not really related to recursion but to conditionals. Alternatively, you could do a separate case for a bigger than z or just change the order of the conditions and define b and use an all-encompassing “else” for a]
→ This is the halting condition.
b) a is smaller than z: the function prints a and calls upon itself, but the variable a is replaced by a+1

Try to put the code together using your knowledge from previous lessons and it might look like this:

When you run your program (remember that defining a function is not enough, you need to use it to see results), you should get the desired result, for instance for a = 3 and z = 10:


When to use recursion?

As I said in the beginning, recursion is just another way to perform repetitions. In some cases, recursion is just easier to read or to implement than iteration like while or for loops. Other programing languages do not even have iteration so they rely on recursion. For you, as someone who is learning Python, it is important to know that recursion exists and how to use it, but you are probably not going to use it frequently.

For more detailed information, I recommend looking at Think Python by Allen B. Downey.

#mastery15

Python for Beginners 14: For

To understand this lesson, I highly recommend you go back to the previous one on while loops if you don’t remember it well. The reason for this is that the for loop that we are learning now is quite similar to the second way of implementing while, i.e. the case in which you know how many times you want to repeat a process. In this case, you can replace a while loop by a for loop. Actually, a for loop might be better in this case, whereas while is mainly for scenarios in which you don’t know the number of repetitions or if you want to check a condition before each iteration.

There are only two differences:

  • the counter: You don’t need to initialize the counter or define it as adding one for every repetition. The for loop does all that automatically. You just use a random name for the counter, which is part of the for syntax. Basically, you have no explicit counter, just an implicit one.
  • the syntax: for + counter + in + range(number1,number2,step):
    indention in the next line

The overall syntax (colon, indention) should look quite familiar, as it is basically the same as for while or if. What is new is having two words (for … in) as part of the syntax in one single line. The range is not officially part of the syntax, but it is used in almost all cases when you use a for loop in combination with numbers.

The function range() has some particularities:

  • The first number is inclusive, the second one exclusive. This means that the first number is part of the range, but the second is not so the range ends one step before reaching the second number.
  • You can also write range(number2), in which case Python is going to set number 1 as 0.

Both of these aspects are important to know, but since Python starts at 0, but ends one number early, in sum, it does not have any implications for our pizza example. If you don’t indicate the step, Python is just going to assume that the step is equal to 1.

Based on this short introduction, you can simply convert the while loop from our pizza example (important: the second one, where we know the number of repetitions) into a for loop.

Your solution might look like this:

The only thing you have to do is delete the lines 2 and 5 (I put them inside of ‘’’ to comment them out) and to change line 4 from while syntax to for, setting a random variable (here: num_pizzas) as the counter and using the amount of pizzas ordered (here: variable order_pizzas) as the range.

If you feel like you need some more time to familiarize yourself with for loops – like I did in the beginning, I recommend this great tutorial by Digital Ocean. Other helpful resourcs are the wiki for Python and/or Tutorials Point. Of course, you can also ask questions in the comments below. #mastery14

Python for Beginners 13: While

In this lesson, we are finally going to learn about the while loop. Why finally? Remember our example of customized pizza cheese from the last lesson?

So far, our program can only take one single order. What if we want to give our customer the possibility to order more than one pizza? For this, we would need to execute our program several times. To avoid this, we can just create a loop, i.e. we include a part in the code that repeats the ordering process.

There are two ways to do it:

a) We don’t know how many pizzas our customers want so we just ask again after each order.
b) We know how many pizzas our customers will order beforehand, for instance because we asked them at the beginning, or we determine an amount of pizzas that has to be ordered.

If we want to know the final price to pay at the end, we need to create a variable called for instance final_price. This variable is a so-called accumulator because in it, we are going to accumulate the cost of all the pizzas we order.

  1. We set the accumulator (here: final_price) to 0.
  2. Inside the while loop (we’ll get into detail later), you define the accumulator as itself increased by whatever variable you want to accumulate inside. In our case, this means final_price = final_price + price. This means that every time we order another pizza, the price of the new pizza is added to the prices of our previous orders.

This aspect is the same in both ways of implementing the while.

Let’s have a look at the actual implementation. For both scenarios, I put an explanatory comment after everything in the code that is different from lesson 12.

a) We don’t know how many pizzas our customers want so we just ask again after each order.

Besides the accumulator that we have already discussed, there are only two more new aspects:

  • the while loop: while followed by a condition and a colon (just like an if in conditionals)
  • a variable that we use to create the condition: I called this variable resp, short for response, because in it we store the response of our customers – Do they want to make another order or not?
  1. At the beginning of the program, where we also initialized the accumulator, we set the variable resp to our desired initial value so that the condition of while is true.
    resp = 1
  2. Next, we create the while loop by writing while followed by the condition (variable == initial value) and the colon.
    while resp == 1:
    This assures that as long as long as the response to “another pizza” is yes (1), we repeat the ordering process.
  3. We copy and paste our code from last lesson (or whatever else we want our program to do as long as the while condition is true). Just make sure that the indention is correct. This works just like the conditionals with if and else, too.
  4. In the last line of the loop, i.e. before printing the final price, we ask the user for input on our resp variable.
    resp = int(input(“Do you want to order another pizza – yes (1) or no (2)? “)
    As long as the user responds 1 for “yes”, the condition defined in 2. is true, we stay in the loop and repeat the code from 3.


b) We know how many pizzas our customers will order.

For the second way of implementing a while, we need to consider three more aspects in addition to the accumulator.

  • the while loop: while followed by a condition and a colon (just like an if in conditionals)
  • How many times do you want to repeat the loop, i.e. how many pizzas will be ordered in total? Here, I named this variable order_pizzas and I ask the user for input.
  • How many times have you repeated the loop already, i.e. how many pizzas have already been order? As this variable does the counting, it is called a counter. In our example, it is called num_pizzas
  1. In the beginning of the program, where we also initialized the accumulator, we set the counter to 0.
    num_pizzas = 0
    Furthermore, if we want the user to determine the amount of repetitions, we have to ask for input here.
    order_pizzas = int(input(“How many pizzas do you want to order? “))
  2. Next, we create the while loop by writing while followed by the condition (counter < number of repetitions) and the colon
    while num_pizzas < order_pizzas:
    This assures that as long as long as we have ordered fewer pizzas than indicated in the beginning, we repeat the ordering process.
  3. We copy and paste our code from last lesson (or whatever else we want our program to do as long as the while condition is true). Just make sure that the indention is correct. This works just like the conditionals with if and else, too.
  4. In the last line of the loop, i.e. before printing the final price, we add 1 to the counter.
    num_pizzas = num_pizzas + 1
    This way, the counter always knows how often we have already repeated the process.

This has been a really long lesson, but I tried to break it down to make it easy to understand. If you have questions, just ask in the comment section below. Be proud, you have learned a fundamental aspect of programming! #mastery13

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

Python for Beginners 11: Conditionals

So far, we have covered the basics of how to write some simple code in sequential order. It is far more common, though, that you want your program to distinguish two or more alternatives. That’s when we need the so-called conditionals.

Just like in English, your condition starts with “if”, but unlike your normal phrases, this “if” needs to be followed by a variable and a comparative value, connected by an operator that describes the desired relationship. You may put the condition (without the if) into brackets. At the end, it is very important to put a colon.

Example for a condition:
in words:         if the variable a is bigger than 10
in Python:       if (a > 10):

In Python, it’s much shorter and thus more convenient.

Now comes the most difficult part: If you press enter, the curser automatically indents the following instructions. This is important. If you just copy something from somewhere else without indentation, Python won’t understand it and will display and error. Writing the instructions, i.e. what to do if the condition is true, is simple: It’s just your normal code.

Python also gives you the possibility to define instructions for the cases in which your conditions is not true. For this, you just write “else” at the same indentation level as your “if” and add a colon. You press enter and write your instruction in the next line. As “else” is the scenario in which your previous condition is not true, you don’t need to define any condition. Needless to say that you cannot use “else” if there is no previous “if”.

Some of you are probably now thinking, “That’s nice, but usually life is not black or white.” This is true, which is why Python has the option of adding one or more “elif” between “if” and “else”. What is “elif”? For once, this is not an actual English word, but a contraction between else and if. This explains also how it is used: It refers to a case in which your original condition (if) is not true (→ else), but you can define a new condition for your instruction (→ if). “elif” works just like “if”: you write your condition, possibly in brackets, and add the colon.

Before you try to write your first code with conditionals, one important piece of advice: Besides indention errors and missing brackets, most errors are due to users mistaking the assignation sign (=) for the equal sign (==). If your variable should be equal to a certain value, you must put ==. Otherwise Python won’t understand you.

Remember our favorite exercise on temperature conversion?

Now you can provide some additional information to the users: Let them know whether water boils at this temperature (under typical conditions).

Your code could look like this:

Of course, you could also leave out “elif” in this case, because we already have a validation since we define the user input as an integer. But as we’re still practicing, it’s nice to have all three options. #mastery11