Skip to main content
Back

Control Structures and the while Loop in Python

Study Guide - Smart Notes

Tailored notes based on your materials, expanded with key definitions, examples, and context.

Structure of Programs

Overview of Program Control Structures

In Python programming, control structures determine the flow of execution within a program. The three fundamental types are sequence, decision, and repetition structures.

  • Sequence Structure: Executes statements one after another in a linear order.

  • Decision Structure: Executes statements based on conditions (e.g., if, elif, else).

  • Repetition Structure: Repeats a block of code as long as a condition is true (e.g., while loops).

Structure Type

Description

Example

Sequence

Linear execution of statements

input → processing → output

Decision

Conditional branching

if-else statements

Repetition

Looping based on condition

while loops

Decision Structures

Conditional Execution in Python

Decision structures allow a program to choose different paths of execution based on boolean conditions.

  • if Statement: Executes a block if the condition is true.

  • if-else Statement: Executes one block if the condition is true, another if false.

  • if-elif-else Statement: Allows multiple conditions to be checked in sequence.

Syntax Example:

if condition: expression elif another_condition: expression else: expression

The condition must evaluate to True or False.

The while Loop

Introduction to the while Loop

The while loop is a fundamental repetition structure in Python. It repeatedly executes a block of code as long as a specified condition remains true.

  • Syntax:

while condition: indented block of statements

  • The condition is a boolean expression.

  • The loop body is executed repeatedly until the condition becomes false.

Planning the while Loop

Effective use of the while loop requires careful planning of initialization, condition, and update steps.

  • Initialize variables before the loop.

  • Update variables within the loop to eventually make the condition false.

Example: Compound Interest Calculation

balance = 100 TARGET = 1000 RATE = 0.05 years = 0 while balance < TARGET: balance = balance * 1.05 years = years + 1 print("Your balance is ${0:,.2f} after {1:n} years.".format(balance, years))

Formula:

while Loop Syntax and Common Errors

Proper syntax and indentation are crucial for while loops in Python.

  • Statements inside the loop must be indented to the same column position.

  • Place a colon : after the while condition.

Common Errors:

  • Incorrect Test Condition: The loop may not execute if the condition is wrong.

  • Infinite Loops: Occur if the test variable is not updated, causing the condition to never become false.

  • Off-by-One Errors: Mistakes in initializing or updating counters can lead to executing the loop one time too many or too few.

Types of while Loops

Event-Controlled Loops

An event-controlled loop continues until a specific event occurs, such as reaching a target value.

  • Example: Continue looping until balance reaches TARGET.

Count-Controlled Loops

A count-controlled loop uses a counter variable to determine how many times the loop executes.

counter = 1 while counter <= 10: print(counter) counter = counter + 1

Input Validation and Sentinel Values

Input Validation Using while Loops

while loops are commonly used to validate user input, ensuring that only acceptable values are processed.

  • Prompt the user until a valid input is received.

response_list = ['1', '2', '3'] response = '0' while response not in response_list: response = input("Enter 1, 2, or 3: ")

Sentinel Values

A sentinel value is a special value used to signal the end of input. It is not part of the data set.

  • Commonly used sentinel: -1 for numeric input.

sum1 = 0 i = 0 number = eval(input("Enter a number: ")) while number != -1: i += 1 sum1 += number number = eval(input("Enter a number: ")) if i > 0: print("The average is {0:.2f}".format(sum1/i)) else: print("No values entered.")

Common Loop Algorithms

Summing and Averaging Values

  • Initialize total and count to zero.

  • Use a while loop with a sentinel value to process input.

  • Divide total by count to compute the average.

Counting Matches

  • Count occurrences of a specific condition (e.g., negative numbers).

negatives = 0 number = input("Enter value: ") while number != "": value = eval(number) if value < 0: negatives += 1 number = input("Enter value: ") print("There were", negatives, "negative values.")

Finding Maximum and Minimum Values

  • Initialize largest or smallest with the first input value.

  • Update the variable if a new input is larger or smaller.

inputStr = input("Enter a value: ") if inputStr != "": largest = float(inputStr) inputStr = input("Enter a value: ") while inputStr != "": value = float(inputStr) if value > largest: largest = value inputStr = input("Enter a value: ") print("The maximum is:", largest) else: print("No values entered.")

Comparing Adjacent Values

  • Detect duplicate consecutive inputs.

value = input("Enter a value: ") if value == "": print("No values entered.") else: value = eval(value) inputStr = input("Enter a value: ") while inputStr != "": previous = value value = int(inputStr) if value == previous: print("Duplicate input") inputStr = input("Enter a value: ")

Loop Control Statements

The break Statement

The break statement immediately terminates the loop when executed, typically used within an if statement.

while True: num = eval(input("Enter a nonnegative number: ")) if num == -1: break # process num

The continue Statement

The continue statement skips the rest of the current loop iteration and returns to the loop header.

for x in my_list: if not isinstance(x, int): continue if x % 11 == 0: print(x, "is the first int divisible by 11.") break

Creating Menus with while Loops

Menu-Driven Programs

Menus allow users to make selections repeatedly until they choose to exit.

while True: print("1. Capital") print("2. National Bird") print("3. National Flower") print("4. Quit") num = int(input("Make a selection from the menu: ")) if num == 1: print("Washington, DC is the capital of the United States.") elif num == 2: print("The American Bald Eagle is the national bird.") elif num == 3: print("The Rose is the national flower.") elif num == 4: break

Summary Table: Loop Control Statements

Statement

Purpose

Typical Use

break

Exit loop immediately

Terminate on special input or event

continue

Skip to next iteration

Skip unwanted values

Additional info: These notes cover foundational control structures and loop algorithms in Python, suitable for introductory programming courses. Examples and tables have been expanded for clarity and completeness.

Pearson Logo

Study Prep