Students_countries = ['Belgium', 'Czech Republic', 'France', We will use the for loop to check each country in new_students_countries to see if we already have students from the same country: We now also have the list students_countries with the home countries of the existing students. We have the list new_students_countries with the home countries of the new students. Now that we’re familiar with the syntax, let’s move on to an example where the usefulness of the for loop is more apparent. It has 95 interactive exercises that cover basic Python topics, including loops. Practice writing for loops with the course Python Basics. The body of the loop is indented and includes the code that we want to execute for each item of the sequence.The initializer section ends with “ :”.Then, the in keyword is followed by the name of the sequence that we want to iterate.It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case).Let’s go over the syntax of the for loop: As a result, we get the name of each country printed out in the output. Here, for each country in the list new_students_countries, we execute the print() command. We use the for loop to access each country in the list and print it: So, we have the list new_students_countries, which contains the countries of origin for our three new students. Let’s say we want to keep track of the home countries of our students. To explain the syntax of the for loop, we’ll start with a very basic example. You use it if you need to execute the same code for each item of a sequence. You should understand it well and master it to build applications in Python.Ī for loop allows you to iterate over a sequence that can be either a list, a tuple, a set, a dictionary, or a string. Python is a powerful programming language that can be used for just about anything, and the for loop is one of its fundamental tools. In this article, I’ll give you a brief overview of the for loop in Python and demonstrate with examples how you can use it to iterate over different types of sequences. You will likely encounter them at the very beginning of your Python journey. The for loop is one of the basic tools in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |