Computer Science

While Loop in Python

A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly based on a condition. The loop continues to execute as long as the specified condition is true. It is useful for situations where the number of iterations is not known beforehand, providing flexibility in handling repetitive tasks.

Written by Perlego with AI-assistance

12 Key excerpts on "While Loop in Python"

  • Book cover image for: 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
  • 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: Job Ready Python
    eBook - PDF
    • Haythem Balti, Kimberly A. Weiss(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    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. THE WHILE LOOP An if statement evaluates a condition, performs specific activities based on that condition, and then moves on to the next set of instructions in the code. Although similar in execution, a while loop repeats a specific set of instructions as many times as needed as long as a con -dition is True. We use the term iteration to refer to each time a set of instructions runs. The basic syntax for a while loop is: while ( condition == True): < statement(s) > In order to iterate through a loop a given number of times, we use a counter variable to increment the variable by a constant measure. For example, we might increase the counter variable by 1, or we may double it. We often refer to that counter variable as an “incrementer.” 147 Lesson 7: Controlling Program Flow with Loops This changing of the counter variable used in the condition is extremely important as it ensures that the condition will eventually stop being True . Without such a condition, we would end up with an endless loop that would run forever, commonly referred to as an infinite loop. In the example of using a while statement presented in Listing 7.2, we simply display the integers 0 through 9. LISTING 7.2 Using a while statement i = 0 while ((i < 10) == True): print(i) i = i + 1 This listing goes through the following steps: 1. It starts by setting a variable i to 0. 2. It then uses a while loop that will run as long as i is less than 10. We can see that the while statement checks to see if i is less than 10.
  • 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.
  • 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)
    while loop.
    The steps are as follows:
    1. Create a script called while_python.py .
    2. Define random as the password and the Boolean validator first.
    3. Initiate the while loop and ask for the user's input.
    4. Validate the password and return an error if the input is invalid.
    5. Run the script in the terminal.
    The output should be as follows: >python while_python.py please enter your password: random Welcome back user! >python while_python.py please enter your password: none invalid password, try again... please enter your password:
    Note
    Solution for this activity can be found at page 283.

    while Versus if

    The main difference between an if and a while statement is that an if statement gives you the opportunity to branch the execution of code once based on a condition. The code in the if block is only executed once. For instance, if a value is greater than another, an if statement will branch out and execute a computation, and then proceed with the program's flow or exit.
    A while statement, however, gives you the opportunity to run a block of code multiple times as long as a condition evaluates to true. This means that a while statement will, for example, execute a computation as long as value A is greater than value B and only proceed with the program flow when A is no longer greater than B .
    In this sense, a 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.
  • Book cover image for: 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
  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    The statements within a loop constitute the loop body ; the body executes as long as the loop-controlling Boolean expression remains true. The same loop-controlling question is asked following each execution of the loop body; the structure is exited only when the test expression is false. You may hear programmers refer to looping as repetition or iteration . The loop structure in Figure 4-1 is also called a while loop because it fits the following statement: while testCondition continues to be true do someProcess endwhile In pseudocode for the while loop, the endwhile statement clearly shows where the looping structure ends. In Chapter 3, you learned to use endif to perform the same function for a selection structure. All loops can be written as while loops. Most programming languages support an additional loop format called the do-while loop. Appendix D discusses this loop. You encounter examples of looping every day, as in the following example: while you continue to be hungry take another bite of food endwhile or while an unread page remains in the reading assignment read another unread page endwhile In a business application, you might perform tasks like the following: while quantity in inventory remains low continue to order items endwhile or No Yes Figure 4-1 The loop structure 118 C H A P T E R 4 Looping Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
  • 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: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

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

    range() . This is shown in the following code:
    Code: rng = range(40,10,-3) lst = list(rng) print(lst) Output: [40, 37, 34, 31, 28, 25, 22, 19, 16, 13] Notice that in this case, value 40 is included and value 10 is excluded.

    8.3 ‘while’ loops

    The while loop executes a block of code based on a condition. The loop continues to execute as long as the condition is true . The condition is a boolean expression. If the condition always remains true, then the while loop will never stop executing.
    Syntax :
    while(condition is true): ……… Look at the following code: x = 0 while(x<10): print(x)
    This code will continue to execute and behave like an infinite loop because the value of x is never increasing and the condition for the while loop will always be true .
    Now, let’s increase the value of x by 1 at the end of every iteration.
    x = 0 while(x<10): print(x) x = x+1 Output: 0 1 2 3 4 5 6 7 8 9 >>>

    8.4 ’else’ clause with loops

    Both for and while loops can have an optional else block which will get executed when:
    • Items in for loop exhaust
    • When the boolean condition in while loop is false
    This is displayed in example 8.5 and 8.6 .
    Example 8.5
    Using while with else .
    a = 50 while a < 100: if a%10==0: print(a) a +=1 else: print('Some boolean condition false') Output: 50 60 70 80 90 Some boolean condition false >>> Example 8.6
    Using for with else .
    for a in range(50,100): if a%10==0: print(a) a +=1 else: print('Some boolean condition false') Output: 50 60 70 80 90 Some boolean condition false >>>

    8.5 continue, break, and pass statements

    If you know C, then you must have come across the continue statement. When the continue statement is encountered, the control is passed on to the beginning of the loop. All the remaining statements in the current iteration of the loop are rejected and the control moves on to the top of the loop. The continue statement is used when you want to skip the remaining statements of the loop and continue with the iteration. The continue
  • Book cover image for: Java Programming
    eBook - PDF
    C H A P T E R 6 Looping Upon completion of this chapter, you will be able to: Describe the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops Nest loops Improve loop performance Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 284 Looping C H A P T E R 6 Learning About the Loop Structure If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration. Figure 6-1 shows a diagram of the logic of a loop. In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time.
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    Within a looping structure, a Boolean expression is evaluated. If it is true , a block of statements called the loop body executes and the Boolean expression is evaluated again. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends. Figure 5-1 shows a diagram of the logic of a loop. One execution of any loop is called an iteration . %RROHDQ H[SUHVVLRQ WUXH IDOVH /RRS ERG Figure 5-1 Flowchart of a loop structure You can use a while loop to execute a body of statements continuously as long as the loop’s test condition continues to be true . A while loop consists of the following: • the keyword while • a Boolean expression within parentheses • the loop body The evaluated Boolean expression in a while statement can be either a single Boolean expression or a compound expression that uses ANDs and ORs. The body can be a single statement or any number of statements surrounded by curly braces. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 191 Creating Loops with the while Statement For example, the following code shows an integer declaration followed by a loop that causes the message Hello to display (theoretically) forever because there is no code to end the loop. A loop that never ends is called an infinite loop . An infinite loop might not actually execute infinitely.
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    Using the While Statement Probably the simplest and most frequently used loop structure to write is the while statement. The general form of the while statement is while (conditional expression) statement(s); The conditional expression, sometimes called the loop condition , is a logical condi-tion to be tested. It is enclosed in parentheses and is similar to the expressions you use for selection statements. The conditional expression must return a Boolean result Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Using the While Statement | 327 6 of true or false . An interpretation of the while statement is “ while condition is true , perform statement(s).” The statement(s) following the conditional expression makes up the body of the loop. The body of the loop is performed as long as the conditional expression evaluates to true . Like the selection construct, the statement following the conditional expres-sion can be a single statement or a series of statements surrounded by curly braces { }. Some programmers use curly braces to surround all loop bodies, even loop bodies consisting of a single statement. Consistently using curly braces increases readability. It also reduces the chance of forgetting to include the curly braces when the body contains multiple statements. You can usually kill an infinite loop by closing the window or pressing the Esc key. If that does not work, try the key combinations Ctrl+C or Ctrl+Break . Press the two keys simultaneously. The easiest way to do this is to hold down the Ctrl key and then press the second key.
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.