text: Python For Loop: An In-Depth Tutorial
  While loops exist in virtually all programming languages, the Python for loop function is one of the easiest built-in functions to master since it reads almost like plain English.In this tutorial, we’ll cover every facet of the for loop. We’ll show you how to use it with a range of examples so that you can start to get a good understanding of its usage with the language. We’ll also go into a few common Python commands and functions like join and argv that are commonly used in practice with the loop. For more in-depth lessons on for loop and other Python introductory programming concepts, check out this course on how to Learn Python From Scratch.
  Last Updated April 2021
  Python course for beginners, Learn Python Programming , Python Web Framework Django, Flask, Web scraping and a lot more. | By Ashutosh PawarExplore Course
  Setting up your computer for Python
  The easiest way to try out Python code is with a web-based IDE and compiler. We’ve used Repl.it for Python 3 for our examples, although you’re welcome to download Python and run it locally on your Windows or Mac machine with your preferred IDE/compiler.
  What is a Python for loop?
  A for loop is used to repeat a block of code (encased in the for loop) n number of times. The for loop is used to repeat the same action over a list of things. It’s one of a number of Python iterators. The basic syntax of the for loop looks like this:
  for item in list:
  do action with item
  Translated into regular English, this would be: “For every item that is present in the list, perform an action with each item in the sequence.”
  If you’ve gone ahead and entered the above code into the Python editor and ran it to see the results you will have noticed that it won’t compile. Why? Because you haven’t defined your list, and the word ‘list’ itself is a built-in type (like int or bool). ‘Do action with’ is plaintext and not defined. The above is simply the structure that you should follow with the for loop.
  There are a few things to note here:
  - Every for loop must reference a list or a range.
  - Every for loop must start with a colon.
  - Code to be executed as part of the for loop must be indented (use four spaces or one press of the Tab key, depending on preference or coding standard used).
  - To use individual items in the list or range, we have to create a variable (item in the syntax above). There’s no need to declare this variable before creating the for loop. You can also reuse the same variable with other for loops.
  - For code to run after the for loop, simply unindent.. Note that text after the hashes are comments that aren’t compiled.
  Example 1
  x = [2, 8, 512] #Creating a list
  for i in x: #Here, i is the variable used to refer to individual items in the list
  print(i)
  Once you’ve put this into your coding window, hit the Run button. Here’s the output:
  Python 3.7.4 (default, Jul 9 2019, 00:06:43) [GCC 6.3.0 20170516] on linux
  2
  8
  512
  Note that you need to use parentheses to perform the print function on each item.
  Let’s look at another example using Python for loop range:
  Example 2
  for i in range (0, 10):
  print(i)
  The output:
  You can see how the above example can be used to print a list of numbers within a specified range. You can also use it to do some simple mathematics and print out lists of even or odd numbers, as we’ll see in later examples.
  for loop vs. while loop
  Python supports two kinds of loops – for and while. They are quite similar in syntax and how they work, but differ in one crucial aspect: a while loop will run infinitely so long as the condition is being met.
  A while loop has the following syntax:
  while condition:
  Do something
  Here’s an example printing a sequence of numbers:
  i = 0
  while i < 100:
  i = i + 1 #This statement is required to eventually make the while loop condition false
  print(i)
  Here’s the output:
  If, however, you were to remove the ‘i = i + 1’ part, the while condition will never exit, as the number will never reach 100. These type of while loops iterate endlessly and the program will probably crash eventually. This is called an infinite loop.
  Try it right now – remove the i = i + 1 part and run the program. You should see something like this:
  Because while loops run infinitely until the condition becomes false, they can often cause programs to throw errors or crash. This is the reason why you should try to use for loops instead of while loops whenever you can, as it’s harder to make these kinds of coding errors. list tuple can’t be changed, whereas you can alter the items in a list. Instead of a square bracket like normal lists, tuples sit inside round brackets (). The basic syntax is as follows:
  tuple_name = (tuple_item_1, tuple_item_2, tuple_item_3)
  Like lists, tuples can hold text strings, numbers, or both (and/or other items beyond the scope of this tutorial): then loops over individual items in the list and reproduces the results. You can not only print, but also perform all sorts of different operations on list items (such as mathematical equations), and add/delete items.
  Let’s look at a few examples to understand how this works:
  Printing items from a list
  list1 = [1, 3, 5, 7, 9, 11]
  for item in list1:
  print(item)
  This will print out each individual item in the list:
  for i in (1, 2, 3, 4, 5, 6):
  print(i)
  The output:
  Modifying items in a list
  What if you want to add items to the list? For this, we can use the append() method.
  Here’s an example:
  list1 = [1, 2, 3, 4, 5, 6, 7]
  list2 = [8, 9, 10]
  list1.append(list2)
  When we print list1, however, we see the following output:
  Can you spot the problem? The append() method treats all of the individual items in list2 as one single item: a single list as one of the items in our original list. Instead of 8, 9, 10 being treated as separate list items, they get clumped together.
  You can see this if you print just eight elements of the list by using print(list1[7]). You can see that [8, 9, 10] adding the entire list2 as an item in list1, we’re going through all the elements in list2 separately and adding them to list1. This is just one of the many uses of for loops and lists.
  Note: You can add the individual elements to the list by using the extend() method as well. This means you don’t have to run a for loop to get the same result as above, simply use list1.extend(list2)., a list of numbers, and a list is what’s called a nested loop. Note that you need an extra tab when you’re adding a loop within a loop. The code itself means that you’re instructing Python to go through each list within list1. The output looks like this:
  We’ll come back to nested for loops later. For now, you should know that to work with lists within lists, you need multiple for loops.
  Using loops with range
  The built-in range() method is especially useful when using loops. The range() method defines a certain set of items boundary for the range. In case you use only one value (say, for i in range(10)), Python will automatically assume that the count starts from 0. However, it is good practice to include both the lower and upper bounds for the range in your code.
  Note that the upper bound of the range is not inclusive, i.e. in the above example, 10 would not be included.
  But what if you wanted to count backwards? Don’t worry, you don’t need to use() can come in very handy when working with numbers. Try to play around with it and see what other kinds of sequences you can come up with.
  The range() can come in very handy when working with numbers. Try to play around with it and see what other kinds. That funny ‘elif’ word in the middle is shorthand for “else if.”
  Let’s consider an example. Suppose we have a list of numbers and we want to print them out only if they are even. One way to do this is by using both for loops and an if statement; this one is missing the else part. If the condition is met (i%2 is equal to zero) we print it.
  list1 = [1, 2, 3, 4, 6, 8, 12, 5, 17, 19, 20, 25, 28]
  for i in list1: #For loop iterates through each item in list
  if i % 2 == 0: #If-statement checks whether the list item leaves any remainder when divided by 2
  print(i)
  Here’s the result of this operation:
  In later examples, we’ll use for loops and if-else statements to create useful, complex programs.
  Nested for loops
  A nested loop is basically a loop within a loop. We covered a simple nested loop in an example above, if you remember, going through a list of lists. Let’s go further an important property in Python – that strings are actually lists of individual characters. statement.
  Let’s see how it works:
  x = range(1, 100)
  for i in x:
  break
  print(i)
  This will produce no output at all because you’ve commanded Python to break the program flow before it can print anything.
  However, if you input the print statement outside the loop (unindent) you’ll get a different output.
  x = range(1, 100)
  for i in x:
  break
  print(i)
  This will simply give 1 as the answer. This is because we only got to the first item, 1, in the range function before we broke the loop. Another useful statement to add that is often mentioned alongside break statements are continue statements, however, these are beyond the scope of this tutorial (read the official docs for more info).
  In the examples below, we’ll learn how we can use Python for loops to create different programs. We’ll also learn about some Python commands and features we didn’t touch upon before.
  Examples
  1. Create a list of items using input provided by a user
  This is a great example of a simple, beginner program that uses for loops and lists. As with any programming exercise, it helps to write out the basic requirements before writing any code. In this program we want to:
  - Create an empty list.
  - Ask the user how many items they want to add to the list.
  - Add input items to the list.
  - Print items.
  Based on these requirements, we can gather that we’ll need to use the input() function to gather user input, and append() to add elements to the list.
  So let’s get started!
  print(“Hello, welcome to the program”)
  print(“This program will ask you to enter the names of places you’ve been to”)
  print(“Before we get started, please enter the number of places you want to enter”)
  number = int(input(“> “))
  print(“Thank you!”)
  print(“We’ll now ask you to enter all the places you’ve traveled to”)
  places_traveled = [] #Empty list created to hold entered values
  for i in range(number): #range(number) used because we want to limit the number of inputs to user choice
  places = input(“> “)
  places_traveled.append(places)
  print(“Here’s a list of places you’ve been to: \n”, places_traveled)
  Running the program, we see this:
  Let’s take a look at one of the statements from the program to explain exactly what’s going on.
  number = int(input(“> “))
  We enclosed.
  How about this piece of code?
  places_traveled = []
  Yes, you can create empty lists as well! This is what declaring an empty list looks like, you simply add to it later.
  for i in range(number):
  Instead of declaring the range ourselves, we asked the user for the number of items they would like to enter. Hence, we declared the variable before using it in the loop.
  Using argv
  If we were running the program from the command line, instead of the in-browser editor, we could add the following to the start of the code:
  from sys import argv #Import command used to import argv or argument variable
  script, user_name = argv #argv used to extract user name and program name
  print(“Hello, welcome to the %s program, %s” % (script, user_name))
  To do this in Repl.it, press F1, then select ‘Open Shell,’ then in the new console area, type
  python main.py John
  You can view the console and output here:
  This is because we’ve given two arguments to the program at runtime: the name of the program and a username. Let’s break it down..
  Try and expand on this example cursory use of for loops, we’ll use it to introduce a few other theabetic characters or not. item.isalpha() essentially means: “proceed only if the entered input is an alphabetic character.; a space, some dashes, some ellipses, or a comma. The format must be enclosed within quotes to print correctly.
  For homework, try to complete the following exercise:
  - Look up both len() and isalpha() on the current official Python documentation. Can you think of any other situations where these two might be used?
  - We’ve used join(), but there’s another Python function called split() that can be used to break strings apart. Look up split() on the official Python documentation. How does it differ from join()? What are some possible use cases for split()?
  3. Printing the first n numbers and checking whether they are prime
  This is a great example that utilizes nested loops, if statements and the break command. It also uses the rare for-else statement that can be utilized with break.”)
  Note that the else statement lines up with our for indentation; it doesn’t belong to the if statement.:
  The percentage symbol in programming called modulo (or mod for short), and is used as a check for divisibility; it shows the remainder if i is divided by x. So 6%2=0, 6%3=0, 6%4=2, 6%5=3, and 6%6=0.
  We know that if a number has more than two divisors (where the result from the operation is 0), it is not prime. So, in our example, because there are 2 cases where the result is not 0, 6 is not a prime number. not all of these numbers, 15, and see what happens when i = 15.
  - Look up else clauses in the Python documentation online.
  Frequently Asked Questions
  Q. Where should you use a for loop instead of a while loop?
  Almost everywhere. The while loop has its uses, but it is also prone to throw off errors or give weird results which can be difficult to hunt down. As a beginner, try to minimize the number of while loops in your programs and stick to for loops instead. Sure, there are problems where you can’t help but use a while loop, but if possible, use if they’re reading your code!).
  Q. I saw a ‘pass’ command in some code online. What is that?
  A ‘pass’ command is basically an empty placeholder. It doesn’t do anything but is used in a place where some code is required syntactically to make sure it compiles and runs – with the actual code itself to be added later on. We can go ahead with executing the block without it causing errors. As an example, look at the question below.
  Q. What is the difference between range and xrange?
  If you looked up range online, you may have encountered xrange as well. xrange is an outdated function from earlier versions of Python. xrange is now defunct, rolled into the range function in Python 3.
  When you use range, you essentially create a list which Python iterates through. Thus, for x in range(0, 100) basically creates a temporary list with numbers from 0 to 100. As the for loop is executed, Python goes through each element in this list. This can be slow, especially when dealing with a very large range of values.
  With the new range abilities in Python 3 (what was xrange in Python 2), it can generate an iterable object that creates the number(s) required in the range. Understanding how this works requires going into object-oriented programming, which is an entirely new ball game altogether.
  You can test the runtime of range (or any other function) by using the timeit module. To use this method, try out the following code:
  import timeit
  start_time = timeit.default_timer()
  for x in range(0,200000):
  pass
  elapsed = timeit.default_timer() – start_time
  print(elapsed)
  (Notice how we used ‘pass’ here because the for loop required an indented block syntactically, but the program didn’t).
  Q. What are dictionaries?
  We haven’t yet mentioned dictionaries in this tutorial. Python dictionaries are basically another type of sequence in Python. They’re like lists, except that they have both items().
  for i, value in animals.items():. Just type in the following at the command prompt (making sure to include import pydoc and run it in your code window first): and GitHub should be to familiarize yourself with the while loop, dictionaries, and eventually things like classes and object-oriented programming, plus breakpoints for debugging code. Try some of these courses below to get started:
  Empower your team. Lead the industry.
  Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.