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

4 Key excerpts on "For Loop in Python"

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.
  • Hands on Data Science for Biologists Using Python
    • Yasha Hasija, Rajkumar Chakraborty(Authors)
    • 2021(Publication Date)
    • CRC Press
      (Publisher)

    ...However, we often prefer to loop through words in texts or items in lists or through keys and values of a dictionary. In such cases, we require definite loops like the “for” loop for accomplishing these tasks of iterating over sequence datatypes. The “for” loop runs through each item in a set of items. The syntax of a “for” loop is similar to the “while” loop: there is a “for” statement and a block of code under that statement. Code: drug_name = ['Metformin', 'Acarbose', 'Canagliflozin','Dapagliflozin'] for drug in drug_name: print(drug) Output: Metformin Acarbose Canagliflozin Dapagliflozin The “for” loop iterates over each item in the list and runs the block statements for all of the items on the list. In simple English, this for loop can be translated as “run the block of code under the “for” loop for every drug in the drug list”. In the “for” statement, the drug is the variable that changes with every iteration. This variable can have any name like other variables. Code: drug_name = ['Metformin', 'Acarbose', 'Canagliflozin','Dapagliflozin'] for temp in drug_name: print(temp) Output: Metformin Acarbose Canagliflozin Dapagliflozin Examine how the output with the variable name “drug” is the same as with the variable name “temp”. Breaking a Loop In order to exit a loop before its full execution, a Python “break” statement is used...

  • Bioinformatics Algorithms
    eBook - ePub

    Bioinformatics Algorithms

    Design and Implementation in Python

    • Miguel Rocha, Pedro G. Ferreira(Authors)
    • 2018(Publication Date)
    • Academic Press
      (Publisher)

    ...The pseudo-code of the block of statements within a while cycle is the following: In this case, the statements in the block will be executed while the condition holds true. When the condition switches to false, the loop ends, and the program flow follows with the next statement. This means that, to avoid infinite cycles, the programmer needs to insure that the condition will be false at some point in the program execution. In the following example, the value of the variable a is printed, while it is smaller than 100. At each iteration its value is incremented by 10, thus insuring the cycle terminates: As an illustration of the potential of while cycles, in the next example, we develop a function that searches if a given element is present in a list of numbers. The function returns the position of the first occurrence of that element, or −1 if the element does not occur in the list. 2.3.5 Iterative Loop Statements If we know in advance that we need to execute a block of statements a fixed number of times, a for loop can be used. This control structure provides an iterative loop through all the elements of an iterator, which can be retrieved from a container variable or using a function that yields these values. An iterable object is any object that can be iterated over, i.e. that provides a mechanism to go through all its elements. Strings or lists are examples of such objects. These objects are particularly suitable to be iterated in for loops. Indeed, iteration through a range of values is one of the most common tasks in programming. In the following example, the code iterates through all the characters in a string and increments the value of the variable seq _ len for each of them, obtaining in the end the length of the string. There are also functions that return iterators, which can be used directly in these loops. Python offers a function range to generate an immutable sequence of integers between a start and a stop value, with an increment step value...

  • Geometric Computation: Foundations for Design
    • Joy Ko, Kyle Steinfeld(Authors)
    • 2018(Publication Date)
    • Routledge
      (Publisher)

    ...Conditional statements have allowed us to define blocks of code that execute only when a given condition is met. Similarly, loop statements have allowed us to author codeblocks that execute once for each item in a given collection. Allowing a wide berth to this definition, even larger-scale structures of code such as functions, modules, even method attributes of an object, could be included, as they are essentially constructions that control which sets of statements are executed, and in which order. Leaving these larger-scale structures aside for the moment, this section focuses on local control flow structures in Python, those statements that operate within a single script and allow us to alter the way nearby statements are executed or evaluated. It turns out that there are only a small handful of such statements, which, with judicious application, are enough to carry us through the remainder of this chapter. Presented here are three local structures of control that are prevalent in Python programming. First, while we have seen the conditional if statement in its most minimal form, we expand our treatment to account for a wider assortment of choice mechanisms. Next, we’ll introduce the while statement, a loop structure that, like the for loop, causes the subsequent block of code to be executed repeatedly, but rather than being controlled by a collection of items, is controlled by a given condition. Finally, we present try, which, along with some related statements, form a mechanism for dealing with uncertainty and handling the inevitable errors that arise when our code is executed. There is one major category of control flow statements that we will defer until later in the chapter...

  • Coding + Math
    eBook - ePub

    Coding + Math

    Strengthen K–5 Math Skills With Computer Science

    ...However, conditionals can also be modeled effectively through the use of flowcharts or unplugged programming activities. Loops Loops are a mainstay of programming, allowing far more efficiency in programming tasks that must be repeated until a desired result is achieved. For example, if a programmer wants the program to perform a task repeatedly a certain number of times but wants the user to determine that number at runtime, the code would utilize a “for-loop”, accepting user input to set the number of intervals. In Scratch terminology, the coder could use an “ask” block to get user input on how many times the sprite should follow a certain sequence. In that case, the code would contain a “repeat” block to encapsulate the loop containing the blocks in the sequence. This not only prevents the need for repetitive code, but also avoids restricting the loop to some predetermined maximum number of iterations. While loops provide additional power and flexibility to the programmer, they also present a source of potential errors if not used properly. Research has shown the use of endless loops in the Scratch environment as a source of many programming errors, where programs get stuck in never-ending loops (Zhang & Nouri, 2019). Varied understanding of different types of loops, particularly nested loops, have often caused confusion, but this confusion has been less prevalent for Scratch users as compared to text-based languages, since loops are easier to identify in a block-based environment (Mladenovi et al., 2017). Perhaps the best analogy for loops in math is summation notation (∑ 2 i, e.g., meaning the summation of all values of 2 i, starting with 1 and ending with 10); this concept is usually not covered until secondary school...