Computer Science

Python Loops

Python loops are control structures that allow for the repeated execution of a block of code. The "for" loop iterates over a sequence of elements, while the "while" loop continues execution as long as a specified condition is true. Loops are essential for automating repetitive tasks and iterating through data structures in Python programs.

Written by Perlego with AI-assistance

9 Key excerpts on "Python Loops"

  • Python Fundamentals
    eBook - ePub

    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)
    while statement can be considered a loop. We'll look at looping structures next.

    Loops

    In Python, looks (just as in any other language) are a way to execute a specific block of code several times. In particular, loops are used to iterate or loop over what we call iterables. For the purposes of this chapter, we can define an iterable as follows:
    • Anything that can be looped over (that is, you can loop over a string or a file)
    • Anything that can appear on the right-hand side of a for loop, for example, for x in iterable
    A few examples of common iterables include the following:
    • Strings
    • Lists
    • Dictionaries
    • Files
    You can think of an iterable as a collection of homogeneous things that have been grouped together to form a large collective. The individuals in the group have the same properties, and when they are combined, they form something new.
    Consider the example of cars in a car yard. We can consider the car yard as the collection or iterable and the individual cars as the constituent members of the car yard. If you were shopping for a car, you would probably have a couple of qualities that you are looking for. You walk into the car yard and start going from car to car looking for one that satisfies your conditions or comes as close as possible to satisfying your conditions. The act of going from car to car and repeating the aforementioned inspection operation is basically what looping is.
    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
  • 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
  • Python Made Simple
    eBook - ePub

    Python Made Simple

    Learn Python programming in easy steps with examples

    if…else statement that is in the else block. If the condition evaluates to true, then the second number is largest will be displayed; otherwise, the third number is largest displayed. After printing appropriate messages, it prints the end of the program message.

    Looping statements

    Looping statements are also known as iteration control statements. An iterative control statement is a control statement that provides the repeated execution of a set of instructions. With decision making statements, we can make decisions on which statement(s) should be executed when the condition is true or false. Sometimes, there is a need to execute the set of statements repeatedly until a certain condition is true. So, looping statements provide the facility to execute the set of statements repeatedly until the condition becomes false. There are mainly two types of looping statements, which are explained in the following sections.

    The while loop

    The while loop is the most basic looping statement available in Python. It allows you to execute the set of statements repeatedly as long as the condition evaluates to true. It is mostly used in those cases where the programmer does not know in advance how many times the loop will be executed. The general form of the while loop is as follows:
    while condition:    statement(s)
    In the preceding representation, the condition is that any valid Python test expression that may use a relational or logical operator which must be followed by a colon (: ) symbol. Here, the statement(s) represent one statement or group of statements. In the while loop, first the test condition is checked and if it evaluates to true, then the statements contained in the block of the loop are executed. The execution continues as long as the condition remains true. When the condition becomes false, the while statement ends and the control moves to the next statement in the program.
    The while loop is also called entry-controlled loop because the condition is checked before the start of execution of the loop. The decision regarding whether the body of the loop is executed or not depends on the test condition which is evaluated at the entry point of the while loop. The following flowchart shows the flow of the while
  • Programming in Python
    eBook - ePub

    Programming in Python

    Learn the Powerful Object-Oriented Programming

    Table 4.2 .
    Loop Description
    while It iterates a statement or group of statements while a given condition evaluates to true. It evaluates the test expression before executing the loop body.
    for It executes a sequence of statements multiple times until the test expression evaluates to true.
    Nested loop A loop either while or for, inside another loop is called nesting of loop.
    Table 4.2. Python loop control structures

    4.2.2. Python while Loop

    The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. It is also called a preset loop that is used when it is not predetermined how many times the loop will be iterated. The syntax of while loop is given as follows:
    while test_condition: body of loop
    In while loop, initially, the test expression is evaluated. If the test_expression evaluates to true only then the body of the loop is executed. After one iteration, the test expression is evaluated and tested again for true or false. This process continues until the test_expression evaluates to false. On the other hand, if the test_expression evaluates to false at the first time, the body of loop will not be executed at all and the first statement after the while loop will be executed.
    Fig. 4.4. Flow chart representing while loop
    Indentation determines the body of the while loop in Python. Body starts with indentation and the first unindented line marks the end of the loop. The flow chart of while loop is given in Fig. 4.4 .
    Code 4.7
  • Introduction to Engineering and Scientific Computing with Python
    • David E. Clough, Steven C. Chapra(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    mid-test loop. Depending on when the end condition is met, there may be 1, 10, 100, or 1,000 repetitions.
    The second loop scenarios are illustrated in Figure 4.4 where the number of loop repetitions is known ahead of the loop being entered. The first is the list-driven structure, and this is an important feature of Python1 . It is based on a list of items where the loop is repeated for each item in the list in sequence.
    The second is the count-controlled loop, a structure that has been around since the earliest programming languages. This loop is characterized by three parameters: a start value, end value, and step value. After each loop iteration, the step value is added to the loop counter, and, unless the end value is equaled or exceeded, the loop is repeated. In this way, it is possible to calculate ahead of loop entry how many times the loop will be repeated. In fact, once the loop is being executed, modifying the step and stop values will not affect the number of repetitions, since they are precalculated.
    In a following section of this chapter, you will learn how to implement the repetition structures in Python. It will be important to reference the figures shown here to keep in mind a good picture of the structures. Also, you will learn some variations and combinations of the structures. This will also be the case for the selection structures.

    4.2 Implementing Decision Structures with Python

    Learning the general programming structures is important because it prepares you to implement these with different programming languages. You can approach a new language, such as Python, with a question, “Since I already know what a Two-way If is, how do I implement a Two-way If in Python?” In other words, once you learn a procedural programming language like Python, you are never starting from scratch.
  • Machine Learning for Decision Sciences with Case Studies in Python
    • S. Sumathi, Suresh Rajappa, L Ashok Kumar, Surekha Paneerselvam(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    Print (i);
  • While loop: Repeats the group of a statement if the given condition is True. For example, add the first five natural numbers.
    I = 0; While y<6: y = y+y I++;
  • Nested loop: To use the loop inside another loop is called a nested loop. Let’s take an example of distributing four chocolates to each student of the class. The nested loop will work here, as we have to use two loops, that is, for chocolate and students. chocolate = [“Cadbury”, “kitkat” “ mars”, “ galaxy”]; students = [“Alice”, “ Jhon”, “ Nick” ]; For students in students : For chocolate in chocolate : Print (students + “got” + chocolate);
  • 2.4.3.3 Loop Control Statements
    To change the sequence of executing a code, Python provides multiple control statements. Following are the loop control statements:
    1. Break statement: To exit from a loop, break statements are used. Let’s take the example of 20 enrollment numbers, and the user wants to print only ten enrollment numbers. x=1; While x< = 20: Ifx ==10: break Print (x) x++;
    2. Continue statement: It is similar to the break statement, it exits the loop, but the loop itself is not exited. Let’s consider the same previous example and replace the break with continue. x = 1; While x < = 20: if x ==10: continue Print (x) x++;
    3. Pass statement: It is also called a null operator. Nothing happens when it is executed. Consider a project that two programmers complete; one falls sick and cannot come on a specific day. The problem is that another programmer cannot hold the work. In this case, all the functions that the sick programmer wrote will be left empty using the pass statement. Let’s consider the same previous example with a pass statement. x=1; While x < = 20: if x ==10: pass print “10 not included” Print (x) x++;
  • Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

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

    while loops fall under this category of the control structure.
    It is very important to take care of indentation while working with control structures.

    8.7 Python iterators

    An object that can be iterated upon is known as an iterator . It is an object that contains a countable number of values. It can be iterated upon, meaning that you can traverse through all the values. This object implements the iterator protocol, which consists of __iter__() and __next__() methods. Sequences such as lists, tuples, etc. are iterable objects that have an iter() method which can be used to get an iterator. Suppose we have a list list1 = [1,2,3,4,5].
    We can print all the values of the list using the for loop as follows :
    >>> list1 =[1,2,3,4,5] >>>for i in list1: print(i) 1 2 3 4 5 We can also create an iterator object and return the value. >>> list1 =[1,2,3,4,5] >>> list_iter = iter(list1) >>> print(next(list_iter)) 1 >>> print(next(list_iter)) 2 >>> print(next(list_iter)) 3 >>> print(next(list_iter)) 4 >>> print(next(list_iter)) 5
    The for loop functions by creating an iterator() object and then it executes the next() method for each loop.

    8.8 Python generators

    Python generators are used to create iterators in a very simple way. A generator is a subclass of an iterator. When we create an iterator we use the __iter()__ and __next()__ functions but that is not the case with generators. We use a function for creating a Python generator. A generator makes use of the ‘yield’ keyword instead of the ‘return’ keyword. A function that contains at least one yield statement is a generator. The return keyword terminates the function and anything placed after ‘return’ will never be executed. The ‘yield’ statement, on the other hand, pauses the function and saves the states, transfers the control to the caller, and then continues from there on for successive calls. When the function terminates, stopIteration
  • Learn C Programming
    eBook - ePub

    Learn C Programming

    A beginner's guide to learning C programming the easy and disciplined way

    Exploring Loops and Iteration
    Some operations need to be repeated one or more times before their result is completely evaluated. The code to be repeated could be copied the required number of times, but this would be cumbersome. Instead, for this, there are loops—for …, while …, and do … while loops. Loops are for statements that must be evaluated multiple times. We will explore C loops. After considering loops, the much-maligned goto statement will be considered.
    The following topics will be covered in this chapter:
    • Understanding brute-force repetition and why it might be bad
    • Exploring looping with the while()… statement
    • Exploring looping with the for()… statement
    • Exploring looping with the do … while() statement
    • Understanding when you would use each of these looping statements
    • Understanding how loops could be interchanged, if necessary
    • Exploring the good, the bad, and the ugly of using goto
    • Exploring safe alternatives to goto—continue and break
    • Understanding the appropriate use of loops that never end

    Technical requirements

    As detailed in the Technical requirements section of Chapter 1 ,Running Hello, World! , continue to use the tools you have chosen.
    The source code for this chapter can be found athttps://github.com/PacktPublishing/Learn-C-Programming .

    Understanding repetition

    Very often, we need to perform a series of statements repeatedly. We might want to perform a calculation on each member of a set of values, or we might want to perform a calculation using all of the members in a set of values. Given a collection of values, we also might want to iterate over the whole collection to find the desired value, to count all the values, to perform some kind of calculation on them, or to manipulate the set in some way—say, to sort it.
    There are a number of ways to do this. The simplest, yet most restrictive way is the brute-force method
  • Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    5
    Repetition with a Loop: The  while    Statement    
    We have seen in the programs we have written that the order in which the statements are written makes a difference. This illustrates a key principle of computing known as sequence  .
    In Chapter  4, we saw that statements placed inside an if  or switch  statement are only performed if a certain condition is true. Such conditional programming illustrates a second key principle of computing known as selection  .
    In this chapter and the next, we will see that, sometimes, one or more statements need to be performed repeatedly   in a computer program. This will illustrate a third key principle in computing: repetition  .
    Human beings often find repetitive tasks to be tedious. In contrast, computers can provide an ideal way to perform repetitive tasks.  Repetition as Long as a Certain Condition Is True
    Like the if  statement, each repetition structure in this chapter will make use of a condition  . This condition will determine whether the repetition should continue  .
    Once again, let’ s consider a cooking recipe as an analogy to a computer program. Suppose a certain dough recipe says that you are to mix the ingredients and then repeatedly   add ½  cup of flour as long as   you can still stir the mixture with a spoon. A flowchart of this recipe might look like the following:
    Similarly, in computer programming, there are sometimes sets of statements that we would like to perform repeatedly  , but only as long as   a certain condition is true.
    Repetition with the while   Statement
    Processing provides several programming structures that can be used for creating repetition. One of the more versatile of these repetition structures is the while   statement. The basic form of the while
  • 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.