Computer Science

For Loop in Python

A for loop in Python is a control flow statement that allows you to iterate over a sequence of elements, such as a list or a string. It consists of a header line that specifies the sequence to iterate over and a block of code to be executed for each element in the sequence. This loop is commonly used for repetitive tasks and iterating through data structures.

Written by Perlego with AI-assistance

10 Key excerpts on "For Loop in Python"

  • Book cover image for: Job Ready Python
    eBook - PDF
    • Haythem Balti, Kimberly A. Weiss(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    Statements in the loop body are executed in sequence on each pass-through. In Python, these statements must be indented and aligned within the same column. NOTE Your integrated development environment (IDE) should automatically indent the lines under the loop header. Best practice dictates a four-space indentation if your IDE does not provide this automatic feature. THE FOR LOOP Python’s for loop is the control statement that easily supports definite iteration , where we know exactly how many times the loop should execute. The format of a for loop was shown before, but let’s look at it again: for < var > in < iterable >: < statement(s) > Figure 7.1: A definite iteration Job Ready Python 146 A for loop is traditionally used when a developer wants to repeat a block of code a fixed number of times. As you can see in the code in Listing 7.1, we know the number of “passes” that the loop will take based on the number defined in the loop header. LISTING 7.1 A for loop in action for eachPass in range(3): print(Wake Up!) When this listing is executed, the following output is displayed: Wake Up! Wake Up! Wake Up! As you can see, the loop happened three times. More specifically, the range(3) sets a sequence of three item numbers starting at 0 and ending before reaching that value included, which is 3. The Python for statement iterates (repeats) the members of the sequence in order, executing the block statements each time. If you changed the range to a different number, then the for statement would iterate that many times. NOTE If you’ve used other programming languages such as C, C++, or Java, then you might notice that the For Loop in Python doesn’t use braces ({}) to mark the beginning and end of the code block that will be iterated with the loop. Rather, Python uses indenting to determine what code to run.
  • Book cover image for: Python Fundamentals
    No longer available |Learn more

    Python Fundamentals

    A practical guide for learning Python, complete with real-world projects for you to explore

    • Ryan Marvin, Mark Ng'ang'a, Amos Omondi(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    Loops allow us to deconstruct iterables and perform operations on their constituent members or even convert them into new data structures. The possibilities are endless once you start using loops.

    The for Loop

    The for loop in Python is also referred to as the for…in loop. This is due to its unique syntax that differs a bit from for loops in other languages.
    A for loop is used when you have a block of code that you would like to execute repeatedly a given number of times. For example, multiplying an iterable value, or dividing the value by another if the iterable value is still present in the loop.
    The loop contrasts and differs from a while statement in that in a for loop, the repeated code block is ran a predetermined number of times, while in a while statement, the code is ran an arbitrary number of times as long as a condition is satisfied.
    The basic syntax of a for loop is shown here:
    # Iterable here can be anything that can be looped over e.g. a list # Member here is a single constituent of the iterable e.g. an entry in a list for member in iterable: # Execute this code for each constituent member of the iterable pass
    As shown in the preceding code, the for loop allows you to go through each constituent member of an iterable and run a block of code for each member. This code could be anything from a simple summation of the values to more complex manipulations and analysis. Again, the possibilities are endless, and having the ability to easily access iterables like this will prove invaluable as you start building more complex programs in Python.

    Exercise 17: Using the for Loop

    A practical use of the for loop is shown here:
    1. First, declare a variable called numbers . We initialize numbers to a list of integers from 1 to 10:numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    2. Next, loop through the list we just created.
      Create a new variable called num in the for loop. We will use this variable to represent and access the individual numbers in the list as we loop through it:
      for num in numbers:
    3. Inside the loop, calculate the square of num by multiplying it by itself. Note that there are other ways to calculate the square, but this rudimentary method will suffice for our example here.
      We assign the square of num to the variable square :
      square = num * num
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2015(Publication Date)
    • Wiley
      (Publisher)
    When Python runs the for loop, it assigns successive values in to and executes the for every value of . After the has been executed for the last value in , execution resumes with statement that is below the indented block and has the same indentation as the first line of the for loop statement. The for loop, and loops in general, have many uses in programming, and there are different ways to use loops. In this section, we describe several basic loop usage patterns. Loop Pattern: Iteration Loop So far in this book, we have used the for loop to iterate over the items of a list: >>> l = ['cat', 'dog', 'chicken'] >>> for animal in l: print(animal) cat dog chicken We have used it to iterate over the characters of a string: >>> s = 'cupcake' >>> for c in s: if c in 'aeiou': print(c) u a e Iterating through an explicit sequence of values and performing some action on each value represents the simplest usage pattern for a for loop. We call this usage pattern the iteration loop pattern. This is the loop pattern we have used most so far in this book. We include, as our final example of an iteration loop pattern, the code from Chapter 4 that reads 132 Chapter 5 Execution Control Structures a file line by line and prints each line in the interactive shell: >>> infile = open('test.txt', 'r') >>> for line in infile: print(line, end='') In this example, the iteration is not over characters of a string or items of a list but over the lines of the file-like object infile. Even though the container is different, the basic iteration pattern is the same.
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2012(Publication Date)
    • Wiley
      (Publisher)
    When Python runs the for loop, it assigns successive values in to and executes the for every value of . After the has been executed for the last value in , execution resumes with statement that is below the indented block and has the same indentation as the first line of the for loop statement. The for loop, and loops in general, have many uses in programming, and there are different ways to use loops. In this section, we describe several basic loop usage patterns. Loop Pattern: Iteration Loop So far in this book, we have used the for loop to iterate over the items of a list: >>> l = ['cat', 'dog', 'chicken'] >>> for animal in l: print(animal) cat dog chicken We have used it to iterate over the characters of a string: >>> s = 'cupcake' >>> for c in s: if c in 'aeiou': print(c) u a e Iterating through an explicit sequence of values and performing some action on each value is the simplest usage pattern for a for loop. We call this usage pattern the iteration loop pattern. This is the loop pattern we have used most so far in this book. We include, as our final example of an iteration loop pattern, the code from Chapter 4 that reads a file line 138 Chapter 5 Execution Control Structures by line and prints each line in the interactive shell: >>> infile = open('test.txt', 'r') >>> for line in infile: print(line, end='') In this example, the iteration is not over characters of a string or items of a list but over the lines of the file-like object infile. Even though the container is different, the basic iteration pattern is the same.
  • Book cover image for: The Statistics and Calculus with Python Workshop
    • Peter Farrell, Alvaro Fuentes, Ajinkya Sudhir Kolhe, Quan Nguyen, Alexander Joseph Sarver, Marios Tsatsos(Authors)
    • 2020(Publication Date)
    • Packt Publishing
      (Publisher)
    for loops. Let's understand each one in detail.

    The while Loop

    A while loop, just like an if statement, checks for a specified condition to determine whether the execution of a given program should keep on looping or not. For example, consider the following code:
    >>> x = 0 >>> while x < 3: ... print(x) ... x += 1 0 1 2
    In the preceding code, after x was initialized with the value 0 , a while loop was used to successively print out the value of the variable and increment the same variable at each iteration. As you can imagine, when this program executes, 0 , 1 , and 2 will be printed out and when x reaches 3 , the condition specified in the while loop is no longer met, and the loop therefore ends.
    Note that the x += 1 command corresponds to x = x + 1 , which increments the value of x during each iteration of the loop. If we remove this command, then we would get an infinite loop printing 0 each time.

    The for Loop

    A for loop, on the other hand, is typically used to iterate through a specific sequence of values. Using the range function in Python, the following code produces the exact same output that we had previously:
    >>> for x in range(3): ... print(x) 0 1 2
    The in keyword is the key to any for loop in Python: when it is used, the variable in front of it will be assigned values inside the iterator that we'd like to loop through sequentially. In the preceding case, the x variable is assigned the values inside the range(3) iterator—which are, in order, 0 , 1 , and 2 —at each iteration of the for loop.
    Instead of range() , other types of iterators can also be used in a Python for loop. The following table gives a brief summary of some of the most common iterators to be used in for
  • Book cover image for: The Python Audio Cookbook
    eBook - PDF

    The Python Audio Cookbook

    Recipes for Audio Scripting with Python

    • Alexandros Drymonitis(Author)
    • 2023(Publication Date)
    • Focal Press
      (Publisher)
    2.6 Loops in Python Python has structures that make parts of our code run in a loop, for a specified number of times. In this section we will look at two different ways to run loops in Python. Ingredients: • Python3 • An interactive Python shell Process: There are two different ways to run code in a loop, using the for or the while reserved keywords. Let us include the if test we already wrote, in a for loop. The code is shown in Shell 2.25. Shell 2.25 A for loop. >>> for i in range(10): ... if i == 5: ... continue ... print(i) ... >>> In this script, we have used the for keyword, combined with range(). range(), which is a class rather than a function (more on classes in Chapter 8), takes from one to three arguments. Here we have passed one argument which is the “stop” argument. This means that range() will iterate over a range from value 0, until it reaches [stop – 1], and it will increment by 1 every time. Essentially, when using range() with one argument only, it will iterate as many times as the argument we pass to it, in our case, it will iterate ten times. 26 Writing Your First Python Programs range() returns a list with the values it iterates over. In this code it will return the follow- ing list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The for loop will iterate over this list and will assign each of its values to the variable i, every time assigning the next item of the list. Inside the body of our loop we can use this variable for any task we want. This example is very simple and all it does is print on the console the value of i except from the iteration where i is equal to 5. This is achieved by using the reversed keyword continue. This word skips any code of the structure that includes it, that is written below it. So, when our if test is true, the code written below this test will be skipped, and the for loop will continue to the next iteration. Running this script will print the following on the console.
  • Book cover image for: A Functional Start to Computing with Python
    A better way to learn about repetition in a programming language would be some interactive game, or to experiment with for and build your own mental model of what is happening. for c in Hello: print c In spite of the inadequacies of the printed page, the following is an attempt to show how for works, in “slow motion.” We start with the simple loop shown to the right. This loop will print the letters of Hello, one at a time, on five lines. c = 'H' print c c = 'e' print c c = 'l' print c c = 'l' print c c = 'o' print c When Python encounters this loop, it will internally expand them into something like the Python statements shown to the left. This expanded view of how Python processes a for statement shows that nothing very complex or sophisticated is going on. Before each print c , the loop variable c is assigned the value that will be used by the body of the loop, in this case one print statement. The thing to remember when you see a for statement is that a repetitive series of assignments, one for each item in the sequence before the colon, will be interleaved with the repetition of the loop body. for i in xrange(0,9,2): print i i = 0 print i i = i + 2 print i i = i + 2 print i i = i + 2 print i i = i + 2 print i Another example shown here expands both the for loop and the xrange function (recall that xrange is a generator in Python2 , equivalent to range in Python3 ). Python stops the looping when another i = i + 2 would put i over the limit value 9 in the xrange sequence. As a test of your understanding, what do you suppose is the last thing that would be printed (after At end ) in the following script? for i in range(0,9,2): print i print At end, i Repetition 229 Loops on Condition: While Statements Python has a statement for repetition that is more primitive than the for statement. It repeats the evaluation of its body so long as some condition holds. The while state-ment demands that a condition be given rather than a variable and a sequence.
  • Book cover image for: Python for Beginners
    • Kuldeep Singh Kaswan, Jagjit Singh Dhatterwal, B Balamurugan(Authors)
    • 2023(Publication Date)
    5 Iterative Control Structure
    DOI: 10.1201/9781003202035-5
    Looping is a program or script procedure that performs repetitive (or iterative) tasks. The loop is a sequence of instructions (a block) that is executed repeatedly while or until some condition is met or satisfied. Each repetition is called an iteration. All programming and scripting languages provide loop structures, and, like other languages, Python has several looping constructs [28 ].
    Algorithm design is frequently based on iteration and conditional execution.

    5.1 The While Loop

    The output of Program 5.1 (counting.py) counts up to five.
    print (5) print (4) print (3) print (2) print (1)
    Output 5 4 3 2 1
    How would you write the code to count to 10,000? Would you copy, paste, and modify 10,000 printing statements? You could, but that would be impractical! Counting is such a common activity, and computers routinely count up to very large values, that there must be a better way. What we would really like to do is print the value of a variable (call it count), then increment the variable (count += 1), repeating this process until the variable is large enough (count == 5 or maybe count == 10000). Python has two different keywords, while and for , that enable iteration [29 ].
    Program 5.2 (loopcounting.py) uses the keyword while to count up to five:
    count = 1 while count <= 5: print (count) count += 1
    Output 1 2 3 4 5
    The while keyword in Program 5.2 (loopcounting.py) causes the variable ‘count’ to be repeatedly printed then incremented until its value reaches five. The block of statements
    print(count) count += 1
    is executed five times. After each print of the variable count
  • Book cover image for: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

    A Complete Reference Book to Master Python with Practical Applications (English Edition)

    for loop is also used to work with objects that are iterable, such as sequences. So, with the help of this loop, you can iterate over each element that exists in a sequence or collection, get one element at a time and execute the code for that element.
    Note: Iterating over an object means retrieving elements one by one from a collection or sequence. Example 8.4 >>>subjects = ['Physics','Chemistry','Biology', 'Geography','History','Economics','Language'] >>> for element in subjects: print(element) Output: Physics Chemistry Biology Geography History Economics Language >>>
    For loops can be used to iterate over a string object.
    Code: str1 = 'I love python' for item in str1: print(item) Output: I l o v e p y t h o n >>> In the preceding example, you would have noticed that each character is printed on a new line. Now, let’s execute the same code with a slight change. str1 = 'I love python' for item in str1: print(item,end =':') Output: I: :l:o:v:e: :p:y:t:h:o:n:
    So, by default when you use print command in for loop, every character is printed on a new line but you can define what you would like to have between two characters. When you write print (item,end =':') it means that a colon ‘:’ will be printed after each character. Let’s see what would be the output for end = ‘ ’.
    Code: str1 = 'I love python' for item in str1: print(item,end =' ') Output: I   l o v e   p y t h o n >>> Iterating over a list: list1 = [10,20,30,40,50] for item in list1: print(item) Output: 10 20 30 40 50 >>> Example 8.5 Write a code to find the duplicate characters in a string. string1 = input("enter the string : ") for index in range(len(string1)): count = 0 string2 = string1[(index+1):] for element in string2: if(element == string1[index]): count = count+1 print("{} is repeated in your string entry. ".format(element))
  • Book cover image for: Python for Everyone
    • Cay S. Horstmann, Rance D. Necaise(Authors)
    • 2020(Publication Date)
    • Wiley
      (Publisher)
    125 C H A P T E R 4 LOOPS C H A P T E R G O A L S To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To process strings To use a computer for simulations C H A P T E R C O N T E N T S © photo75/iStockphoto. 4.1 THE WHILE LOOP 126 SYN while Statement 127 CE 1 Don’t Think “Are We There Yet?” 130 CE 2 Infinite Loops 130 CE 3 Off-by-One Errors 131 ST 1 Special Form of the print Function 132 C&S The First Bug 132 4.2 PROBLEM SOLVING: HAND-TRACING 133 4.3 APPLICATION: PROCESSING SENTINEL VALUES 135 ST 2 Processing Sentinel Values with a Boolean Variable 138 ST 3 Redirection of Input and Output 138 4.4 PROBLEM SOLVING: STORYBOARDS 139 4.5 COMMON LOOP ALGORITHMS 141 4.6 THE FOR LOOP 145 SYN for Statement 145 SYN for Statement with range Function 146 PT 1 Count Iterations 148 HT 1 Writing a Loop 149 4.7 NESTED LOOPS 152 WE1 Average Exam Grades 155 WE2 A Grade Distribution Histogram 157 4.8 PROCESSING STRINGS 159 4.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 164 WE 3 Graphics: Bull’s Eye 167 4.10 GRAPHICS: DIGITAL IMAGE PROCESSING 169 4.11 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 174 C&S Digital Piracy 180 126 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter, you will learn about loop statements in Python, as well as techniques for writing programs that process input and simulate activities in the real world. 4.1 The while Loop In this section, you will learn about loop statements that repeatedly execute instructions until a goal has been reached. Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent inter- est per year.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.