For next loop in python

For loops

There are two ways to create loops in Python: with the for-loop and the while-loop.

When do I use for loops

for loops are used when you have a block of code which you want to repeat a fixed number of times. The for-loop is always used in combination with an iterable object, like a list or a range. The Python for statement iterates over the members of a sequence in order, executing the block each time. Contrast the for statement with the »while» loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example:

For loop from 0 to 2, therefore running 3 times.

for x in range(0, 3): print("We're on time %d" % (x))

While loop from 1 to infinity, therefore running forever.

x = 1 while True: print("To infinity and beyond! We're getting close, on %d now!" % (x)) x += 1

When running the above example, you can stop the program by pressing ctrl+c at the same time. As you can see, these loop constructs serve different purposes. The for loop runs for a fixed amount of times, while the while loop runs until the loop condition changes. In this example, the condition is the boolean True which will never change, so it will run forever.

How do they work?

If you’ve done any programming before, you have undoubtedly come across a for loop or an equivalent to it. Many languages have conditions in the syntax of their for loop, such as a relational expression to determine if the loop is done, and an increment expression to determine the next loop value. In Python, this is controlled instead by generating the appropriate sequence. Basically, any object with an iterable method can be used in a for loop. Even strings, despite not having an iterable method — but we’ll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there are multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods. This means that you’ll rarely be dealing with raw numbers when it comes to for loops in Python — great for just about anyone!

Nested loops

When you have a block of code you want to run x number of times, then a block of code within that code which you want to run y number of times, you use what is known as a «nested loop». In Python, these are heavily used whenever someone has a list of lists — an iterable object within an iterable object.

for x in range(1, 11): for y in range(1, 11): print('%d * %d = %d' % (x, y, x*y))

Like the while loop, the for loop can be made to exit before the given object is finished. This is done using the break statement, which will immediately drop out of the loop and continue execution at the first statement after the block. You can also have an optional else clause, which will run should the for loop exit cleanly — that is, without breaking.

for x in range(3): if x == 1: break

Examples

for x in range(3): print(x) else: print('Final x = %d' % (x))
string = "Hello World" for x in string: print(x)
collection = ['hey', 5, 'd'] for x in collection: print(x)
list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: for x in list: print(x)

Creating your own iterable

class Iterable(object): def __init__(self,values): self.values = values self.location = 0 def __iter__(self): return self def next(self): if self.location == len(self.values): raise StopIteration value = self.values[self.location] self.location += 1 return value

Your own range generator using yield

def my_range(start, end, step): while start yield start start += step for x in my_range(1, 10, 0.5): print(x)

A note on `range`

The »range» function is seen so often in for statements that you might think range is part of the for syntax. It is not: it is a Python built-in function that returns a sequence following a specific pattern (most often sequential integers), which thus meets the requirement of providing a sequence for the for statement to iterate over. Since for can operate directly on sequences, there is often no need to count. This is a common beginner construct (if they are coming from another language with different loop syntax):

mylist = ['a', 'b', 'c', 'd'] for i in range(len(mylist)): # do something with mylist[i]

It can be replaced with this:

mylist = ['a', 'b', 'c', 'd'] for v in mylist: # do something with v

Consider for var in range(len(something)): to be a flag for possibly non-optimal Python coding.

Читайте также:  Run your javascript online

More resources

ForLoop (last edited 2022-01-23 09:18:40 by eriky )

Источник

Python for loop [with easy examples]

Python for loop [with easy examples]

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

The for loop in Python is an iterating function. If you have a sequence object like a list, you can use the for loop to iterate over the items contained within the list. The functionality of the for loop isn’t very different from what you see in multiple other programming languages. In this article, we’ll explore the Python for loop in detail and learn to iterate over different sequences including lists, tuples, and more. Additionally, we’ll learn to control the flow of the loop using the break and continue statements.

Basic Syntax of the Python for loop

for itarator_variable in sequence_name: Statements . . . Statements 
  • The first word of the statement starts with the keyword “for” which signifies the beginning of the for loop.
  • Then we have the iterator variable which iterates over the sequence and can be used within the loop to perform various functions
  • The next is the “in” keyword in Python which tells the iterator variable to loop for elements within the sequence
  • And finally, we have the sequence variable which can either be a list, a tuple, or any other kind of iterator.
  • The statements part of the loop is where you can play around with the iterator variable and perform various function
Читайте также:  Sqlite java запросы примеры

1. Print individual letters of a string using the for loop

Python string is a sequence of characters. If within any of your programming applications, you need to go over the characters of a string individually, you can use the for loop here.

Here’s how that would work out for you.

word="anaconda" for letter in word: print (letter) 

The reason why this loop works is because Python considers a “string” as a sequence of characters instead of looking at the string as a whole.

2. Using the for loop to iterate over a Python list or tuple

Lists and Tuples are iterable objects. Let’s look at how we can loop over the elements within these objects now.

words= ["Apple", "Banana", "Car", "Dolphin" ] for word in words: print (word) 

Now, let’s move ahead and work on looping over the elements of a tuple here.

nums = (1, 2, 3, 4) sum_nums = 0 for num in nums: sum_nums = sum_nums + num print(f'Sum of numbers is sum_nums>') # Output # Sum of numbers is 10 

3. Nesting Python for loops

When we have a for loop inside another for loop, it’s called a nested for loop. There are multiple applications of a nested for loop.

Consider the list example above. The for loop prints out individual words from the list. But what if we want to print out the individual characters of each of the words within the list instead?

This is where a nested for loop works better. The first loop (parent loop) will go over the words one by one. The second loop (child loop) will loop over the characters of each of the words.

words= ["Apple", "Banana", "Car", "Dolphin" ] for word in words: #This loop is fetching word from the list print ("The following lines will print each letters of "+word) for letter in word: #This loop is fetching letter for the word print (letter) print("") #This print is used to print a blank line 

python nested for loop example

4. Python for loop with range() function

Python range() is one of the built-in functions. When you want the for loop to run for a specific number of times, or you need to specify a range of objects to print out, the range function works really well. Consider the following example where I want to print the numbers 1, 2, and 3.

for x in range(3): print("Printing:", x) # Output # Printing: 0 # Printing: 1 # Printing: 2 

The range function also takes another parameter apart from the start and the stop. This is the step parameter. It tells the range function how many numbers to skip between each count.

In the below example, I’ve used number 3 as the step and you can see the output numbers are the previous number + 3.

for n in range(1, 10, 3): print("Printing with step:", n) # Output # Printing with step: 1 # Printing with step: 4 # Printing with step: 7 

5. break statement with for loop

The break statement is used to exit the for loop prematurely. It’s used to break the for loop when a specific condition is met.

Let’s say we have a list of numbers and we want to check if a number is present or not. We can iterate over the list of numbers and if the number is found, break out of the loop because we don’t need to keep iterating over the remaining elements.

In this case, we’ll use the Python if else condition along with our for loop.

nums = [1, 2, 3, 4, 5, 6] n = 2 found = False for num in nums: if n == num: found = True break print(f'List contains n>: found>') # Output # List contains 2: True 

6. The continue statement with for loop

We can use continue statements inside a for loop to skip the execution of the for loop body for a specific condition.

Let’s say we have a list of numbers and we want to print the sum of positive numbers. We can use the continue statements to skip the for loop for negative numbers.

nums = [1, 2, -3, 4, -5, 6] sum_positives = 0 for num in nums: if num  0: continue sum_positives += num print(f'Sum of Positive Numbers: sum_positives>') 

6. Python for loop with an else block

We can use else block with a Python for loop. The else block is executed only when the for loop is not terminated by a break statement.

Let’s say we have a function to print the sum of numbers if and only if all the numbers are even.

We can use break statement to terminate the for loop if an odd number is present. We can print the sum in the else part so that it gets printed only when the for loop is executed normally.

def print_sum_even_nums(even_nums): total = 0 for x in even_nums: if x % 2 != 0: break total += x else: print("For loop executed normally") print(f'Sum of numbers total>') # this will print the sum print_sum_even_nums([2, 4, 6, 8]) # this won't print the sum because of an odd number in the sequence print_sum_even_nums([2, 4, 5, 8]) # Output # For loop executed normally # Sum of numbers 20 

Conclusion

The for loop in Python is very similar to other programming languages. We can use break and continue statements with for loop to alter the execution. However, in Python, we can have optional else block in for loop too.

I hope you have gained some interesting ideas from the tutorial above. If you have any questions, let us know in the comments below.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью