☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Repetition : while Loops

while Loops

Subscribe Contact


Contents

Overview

Repetition is so common in programming that most programming languages have standard repetition structures such as while loops and for loops. This is good news because the concept behind these loops is generally the same across languages, so understanding them conceptually in one language transfers to other languages.

The while loop is a condition-controlled repetition structure that repeats one or more statements until a condition is met. The condition is generally a boolean expression which can be a simple condition or compound condition. The while loop is also a pre-test loop, which means it evaluates the condition before anything inside the loop executes. This fact means we often have to prepare variables or conditions before the while statement for the condition evaluation to work as we intend.

General Form

The general code form and flowchart representation of the while loops are as follows:

while boolean_expression:
    statement_1
    statement_2
    .
    .
    statement_n

Code Details:

  • The boolean_expression can be any logical expression that evaluates to either True or False.
  • When the boolean_expression evaluates to True, statement_1 thru statement_n repeat until the condition(s) evaluate to False.
  • Note that the while statement must end with a colon (:).
  • Note that all statements included in the loop must be indented.


Figure 1: General Form of a while loop

Flowchart Details:

Let's take a look at a few examples.

Examples

Example 1

Problem: Print integers from 1 to 10 using a while loop.

Solution:

x = 1
while x < 11:
    print(x)
    x = x + 1   # See assignment operator note below

Code Details:

  • Line 1 is not part of the loop. As indicated above, because the while loop is a pre-test loop we often set up variables before the loop starts to support the loop condition(s). In this case, we're creating the variable x and initializing it to 1. We will use x in our loop as a counter.
  • The while statement on Line 2 sets the condition of x < 11, which means the loop will repeat as long as the value of x is less than 11.
  • In Line 3 we print the value of x.
  • And Line 4 adds one (increments) to the value of x. By incrementing x each time through the loop eventually x will equal 11 and the loop condition will evaluate to False and the loop will terminate.



Program Output:

1
2
3
4
5
6
7
8
9
10


Figure 2: Flowchart for Example 1


Flowchart Details:

  • Compare the flowchart to the Code Details.
  • Note that the flowchart presents a visual representation of the code solution and visa versa.
  • The flowchart includes a Start and End to depict the entire execution path of the code solution. In larger programs, the execution path would be larger and the loop would be only one segment of the larger codebase.

Assignment Operator Note: In the code solution for Example 1 above, I wrote x = x + 1 to increment the value of x. While this works, it is more common to use a more abbreviated form using the Addition Assignment Operator like this:

x += 1

This performs the same operation as x = x + 1 and is more efficient. Python supports numerous Assignment Operators, which you can review on the Operators Reference Materials  page.

Problem 1

How could we change the code in Example 1 to print the numbers from 1 to 10 in reverse order? Like this:

10
9
8
7
6
5
4
3
2
1



Problem 2

How could we change the code in Example 1 to print only the odd numbers between 1 and 10? or only the even numbers? Like this:

Odd only:

1
3
5
7
9

Even only:

2
4
5
6
10



Example 2

Problem: Prompt the user to enter integers. Accumulate the integers they enter until they indicate they are finished entering integers. Then print a report of how many integers they entered, the sum of all the integers, and the average of their integers.

This problem demonstrates several key uses of while loops, including giving users control over entering data, accumulating data values and producing summaries of that data, and handling numerous variables through a repetition structure.

Solution:

user_int = 0
counter = 0
int_sum = 0
print("-" * 50)
print("Enter a series of integers and")
print("receive a summary report.")
print("-" * 50)
print("When finished, press Enter")
print("at the prompt with no integer.")
print("-" * 50)
user_int = input("Enter your first integer: ")
while user_int != "":
   int_sum = int_sum + int(user_int)
   counter += 1
   user_int = input("Enter your next integer: ")
print("-" * 50)
print("Summary Report")
print("-" * 50)
if counter > 0:
   print("You entered " + str(counter) + " integers.")
   print("The sum of your integers is " + str(int_sum) + ".")
   print("The average of your integers is " + str(int_sum / counter) + ".")
else:
   print("You entered no integers.")
print("-" * 50)

This is a more substantial program than we have seen thus far, so take your time and work through the following code details that explain each line of this program.
Code Details:

  • As indicated in the problem description, we will use several variables in this program.
  • The variable user_int initialized on Line 1 to 0, will hold each integer value entered by the user.
  • The variable counter initialized on Line 2 to 0, will be incremented in the while loop each time the user enters another integer so that we know how many they entered in total.
  • The variable int_sum initialized on Line 3 to 0, is an accumulator, that is, each time the user enters an integer we add their integer to int_sum so that by the end we will have the sum of their integers.
  • On Lines 4, 7, 10, 16, 18, and 25 we use Python's ability to repeat a character using the * operator to draw a dashed line as separators for our output. This is commonly used to produce well-formatted output.
  • On Lines 5, 6, 7, and 8 we print instructions for the user.
  • Line 11 demonstrates the input statement to prompt the user for (in this case) an integer. Notice that the input statement includes the prompt text inside its parentheses. The user_int variable will contain what they type when they press Enter. Also, remember that anything typed by the user at an input prompt will be a string (including numbers) so we will have to cast their entries which we see on Line 13.
  • Line 12 contains our while loop. Notice the syntax here: while user_int != "":. What does this mean? Again, remember that the user's entry at the input prompt is a string, so we can take advantage of this fact by using, as our boolean expression, user_int != "" which means this while loop will continue until the user presses Enter without entering a value, as indicated in our user instructions on Lines 8 & 9 in the code.
  • Line 13 is our accumulation line, each time a user enters an integer we cast their entry (stored in the user_int variable) to an integer and add it to the int_sum accumulator variable. In this manner, each iteration of the loop builds a running total of their integers.
  • On Line 14 we increment our counter variable. Like the sum accumulator, incrementing this counter variable provides us with a running total of the number of integers they have entered.
  • Line 15 prints a new prompt on the screen asking them for their next integer. Notice that because this is inside the loop (we know this because it is indented), each time the user enters a new integer this prompt will appear again and again until the user presses Enter without typing an integer as instructed above.
  • The while loop is contained on Lines 12 thru 15. Notice the indentation, it is a requirement of Python for that indentation to be used to indicate what statements are part of the loop.
  • Line 17 prints a report header line, this is for user-friendliness.
  • Line 19 is an example of programmatic validation. We will discuss this a lot more later, but this is a good example to introduce the idea of validating user input and data in our programs. The purpose of this particular validation, if counter > 0: ensures that the user has entered at least 1 integer. If they don't then we do not want to perform the calculations because we'll get a runtime error. Any idea why?
  • The runtime error would occur if no values were entered, that is, the user pressed Entry with no value on the first prompt because computers cannot divide by zero so the average calculation on Line 22 would throw an error. So, to avoid this, we confirm at least 1 value was entered with the if statement.
  • If values were entered, then Lines 20, 21, and 22 would run and print summary values for the counter, sum, and average.
  • If no values were entered, the counter would still be zero (it was initialized to 0 on Line 2) therefore the else statement would run the print statement on Line 24.

Infinite Loops

As indicated above, while loops are pre-test loops that depend on a boolean expression condition to determine if the statements inside the loop should run and how many times. What if that boolean expression remains true, that is, there is no change to the boolean expression variables in the loop that causes it to ever turn false? The result is, what we call, an infinite loop. Infinite loops can occur accidentally though an error in coding or logic, or they can be intentional. In either case, if not terminated in some way, an infinite loop would repeat forever.

Consider the following code:

while True:
    print("Hello")

If we run this code, what is the result? Since the boolean expression condition of this while loop is simply True, and nothing inside the loop statements will terminate the loop, it will run forever.

Here's another example:

x = 1
while x > 0:
    print("Hello")

This is also an infinite loop. Why? Our boolean expression is valid and will run the loop as long as x is greater than zero. The problem is that we initialized x to equal 1, and there is nothing in the loop that changes the value of x, so it remains 1 which is greater than zero, so the boolean expression never turns False. This is a common mistake, where we write a while condition but inadvertently forget to include code inside the loop to finish the loop.

The break Statement

Python includes a break statement that terminates the execution of a loop. This is often called brute force termination because your boolean expression should handle the termination of a loop. However, the break statement is useful in some circumstances. Use of the break statement is often strongly discouraged in production code. Here's an example of its use:

counter = 1
while True:
    print(counter)
    counter += 1
    if counter > 75:
        break
print("Done")

This example is similar to our first infinite loop example above. The boolean expression is while True: so this loop will not terminate on its own based on the while condition. However, we've set a counter and increment the counter inside the loop. The if statement inside the loop includes a boolean expression that monitors the value of the counter variable. When that value is greater than 75, we use the break statement and the loop terminates.

This last example simulates what is called a counter-controlled loop, which Python provides and is called the for loop. We will cover the for loop on the next page.



 





© 2023 John Gordon
Cascade Street Publishing, LLC