Creating a Loop to Go Through the Program Again in Python

Python For Loop – Example and Tutorial

Loops let y'all control the logic and flow structures of your programs.

Specifically, a for loop lets you execute a block of similar code operations, over and over again, until a condition is met.

You repeat certain code instructions for a set of values yous determine, and you perform deportment on each value for a pre-determined number of times.

What is a for loop in Python?

A for loop can iterate over every item in a list or get through every single character in a string and won't stop until it has gone through every character.

Writing for loops helps reduce repetitiveness in your lawmaking, following the Dry (Don't Repeat Yourself) principle. Y'all don't write the aforementioned block of code more than than once.

In this article, we'll get to know the basics of for loops in the Python programming linguistic communication using different examples. Just starting time let'due south learn some for loop basics.

How Does a for loop Work in Other Programming Languages?

Looping in near modernistic programming languages similar JavaScript, Java, or C looks something similar the example below.

Loops in JavaScript:

                for (let i = 0; i < 10; i++) {   console.log('Counting numbers');   // prints "Counting numbers" 10 times   // values of i from 0 to 9    }                              

The for loop by and large keeps track of three things:

  1. The initialization expression statement which is exactuted once, let i = 0;
  2. The condition that needs to be met, i < 10;. This status is evaluated every bit either true or false. If it is false, the loop is terminated.
  3. If the condition is true the trunk of the loop will be executed and the initialized expression volition take some activity. In this case it volition exist incremented by 1 (i++), until the condition set is met.

for loop Syntax in Python

The for loop in Python looks quite different compared to other programming languages.

Python prides itself on readability, then its for loop is cleaner, simpler, and more compact.

The basic structure is this:

                for particular in sequence:     execute expression                              

where:

  • for starts a for loop.
  • item is an individual item during each iteration. It is given a temporary arbitary variable name.
  • in separates each detail from the other(s).
  • sequence is what we want to iterate over.
  • a colon : gives the instruction to execute the torso of code that follows.
  • A new line.
  • A level of indentation. 4 spaces before writing the body of the loop, otherwise we go an IndentationError.
  • The body with the actions that need to exist taken and repeated (for example, print something to the panel). It goes where the execute experssion line is.

How the Python for loop works

Let'due south say we have a sequence, a list of stored items nosotros want to run through – in this case a grocery list:

                groceries = ["bananas","butter","cheese","toothpaste"]                              

The in keyword checks to see if an detail is included in a sequence. When combined with the for keyword, information technology indicates iterating over every particular in the sequence.

Information technology does something with every detail on the list. In this case it prints separetely each individual item to the console until every item has been iterated over.

                for grocery in groceries:     # for each iteration print the value of grocery     print(grocery)                              

grocery is a temporary variable name to refer to each item of the list.

It'southward an iterator variable, that with each succesive iteration its value gets fix to each value the listing includes. Essentially, information technology'south a temporary variable with a temporary value.

We could name it whatsoever we want, such as g or item. But the proper noun should exist unique and not be the same as any other variable in our program.

On the outset run, the first element – bananas – is stored in the variable particular.

Then the expression print(grocery), which substantially is how impress("bananas") is executed.

On the second run, the element butter is stored in the variable detail and as above, it gets printed to the console.

This procedure continues until all items have been iterated over.

Here'southward the output of that code:

                bananas butter cheese toothpaste                              

How to use a for loop for a range of numbers

We can use the range() function with a given range to specify how many times in a row nosotros desire the for loop to iterate over. This simplifies the for loop.

The range() office creates a sequence of integers depending on the arguments we requite it.

How does this work?

Take a look at the example beneath:

                for i in range(5):     print(i)                              

The output of which is:

                0 ane 2 3 4                              

It creates a list of numbers between 0 and 4.

By default when nosotros give range() one argument, the range starts counting from 0.

Notice that 5 is non printed to the console.

In range(5), we specify that 5 is the highest number we want, but not inclusive. It does not include it, information technology'south just the stopping point. It defines how many times we desire our loop to run. Nosotros see it runs 5 times and creates a sort of list of 5 items: 0,1,2,3,4.

If you want to come across what range() produces for debugging purposes, you can pass it to the list() function.

Open the interactive Python shell in your console, typically with the command python3, and type:

                show_numbers = listing(range(five))  impress(show_numbers)                              

What if we want our range to start from one and then to also see five printed to the console? We instead requite range() two different arguments this time:

                for i in range(1,6):     print(i)                              

Output:

                0 one 2 3 four five                              

The start argument (kickoff) which as we saw earlier is optional, is where the sequence should begin (in this case it'southward one). This argument is inclusive and the number is included.

The second statement (stop) which is required, is where the sequence should cease and is not inclusive, as mentioned earlier. In this case information technology's 6.

Lastly, you tin pass in a third optional parameter: step.

This controls the increase between the two values in the range. The default value of pace is i.

Permit's say nosotros wanted to jump every 2 numbers and get the odd numbers from a sequence. We could do:

                for i in range(1,ten,2):     print(i)                              

Output:

                1 three 5 seven 9                              

1 is where we beginning, 10 is i higher than what we want (which is 9), and 2 is the amount we want to bound between numbers (in this case we bound every ii numbers).

How to use enumerate() in Python

So far nosotros have not used whatever indexes when iterating. Sometimes, we need to access the index of the item we're looping through and display it.

We can loop over items with the alphabetize using enumerate().

Our example from before:

                groceries = ["bananas","butter","cheese","toothpaste"]  for grocery in groceries:     print(grocery)                              

Tin now be written like this:

                groceries = ["bananas","butter","cheese","toothpaste"]  for alphabetize, grocery in enumerate(groceries):     print(index,grocery)                              

Output:

                0 bananas 1 butter 2 cheese 3 toothpaste                              

Or for a bit more complex output:

                groceries = ["bananas","butter","cheese","toothpaste"] for index, grocery in enumerate(groceries):     print(f"Grocery: {grocery} is at index: {index}.")                              

Output:

                Grocery: bananas is at index: 0. Grocery: butter is at index: 1. Grocery: cheese is at index: 2. Grocery: toothpaste is at alphabetize: three                              
  • Instead of just writing one variable grocery like before, at present we write two: index,grocery. On each iteration, index contains the index of the value and grocery the value of groceries.
  • alphabetize is the index of the value beingness iterated.
  • Indexes in Python start counting at 0 .
  • grocery is the value of the detail at the current iteration
  • The line enumerate(groceries) lets us iterate through the sequence and go on track of the index of the value and the value itself.

Conclusion

I promise y'all enjoyed this basic introduction to the for loop in Python.

Nosotros went over the bones syntax that makes up a for loop and how it works.

We and then briefly explained what the two built-in python methods, range() and enumerate(), do in for loops.

Thanks for reading and happy coding!



Learn to code for free. freeCodeCamp'southward open up source curriculum has helped more 40,000 people get jobs as developers. Get started

smitheveng1943.blogspot.com

Source: https://www.freecodecamp.org/news/python-for-loop-example-and-tutorial/

0 Response to "Creating a Loop to Go Through the Program Again in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel