Skip to main content
Indietro

Decision and Repetition Structures in Python Programming

Guida di studio - Note intelligenti

Appunti personalizzati basati sui tuoi materiali, ampliati con definizioni chiave, esempi e contesto.

Decision Structures and Boolean Logic

The if Statement

The if statement is a fundamental control structure in programming that allows a program to execute certain statements only when a specified condition is true. This enables the creation of multiple paths of execution within a program.

  • Control structure: Logical design that controls the order in which statements execute.

  • Sequence structure: Statements execute in the order they appear, from top to bottom.

  • Decision structure: Executes specific actions only if a condition exists (also called selection structure).

  • In flowcharts, a diamond shape represents a true/false condition to be tested.

Python syntax:

if condition: statement statement

The condition is evaluated as either true or false. If true, the indented block is executed; otherwise, it is skipped.

Boolean Expressions and Relational Operators

A Boolean expression is an expression that evaluates to either true or false. These are commonly used in decision structures to control program flow.

  • Relational operators compare two values and return a Boolean result.

  • Common relational operators include: >, <, >=, <=, ==, !=.

Expression

Meaning

x > y

Is x greater than y?

x < y

Is x less than y?

x >= y

Is x greater than or equal to y?

x <= y

Is x less than or equal to y?

x == y

Is x equal to y?

x != y

Is x not equal to y?

Boolean expressions using relational operators

The if-else Statement

The if-else statement provides two alternative paths of execution. If the condition is true, one block of statements is executed; if false, another block is executed.

if condition: statements else: other statements

  • Both if and else clauses must be aligned, and statements must be consistently indented.

Conditional execution in an if-else statement

Comparing Strings

Strings can be compared using relational operators. Comparisons are case-sensitive and are performed character by character based on ASCII values.

  • == and != test for equality and inequality.

  • >, <, >=, <= compare strings lexicographically.

  • If one string is a substring of another, the longer string is considered greater.

ASCII comparison of 'Mary' and 'Mark'

Nested Decision Structures and the if-elif-else Statement

Decision structures can be nested, meaning an if or if-else statement can appear inside another. This is useful for checking multiple conditions in sequence.

  • Proper indentation is crucial for readability and correct execution in Python.

  • The if-elif-else statement simplifies complex nested decisions by aligning all clauses.

if condition1: statements elif condition2: statements else: statements

This structure is easier to read and maintain than deeply nested if-else statements.

Logical Operators

Logical operators allow the creation of complex Boolean expressions by combining simpler ones.

  • and: True if both operands are true.

  • or: True if at least one operand is true.

  • not: Reverses the logical value of its operand.

Expression

Meaning

x >= y and x < b

Is x greater than y AND is x less than b?

x == y or x == z

Is x equal to y OR is x equal to z?

Short-circuit evaluation in logical operators

Boolean Variables

A Boolean variable can reference one of two values: True or False. These are often used as flags to signal when a condition exists in a program.

  • Flags are set to False when a condition does not exist, and True when it does.

Repetition Structures

Introduction to Repetition Structures

Repetition structures, or loops, allow a program to repeat a section of code multiple times. This avoids code duplication and makes programs more efficient and easier to maintain.

  • Condition-controlled loop: Repeats as long as a condition is true (e.g., while loop).

  • Count-controlled loop: Repeats a specific number of times (e.g., for loop).

The while Loop: a Condition-Controlled Loop

The while loop repeats a block of statements as long as a specified condition is true. It is known as a pretest loop because the condition is tested before each iteration.

while condition: statements

  • Each repetition is called an iteration.

  • If the condition is initially false, the loop body will not execute at all.

  • Infinite loops occur if the condition never becomes false.

Example of an infinite loop

The for Loop: a Count-Controlled Loop

The for loop is used to iterate a specific number of times, typically over a sequence of values. In Python, the range() function is commonly used to generate such sequences.

for variable in range(start, stop, step): statements

  • The target variable takes on each value in the sequence for each iteration.

  • range(n) generates numbers from 0 up to (but not including) n.

  • Three arguments: range(start, stop, step).

Using the range function with a for loop

Calculating a Running Total

Programs often need to calculate the total of a series of numbers. This is done using an accumulator variable, which is updated within a loop.

  • Initialize the accumulator to 0 before the loop.

  • Add each new value to the accumulator during each iteration.

Sentinels

A sentinel is a special value that marks the end of a sequence of items. When a program encounters a sentinel, it knows to terminate the loop.

  • Sentinel values must be unique and not mistaken for regular data.

Input Validation Loops

Input validation ensures that only valid data is processed by the program. This is typically implemented using a loop that continues to prompt the user until valid input is received.

  • "Garbage in, garbage out" (GIGO): Invalid input leads to invalid output.

  • A priming read is the initial input operation before entering the validation loop.

Nested Loops

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop. This is useful for processing multi-dimensional data or repeated tasks within repeated tasks.

  • Total iterations = (iterations of outer loop) × (iterations of inner loop).

Summary

  • Decision structures: single, dual, and nested alternatives using if, if-else, and if-elif-else.

  • Boolean expressions and relational/logical operators.

  • String comparison and Boolean variables.

  • Repetition structures: while and for loops, infinite loops, and nested loops.

  • Use of range() in for loops, running totals, augmented assignment operators, sentinels, and input validation.

Pearson Logo

Study Prep