Week-5-1
Introduction to Loops
Loops: Control flow statements that execute code multiple times.
While Loops: Executes code as long as a condition is true.
While Loop Structure
Syntax:
while condition: body
Consists of
while
keyword, a boolean expression, and loop body.If true, body executes; if false, control passes to the next statement.
Loop Iterations
Iteration: One execution cycle through the loop.
Re-evaluates condition until false to exit the loop.
Example of a While Loop
Initialization:
current_power
to 2,user_character
to 'y'.Uses
while user_character == 'y':
to printcurrent_power
, double it, and read new input.Example flow: 2, 4, 8, exits on 'n'.
Incorporating Input with Sentinel Values
Sentinel Values: Indicate end of data, e.g., 'Q'.
Structure:
while user_value != 'Q':
continues until 'Q'.
Extracting Digits from Numbers
Extract digits via while loop:
while number > 0:
prints last digit, reduces number.Example for 902: prints 2, 0, 9.
Handling Infinite Loops
Occurs when condition is always true, freezing the program.
Example Program: Greatest Common Divisor (GCD)
Algorithm with two integers A and B:
while A != B:
subtracts the smaller from the larger until equal.Example: A = 20, B = 15 results in GCD = 5.
Example Program: Conversation Simulation
Uses
while user_input != 'goodbye':
for random responses based on input.
Example Program: Computing the Average
Ends input with zero; sums and counts input until sentinel.
Average calculated as
{sum} / {count}
.