0% found this document useful (0 votes)
2 views11 pages

Python Loops Guide

The document is a comprehensive Python learning guide focusing on loops, indexing, and hands-on practice. It covers prerequisites such as variables, data types, operators, conditional statements, and lists, followed by detailed explanations of for and while loops, including their syntax, usage, and examples. Additionally, it presents practice problems to reinforce the concepts learned.

Uploaded by

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

Python Loops Guide

The document is a comprehensive Python learning guide focusing on loops, indexing, and hands-on practice. It covers prerequisites such as variables, data types, operators, conditional statements, and lists, followed by detailed explanations of for and while loops, including their syntax, usage, and examples. Additionally, it presents practice problems to reinforce the concepts learned.

Uploaded by

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

Python Learning Guide

Loops, Indexing & Hands-On Practice


Prerequisites • For Loops • While Loops • Indexing • Practice Problems

Section 1: Prerequisites
Before diving into loops and indexing, make sure you are comfortable with the building blocks
below. Each one will be used repeatedly throughout this guide.

1.1 Variables & Data Types


A variable is a named container that stores a value. Python automatically figures out the type based
on what you assign.

# Integer
age = 25

# Float
price = 9.99

# String
name = "Alice"

# Boolean
is_active = True

Key types you need to know: int, float, str, bool.

You can always check a variable's type using type(x). For example: type(42) returns
Tip
<class 'int'>

1.2 Arithmetic & Comparison Operators


Operator Meaning Example Result
+ Addition 3+4 7
- Subtraction 10 - 3 7
* Multiplication 6*7 42
/ Division 10 / 3 3.333...
// Floor division 10 // 3 3
% Modulo (remainder) 10 % 3 1
** Exponentiation 2 ** 8 256
== Equal to 5 == 5 True
!= Not equal 5 != 3 True
<, > Less / Greater 3<7 True

1.3 Conditional Statements (if / elif / else)


Loops often rely on conditions to decide when to stop or what to do. Make sure you understand how
if-else works.

score = 75

if score >= 90:


print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
print("Grade: C or below")

# Output: Grade: B

1.4 Lists & Basic Collections


Lists are ordered collections that hold multiple values. They are the main data structure you will
iterate over using loops.

fruits = ["apple", "banana", "cherry"]


numbers = [10, 20, 30, 40, 50]
mixed = [1, "hello", True, 3.14]

print(len(fruits)) # 3 (number of items)


print(fruits[0]) # apple (first item)
print(fruits[-1]) # cherry (last item)

Remembe Python lists use zero-based indexing. The first element is always at index 0, not 1.
r
Section 2: The For Loop
A for loop repeats a block of code a known number of times, once for each item in a sequence.

2.1 Syntax
for variable in sequence:
# body — runs once per item
do_something(variable)

The variable automatically takes the value of each item in the sequence on every iteration.

2.2 Iterating Over a List


colors = ["red", "green", "blue"]

for color in colors:


print(color)

# Output:
# red
# green
# blue

2.3 Using range()


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

for i in range(5):
print(i) # 0, 1, 2, 3, 4

for i in range(1, 6):


print(i) # 1, 2, 3, 4, 5

for i in range(0, 10, 2):


print(i) # 0, 2, 4, 6, 8 (step = 2)

2.4 Using enumerate()


enumerate() gives you both the index and the value at the same time.

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):


print(index, fruit)

# Output:
# 0 apple
# 1 banana
# 2 cherry

2.5 Nested For Loops


A loop inside another loop. The inner loop completes ALL its iterations for each single iteration of
the outer loop.

for row in range(1, 4):


for col in range(1, 4):
print(row * col, end=" ")
print() # new line after each row

# Output:
# 1 2 3
# 2 4 6
# 3 6 9

Section 3: The While Loop


A while loop repeats a block of code as long as a condition is True. Unlike for loops, you do not
need to know the number of iterations in advance.

3.1 Syntax & Flow


while condition:
# body — runs while condition is True
update_condition()

For Loop While Loop


Use when iterations are known Use when iterations are unknown
Iterates over a sequence/range Repeats while a condition holds
Loop counter managed automatically You must update the counter manually
Cannot accidentally loop forever Can create an infinite loop if not careful

3.2 Basic While Loop Example


count = 1
while count <= 5:
print("Count:", count)
count += 1 # IMPORTANT: update the variable!

# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5

If you forget to update count (count += 1), the condition will never become False and
Warning
your program will loop forever. This is called an infinite loop. Press Ctrl+C to stop it.

3.3 Three Essential Parts of a While Loop

1. Initialise — set the variable before the loop starts


2. Condition — define when the loop should keep running
3. Update — change the variable so the loop eventually ends

# 1. Initialise
total = 0
n = 1

# 2. Condition
while n <= 10:
total += n # accumulate sum
n += 1 # 3. Update

print("Sum 1..10 =", total) # 55

3.4 break and continue


break — exit the loop early
num = 1
while num <= 100:
if num == 7:
break # stop immediately
print(num)
num += 1

# Prints 1 2 3 4 5 6, then stops


continue — skip to the next iteration
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # skip even numbers
print(num) # only prints odd numbers

# Output: 1 3 5 7 9

3.5 while with User Input


A common real-world use of while is repeating until the user gives valid input.

secret = "python"
guess = ""

while guess != secret:


guess = input("Guess the password: ")

print("Access granted!")

3.6 while-else (Python Specific)


Python has a unique else clause on while loops. The else block runs only if the loop ended
normally (condition became False), NOT if it ended via break.

n = 2
while n < 10:
if n % 7 == 0:
print(n, "is divisible by 7")
break
n += 1
else:
print("No number in range was divisible by 7")

# Output: 7 is divisible by 7

Section 4: How Indexing Works


Indexing lets you access individual elements inside a sequence (list, string, tuple). Python uses
zero-based indexing.
4.1 Zero-Based Positive Indexing
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# [0] [1] [2] [3] [4]

print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[4]) # elderberry

4.2 Negative Indexing


Negative indices count from the end of the list. -1 is always the last element.

fruits = ["apple", "banana", "cherry", "date", "elderberry"]


# [-5] [-4] [-3] [-2] [-1]

print(fruits[-1]) # elderberry
print(fruits[-2]) # date
print(fruits[-5]) # apple

4.3 Slicing
Slicing extracts a sub-sequence using sequence[start:stop:step]. The stop index is NOT
included.

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(nums[2:5]) # [2, 3, 4] start=2, stop=5


print(nums[:4]) # [0, 1, 2, 3] start defaults to 0
print(nums[6:]) # [6, 7, 8, 9] stop defaults to end
print(nums[::2]) # [0, 2, 4, 6, 8] every 2nd element
print(nums[::-1]) # [9,8,7,...,0] reversed list

Slicing never throws an IndexError — if your indices are out of range, Python just returns
Tip
what it can.

4.4 Indexing Strings


Strings behave exactly like lists for indexing. Each character has a position.

word = "Python"
# P y t h o n
# 0 1 2 3 4 5

print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # yth
print(word[::-1]) # nohtyP (reversed)

4.5 Combining Loops and Indexing


scores = [85, 92, 78, 95, 60]

# Using index to access and modify


for i in range(len(scores)):
if scores[i] < 70:
scores[i] = 70 # bump up failing grades

print(scores) # [85, 92, 78, 95, 70]

Section 5: Practice Problems


Work through these problems in order. They progress from simple to challenging. Try solving each
one before peeking at the hint.

Problem 1: Count Down


Description:
Using a while loop, print numbers from 10 down to 1, then print 'Blast off!'
Example:
Output: 10 9 8 7 6 5 4 3 2 1 Blast off!
Hint: Initialise a variable at 10. Condition: variable > 0. Update: subtract 1.

Problem 2: Sum of Digits


Description:
Given a number (e.g. 4321), use a while loop to find and print the sum of its digits.
Example:
Input: 4321 Output: Sum = 10
Hint: Use % 10 to get the last digit, then // 10 to remove it. Repeat while number > 0.

Problem 3: Fibonacci Sequence


Description:
Using a while loop, print the first 10 numbers of the Fibonacci sequence (0, 1, 1, 2, 3, 5, 8,
13, 21, 34).
Example:
Output: 0 1 1 2 3 5 8 13 21 34
Hint: Keep track of two variables (a, b). Each step: new_a = b, new_b = a + b.
Problem 4: Reverse a List Without reverse()
Description:
Given a list, use a for loop and indexing to build a new reversed list without using .reverse()
or [::-1].
Example:
Input: [1, 2, 3, 4, 5] Output: [5, 4, 3, 2, 1]
Hint: Loop from len(lst)-1 down to 0 using range(len(lst)-1, -1, -1) and append to a new list.

Problem 5: Find the Second Largest


Description:
Given a list of integers, use a for loop to find the second-largest number without sorting.
Example:
Input: [12, 35, 1, 10, 34, 1] Output: 34
Hint: Track two variables: largest and second. Update them as you iterate.

Problem 6: Prime Checker


Description:
Write a function is_prime(n) using a while loop that returns True if n is prime, False
otherwise.
Example:
is_prime(17) -> True is_prime(18) -> False
Hint: A number is prime if no integer from 2 to sqrt(n) divides it evenly. Use the % operator.

Problem 7: Remove Duplicates (Keep Order)


Description:
Using a for loop and a list, remove duplicate elements from a list while preserving the original
order.
Example:
Input: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] Output: [3, 1, 4, 5, 9, 2, 6]
Hint: Maintain a 'seen' list or set. Add to result only if the element has not been seen before.

Problem 8: Rotate a List by k Positions


Description:
Rotate a list to the right by k positions using slicing and indexing. Do NOT use built-in rotate
methods.
Example:
Input: [1,2,3,4,5], k=2 Output: [4, 5, 1, 2, 3]
Hint: Use slicing: result = lst[-k:] + lst[:-k]. Think about what each slice gives you.

Problem 9: Number Guessing Game


Description:
Simulate a number guessing game. Pick a secret number (e.g. 42). Use a while loop to keep
asking the user to guess. Print 'Too high', 'Too low', or 'Correct!' and count the attempts.
Example:
Guess: 50 -> Too high! Guess: 30 -> Too low! Guess: 42 -> Correct in 3
attempts!
Hint: Compare guess to secret inside the loop. Track attempts with a counter. Break on correct
guess.

Problem 10: Matrix Spiral


Description:
Given an n x n matrix represented as a list of lists, use nested for loops and indexing to print
all elements in spiral order (outer ring first, going clockwise).
Example:
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: 1 2 3 6 9 8 7 4 5
Hint: Use four pointers: top, bottom, left, right. Peel off one layer per iteration of a while loop.

Quick Reference Cheat Sheet

Concept Syntax / Example


for loop for item in list: / for i in range(n):
while loop while condition: / (remember to update!)
break Exits the loop immediately
continue Skips current iteration, goes to next
Positive index lst[0] lst[1] lst[n-1]
Negative index lst[-1] = last / lst[-2] = second-to-last
Slice lst[start:stop:step] / lst[2:5] / lst[::-1]
enumerate for i, val in enumerate(lst):
range() range(n) range(a,b) range(a,b,step)
len() len(lst) — number of items
Happy Coding!
The best way to learn loops is to write them — open your editor and tackle each problem above.

You might also like