☰
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 : Repetition Concepts

Repetition Concepts

Subscribe Contact


Contents

Overview

Repetition in programming allows us to repeat a code block (one or more programming statements) as many times as needed to accomplish a task. Like Decisions, repetition is a very common and useful programming concept. Implementing repetition in Python involves choosing from a couple of repetition options in the language. Also like decisions, repetition operates based on conditions. The first of the repetition options is called a while loop, which repeats a code block until a specified condition is met. The second repetition option is the for loop, which repeats a code block a specified number of times. For example, let's say we want to prompt the user for several numbers and after they have entered them we want to calculate and report the average of those numbers. We could write this task out in English something like this:

1. Ask the user to enter a number
2. Store the number they entered
3. And then repeat the following:
      a. Ask the user for the next number
      b. Add the new number entered to a running total (we call this an accumulator).
      c. Check to see if they are finished, when they are, stop asking for more numbers
4. Next, calculate the average by dividing the running total by the number of numbers the user entered
5. Lastly, print a message for the user informing them of the average of the numbers they entered.

This is an example of repetition, in this case, we repeat asking for the next number until they are "finished," which is our condition. We will cover this and other examples of how to use repetition in this chapter.

Concept: Repetition

Repetition in programming, commonly referred to as looping, or iteration, allows us to execute a block of code multiple times. This is particularly useful when you need to perform repetitive tasks efficiently. Python provides several constructs for looping, the most common being the for loop and the while loop. The for loop is used to repeat a code block a specified number of times or iterate over a sequence (like a list, tuple, or string) in the order that the items appear. For instance, you can use a for loop to process each item in a list or each character in a string. The while loop, on the other hand, continues to execute as long as a specified condition is True. It's ideal for repeating an action when you don't know in advance how many times you'll need to repeat it. Both types of loops help in writing concise and effective code, eliminating the need to write the same code multiple times.

Concept: Iterable

In Python programming, an iterable is an object that can be iterated over (sometimes called a container), meaning that you can traverse through all its elements in the object, one by one. Common examples of iterables include data structures like lists, tuples, dictionaries, and strings. The key characteristic of an iterable is that it implements the __iter__() method, which returns an iterator. This iterator then allows you to use a loop (like a for loop) to go through the elements of the iterable sequentially. Each iteration asks the iterator for the "next" item, and this continues until there are no more items, at which point the iteration stops. Iterables are a fundamental concept in Python, enabling a clean, readable, and efficient way to look at and process each item in a collection of elements, without the need for indexing or manual loop management. This feature underpins much of Python's simplicity and power in handling collections of data.



Example of iteration of a list from index 0 to 4.
Concept: Accumulator (Accumulation)

In Python, accumulation refers to the process of repeatedly updating a variable by adding or appending values to it within a loop, thereby "accumulating" a final result. This concept is often used in scenarios such as summing a sequence of numbers, concatenating strings, or building up a list. For example, to calculate the sum of numbers in a list, you would initialize an accumulator variable (e.g., total = 0) and then iterate over the list, adding each element to total. Similarly, for concatenating strings, you would start with an empty string and append characters or other strings in a loop. The accumulator pattern is powerful in scenarios where a computation over a sequence of data is required, making it a fundamental technique in Python for processing collections of data, like lists, tuples, or even strings. The simplicity and versatility of this pattern make it a staple in Python programming, especially in data processing and manipulation tasks.



Example of additive accumulation during iteration of a list from index 0 to 4.

Repetition Example 1

Let's prompt the user for a series of test scores and our program will produce the average of the test scores. To calculate an average we add up all of the numbers (scores) in our list to get a total, and then we divide that calculated total by the number of scores we received from the user (in this example, the number of scores).

Here's a description and flowchart of how we might approach this problem:

As depicted in the flowchart, a common approach would be to set a variable that will hold our running total age (we call this an accumulator). Then prompt the user for the first test score. Then in a repetition structure (loop), we add each newly entered score to the accumulator. After adding we prompt the user for the next score. We repeat these steps over and over until the user indicates there are no more scores to enter (we will take a closer look at how the user indicates this on the next pages). When it exits the loop, the accumulator would contain the total score. We could then calculate the average score after the loop by dividing the total score by the number of scores entered by the user.



Figure 1: Flowchart for Repetition Example 1

Repetition Example 2

For our second example, suppose we have a list of the ages of every person in Utah and we want to calculate the average age.

Looking at census data for 2020, the population of Utah was 3,271,616 people. It would be absurd to try to manually calculate the average of that many numbers (ages). So, if we have a list of all the ages (let's say in a file), we could read those numbers into a Python program, add them all up and then divide by 3,271,616. To do this efficiently, we would use a repetition structure.

Here's a description and flowchart of how we might approach this problem:

As depicted in the flowchart, a common approach would be to set a variable that will hold our running total age (we call this an accumulator). Then we read each age from the data source (we'll learn more about how to read data from outside sources later) and in a repetition structure (loop) we add each newly read age to the accumulator. We repeat that step over and over until there are no more pages to read from the data source. In this example, the loop would repeat 3,271,616 times. When it exits the loop, the accumulator would contain the total age. We could then calculate the average age after the loop by dividing the total age by the number of ages.

In the following several pages we will take a look at the while loop and the for loop which are two of the primary repetition structures that we use in programming. We'll also look at several examples of problems that are solved by repetition structures.



Figure 2: Flowchart for Repetition Example 2






© 2023 John Gordon
Cascade Street Publishing, LLC