0
0
Pythonprogramming~10 mins

Iterating over strings in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iterating over strings
Start with string
Set index = 0
Check: index < length of string?
NoEXIT
Yes
Access character at index
Use character (e.g., print)
Increase index by 1
Back to Check
This flow shows how we start at the first character of a string and move through each character one by one until we reach the end.
Execution Sample
Python
word = "hello"
for char in word:
    print(char)
This code goes through each letter in the word "hello" and prints it on its own line.
Execution Table
IterationcharActionOutput
1"h"Print characterh
2"e"Print charactere
3"l"Print characterl
4"l"Print characterl
5"o"Print charactero
--Loop endsAll characters printed
💡 After printing 'o', no more characters left, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
charNone"h""e""l""l""o"None
Key Moments - 3 Insights
Why does the loop stop after printing 'o'?
The loop stops because it has gone through all characters in the string. As shown in the execution_table last row, there are no more characters left to process.
Is 'char' a number or a letter inside the loop?
Inside the loop, 'char' holds one letter (a string of length 1) from the word each time, as seen in the variable_tracker where 'char' changes to each letter.
Can we change characters inside the loop?
Strings are fixed in Python, so you cannot change characters directly. You can use the character for other actions, but not modify the original string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'char' at iteration 3?
A"l"
B"e"
C"o"
D"h"
💡 Hint
Check the 'char' column in the execution_table at iteration 3
At which iteration does the loop finish printing all characters?
A4
B5
C6
D3
💡 Hint
Look at the exit_note and the last iteration row in execution_table
If the string was "hi", how many rows would the execution_table have before loop ends?
A2
B3
C4
D1
💡 Hint
Number of characters plus one exit row, see execution_table row count for 5-letter word
Concept Snapshot
Iterating over strings:
Use a for loop: for char in string:
Each loop step gives one character (char) from the string.
Loop runs until all characters are processed.
Strings are read-only; you can use but not change chars directly.
Full Transcript
This lesson shows how to go through each letter in a word using a for loop in Python. We start with the first letter, print it, then move to the next until we reach the end. The variable 'char' holds each letter one by one. The loop stops when there are no more letters. This is useful to read or use each character separately. Remember, strings cannot be changed inside the loop, only read.