0% found this document useful (0 votes)
4 views10 pages

Python Loops Depth Guide(Chatgpt)

This guide provides a comprehensive overview of Python loops, covering while loops, for loops, and their control mechanisms such as break and continue. It includes practical examples, common patterns, and debugging tips to help users understand and effectively utilize loops in programming. Additionally, it offers practice exercises and emphasizes the importance of tracing code to avoid common mistakes.

Uploaded by

souvik534p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Python Loops Depth Guide(Chatgpt)

This guide provides a comprehensive overview of Python loops, covering while loops, for loops, and their control mechanisms such as break and continue. It includes practical examples, common patterns, and debugging tips to help users understand and effectively utilize loops in programming. Additionally, it offers practice exercises and emphasizes the importance of tracing code to avoid common mistakes.

Uploaded by

souvik534p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Loops: A Complete Study Guide

From first steps to nested loops, loop control, common patterns, debugging, and solved examples

This guide is written as a self-study PDF for Python 3. It explains not only the syntax of loops, but also the
thinking behind them, so you can understand when to use them, how to build them, and how to avoid the
most common mistakes.

What you will learn: while loops, for loops, range(), break, continue, pass, loop-else, nested loops, looping
through strings and collections, counting and searching patterns, tracing code by hand, and a set of
practice programs with explanations.

Best way to use this PDF: read one section, then type the examples yourself, then change the values
and predict the output before running them.

Made for study and revision

Page 1
1. What a loop really is
A loop is a way to repeat a block of code. Instead of writing the same instructions again and again, you
write them once and let Python repeat them for you.

Loops are useful whenever the number of actions is large, repeated, or unknown in advance. Examples
include printing numbers, checking every item in a list, searching for a word in a sentence, and repeating a
task until a condition becomes true.

There are two main loop types in Python: while and for. A while loop repeats while a condition stays true.
A for loop repeats over items in a sequence or over a range of numbers.

The mental model


When you write a loop, think of it as a small machine:

1 check a condition or take the next item


2 run the body of the loop
3 update something so the next round can happen correctly
4 stop when the condition becomes false or items are finished

2. while loops
A while loop keeps running as long as its condition is true. This makes it perfect when you do not know in
advance how many times the repetition will happen.
count = 1
while count <= 5:
print(count)
count += 1

Logic: start with count = 1. Check the condition count <= 5. If it is true, print the value and increase count.
When count becomes 6, the condition becomes false and the loop stops.

This is the most important rule for while loops: you must change something inside the loop so that the
condition will eventually become false. If you do not, the loop can run forever.

Infinite loop example


x = 1
while x > 0:
print(x)
x = x - 1

Here the loop starts with x = 1. After one round, x becomes 0, so x > 0 is false and the loop ends.

while with user input


password = ''
while password != 'python123':
password = input('Enter password: ')
print('Access granted')

This is a common pattern called a sentinel loop: keep asking until the user enters the correct value.

Practical while examples


# 1) Countdown

Page 2
n = 5
while n >= 1:
print(n)
n -= 1
print('Lift off!')

# 2) Sum of digits
n = 3472
s = 0
while n > 0:
digit = n % 10
s += digit
n //= 10
print(s)

The first program counts down. The second program repeatedly takes the last digit of a number, adds it to
a sum, and removes that digit. This shows how while loops are often used in step-by-step calculations.

3. for loops
A for loop is used when you want to go through items one by one. It is the natural choice for lists, strings,
tuples, sets, dictionaries, and ranges of numbers.
for i in range(5):
print(i)

This prints 0, 1, 2, 3, 4. The range(5) function creates a sequence of numbers starting from 0 and stopping
before 5.

range() in detail
range(stop)
range(start, stop)
range(start, stop, step)

Examples: range(5) gives 0 to 4, range(2, 6) gives 2 to 5, and range(1, 10, 2) gives odd numbers from 1 to
9. The stop value is never included.

for loop with a list


fruits = ['apple', 'banana', 'mango']
for item in fruits:
print(item)

Here Python moves through the list one item at a time. The variable item gets the first element, then the
second, then the third.

for loop with a string


word = 'python'
for ch in word:
print(ch)

A string is also a sequence, so the loop gives one character at a time.

Useful for-loop patterns


# print even numbers from 2 to 10
for num in range(2, 11, 2):
print(num)

# print squares

Page 3
for n in range(1, 6):
print(n, n*n)

The step in range() can move forward or backward. For example, range(10, 0, -1) counts down from 10 to
1.

4. break, continue, and pass


break stops the loop completely. continue skips the rest of the current round and jumps to the next round.
pass does nothing and is used when Python requires a statement but you have nothing to put there yet.

break example
for n in range(1, 10):
if n == 5:
break
print(n)

The loop prints 1, 2, 3, 4 and stops when n becomes 5.

continue example
for n in range(1, 6):
if n == 3:
continue
print(n)

When n equals 3, that round is skipped. The numbers 1, 2, 4, 5 are printed.

pass example
for n in range(3):
pass
print('Loop ended')

pass is often used while planning code, building empty functions, or creating placeholders.

5. Nested loops
A nested loop is a loop inside another loop. The outer loop runs one time, and for each outer step the inner
loop runs completely.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)

The outer loop gives i = 1, 2, 3. For each value of i, the inner loop runs through j = 1, 2, 3. That means 9
pairs are printed.

Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end='■')
print()

This is one of the best examples of a nested loop. The inner loop prints each row, and the outer loop
moves to the next row.

Pattern example

Page 4
for row in range(1, 6):
for col in range(row):
print('*', end=' ')
print()

The number of stars increases by one each line because the inner loop depends on the outer loop
counter.

6. Looping through collections


Most real programs loop through data. Python makes this easy because lists, strings, tuples, sets, and
dictionaries are iterable.

List example
marks = [78, 91, 65, 88]
for m in marks:
print(m)

To get the index as well as the value, use enumerate().


for index, value in enumerate(marks):
print(index, value)

Dictionary example
student = {'name': 'Aman', 'age': 19, 'city': 'Siliguri'}
for key in student:
print(key, student[key])

for key, value in [Link]():


print(key, value)

The first form gives keys, and you can fetch the value using student[key]. The second form gives both key
and value directly.

Set example
colors = {'red', 'green', 'blue'}
for c in colors:
print(c)

A set has no fixed order, so the output order can change.

7. Very common loop logic patterns


A. Counting
nums = [2, 4, 6, 7, 9, 10]
count_even = 0
for n in nums:
if n % 2 == 0:
count_even += 1
print(count_even)

The idea: create a counter, check a condition for each item, and increase the counter when the condition
is true.

B. Summing values
nums = [5, 10, 15]

Page 5
total = 0
for n in nums:
total += n
print(total)

This is one of the most basic patterns in programming. Start with zero and keep adding.

C. Finding the maximum


nums = [12, 3, 45, 7, 19]
maximum = nums[0]
for n in nums:
if n > maximum:
maximum = n
print(maximum)

The variable maximum keeps the best answer seen so far. Every new number is compared with it.

D. Searching for a value


names = ['Ravi', 'Neha', 'Anita']
found = False
for name in names:
if name == 'Neha':
found = True
break
print(found)

A flag variable like found is useful when you need to remember whether something was discovered.

E. Building a new list


nums = [1, 2, 3, 4, 5]
squares = []
for n in nums:
[Link](n * n)
print(squares)

A loop can transform data by reading one item and pushing a changed version into a new list.

F. Filtering data
nums = [1, 2, 3, 4, 5, 6]
even_nums = []
for n in nums:
if n % 2 == 0:
even_nums.append(n)
print(even_nums)

This keeps only the items that satisfy a condition.

8. Important practice programs with logic


1) Factorial
n = 5
fact = 1
for i in range(1, n + 1):
fact *= i
print(fact)

Logic: factorial means 1 x 2 x 3 x ... x n. Keep multiplying the running result by the next number.

Page 6
2) Prime check
n = 29
is_prime = True
if n < 2:
is_prime = False
else:
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
print(is_prime)

Logic: a number is prime if it has no divisor other than 1 and itself. It is enough to test up to the square root
of the number.

3) Fibonacci sequence
a, b = 0, 1
for _ in range(10):
print(a)
a, b = b, a + b

Logic: each new number is the sum of the previous two. The tuple assignment updates both values at
once.

4) Reverse a number
n = 12345
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n //= 10
print(rev)

Logic: take the last digit, shift the reversed number left by one place, and add the digit.

5) Count digits in a number


n = 987654
count = 0
while n > 0:
n //= 10
count += 1
print(count)

Each division by 10 removes one digit.

6) Sum of list items using while


nums = [3, 6, 9, 12]
i = 0
total = 0
while i < len(nums):
total += nums[i]
i += 1
print(total)

This shows that while loops can also move through lists manually using an index.

7) Print all words longer than 4 letters

Page 7
words = ['cat', 'house', 'python', 'sun']
for w in words:
if len(w) > 4:
print(w)

This is filtering by length.

8) Frequency count
text = 'banana'
counts = {}
for ch in text:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
print(counts)

This is a classic counting pattern. The dictionary stores how many times each character appears.

9) Sum of digits in a string of digits


s = '48391'
total = 0
for ch in s:
total += int(ch)
print(total)

Because each character is a string, convert it to int before adding.

10) Simple login attempts


correct = 'admin'
attempts = 0
while attempts < 3:
name = input('Username: ')
if name == correct:
print('Welcome')
break
attempts += 1
else:
print('Too many attempts')

This combines a while loop, break, and else. The else runs only if the loop ends normally, not by break.

9. for-else and while-else


Python has a special feature where an else block can be attached to a loop. The else runs only if the loop
finishes without hitting break.
for n in range(2, 10):
if n == 7:
print('Found 7')
break
else:
print('7 not found')

This is very useful for searching. If the loop breaks because the value is found, the else block is skipped.

10. Common mistakes and how to think correctly


• Forgetting to update the loop variable in a while loop, which can create an infinite loop.

Page 8
• Using range(1, 5) and expecting 5 to appear. The stop value is excluded.

• Changing a list while iterating over it without understanding the effect.

• Using break when continue is needed, or continue when break is needed.

• Starting a maximum or minimum variable with the wrong initial value.

A good habit is to trace the loop by hand for the first few steps. Write the variable values on paper and
check whether the loop will end correctly.

11. How to trace a loop by hand


Tracing means following the variables step by step without running the program. This helps you
understand the logic and catch mistakes early.
x = 3
while x > 0:
print('x =', x)
x -= 1

Trace table:

1 Start: x = 3, condition true, print 3, then x becomes 2


2 Next: x = 2, condition true, print 2, then x becomes 1
3 Next: x = 1, condition true, print 1, then x becomes 0
4 Next check: x = 0, condition false, stop

12. Practice set with answers


Try each problem first, then compare with the solution idea below.

Exercise 1: print numbers from 1 to 10


for i in range(1, 11):
print(i)

Exercise 2: print only even numbers from 1 to 20


for i in range(1, 21):
if i % 2 == 0:
print(i)

Exercise 3: find the sum of 1 to 100


total = 0
for i in range(1, 101):
total += i
print(total)

Exercise 4: count vowels in a word


word = 'education'
vowels = 'aeiou'
count = 0
for ch in word:
if ch in vowels:
count += 1
print(count)

Page 9
Exercise 5: check whether a number is divisible by 3 and 5
n = 30
if n % 3 == 0 and n % 5 == 0:
print('Yes')
else:
print('No')

The main idea is not just to memorize code, but to recognize patterns: counting, summing, searching,
filtering, and repeated processing.

13. Final memory map


If you remember only this, you already understand the core of Python loops:

• Use while when the loop stops by a condition changing.

• Use for when you are moving through items or a known range.

• break stops, continue skips, pass does nothing.

• Nested loops mean one loop inside another.

• Most loop programs are built from a few patterns: count, sum, search, filter, and transform.

• Trace the variables by hand when the logic feels confusing.

End of guide

Page 10

You might also like