0% found this document useful (0 votes)
19 views6 pages

Python Looping Techniques Explained

The document provides examples and explanations of for and while loops in Python. It discusses the syntax and usage of these loops, and includes examples of iterating over sequences, using range(), modifying lists while iterating, break, continue, else clauses, nested loops, and common loop problems.

Uploaded by

The Jazz
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)
19 views6 pages

Python Looping Techniques Explained

The document provides examples and explanations of for and while loops in Python. It discusses the syntax and usage of these loops, and includes examples of iterating over sequences, using range(), modifying lists while iterating, break, continue, else clauses, nested loops, and common loop problems.

Uploaded by

The Jazz
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

Notes For Shirish

Wednesday, October 11, 2023 9:59 PM

for Loop:

Usage:
Iterate over a sequence (list, tuple, string, etc.) or other iterable objects.

Syntax:

for variable in sequence:


# Code to execute

Example:

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


for fruit in fruits:
print(fruit)

Iterating Over Strings:

You can iterate over each character of a string.

for char in "hello":


print(char)

Using the range() Function:

Produces a sequence of numbers and is often used to loop a specific number of times.

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

Modifying a List While Iterating:

Generally, you shouldn't modify the list you're looping over because it can lead to unexpected
behavior. If you need to, loop over a copy.

numbers = [1, 2, 3, 4, 5]
for num in numbers[:]: # iterating over a slice copy of the entire list
if num % 2 == 0:
[Link](num)

while Loop:

Usage:
Execute a set of statements as long as a condition is true.

Syntax:

while condition:

Quick Notes Page 1


while condition:
# Code to execute

Example:

count = 0
while count < 5:
print(count)
count += 1

while Loop with Multiple Conditions:

x, y = 0, 5
while x < 5 and y > 0:
x += 1
y -= 1

Loop Control Statements:


break: Exits the loop prematurely.
continue: Skips the rest of the current iteration and moves to the next iteration.
pass: A null operation, a placeholder when syntactically required.

Nested Loops:
Loops inside loops. Can be a combination of for and/or while loops.

Indentation: Very important in Python. It differentiates the blocks of code inside a loop.

Example:

for i in range(3): # Outer loop


for j in range(3): # Inner loop
print(i, j)

else in Loops:

An else block after a loop is executed only if the loop completes normally (i.e., without encountering
a break).

Example:

for i in range(5):
print(i)
else:
print("Loop completed!")

Using else with while:

Similar to the for loop, the else part is executed if the condition in the while loop evaluates to False.

count = 0
while count < 3:
print(count)

Quick Notes Page 2


print(count)
count += 1
else:
print("Count is no longer less than 3.")

Using else in Loops with break:

The else block is executed only if the loop didn't encounter a break.

for n in range(2, 10):


for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number') # loop fell through without finding a factor

Using for-else for Search:

The else block can be useful to check if a loop completed without finding anything.

elements = [1, 3, 5, 7]
for el in elements:
if el == 4:
print("Found!")
break
else:
print("Not found!")

Practical Tips:

Use for loops when you know the number of times the loop should run.

Use while loops when you want the loop to run based on a condition, and you're unsure of the
number of iterations.

Remember to avoid infinite loops. Always ensure the condition in a while loop can be false at some
point.

Nested loops can be CPU-intensive. Ensure you're not accidentally creating more iterations than
required.

Pattern Generation:

Rectangle Pattern:
Pattern:

*****
*****
*****

Code:

Quick Notes Page 3


Code:

for i in range(3): # Outer loop


for j in range(5): # Inner loop
print('*', end='') # Use 'end' to prevent new lines after each print
print() # New line after finishing inner loop

Right-Angled Triangle Pattern:


Pattern:

*
**
***
****
*****

Code:

for i in range(5):
for j in range(i+1):
print('*', end='')
print()

Pyramid Pattern:
Pattern:

*
***
*****
*******
*********

Code:

n=5
for i in range(n):
for j in range(n - i - 1): # Print spaces
print(' ', end='')
for j in range(2*i + 1): # Print stars
print('*', end='')
print()

Outer Loop: This determines the number of rows in the pattern.

Inner Loop(s): These determine the content of each row. If you look at the pyramid example, you see
two inner loops: one for spaces and another for stars. By carefully controlling the number of
iterations these loops make, you shape the pattern.

print() with end='': By default, the print function adds a newline after printing. By specifying the end
parameter as an empty string, you can override this behavior, allowing the next print statement to
continue on the same line.

Quick Notes Page 4


Loop Problems:
#f -> way to format string to avoid
commas
1. Sum of Natural Numbers:

n = int(input("Enter a number: "))


sum = 0
for i in range(1, n+1):
sum += i
print(f"Sum of first {n} natural numbers is: {sum}")

2. Factorial Calculation:

n = int(input("Enter a number: "))


factorial = 1
for i in range(1, n+1):
factorial *= i
print(f"Factorial of {n} is: {factorial}")

3. Fibonacci Series:

n = int(input("How many Fibonacci numbers to print? "))


a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a+b

4. Table Generation:

n = int(input("Enter a number to see its multiplication table: "))


for i in range(1, 11):
print(f"{n} x {i} = {n*i}")

5. Prime Number Check:

n = int(input("Enter a number: "))


is_prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
if is_prime and n > 1:
print(f"{n} is a prime number.")
else:
print(f"{n} is not a prime number.")

6. Reverse a Number:

n = int(input("Enter a number: "))


reversed_num = 0
while n > 0:
reversed_num = reversed_num*10 + n%10
n //= 10
print(f"Reversed number is: {reversed_num}")

7. Palindrome Check (For Number):

Quick Notes Page 5


7. Palindrome Check (For Number):

n = int(input("Enter a number: "))


original_n = n
reversed_num = 0
while n > 0:
reversed_num = reversed_num*10 + n%10
n //= 10
if original_n == reversed_num:
print(f"{original_n} is a palindrome.")
else:
print(f"{original_n} is not a palindrome.")

8. Count Digits, Vowels, Consonants, and Special Characters:

s = input("Enter a string: ")


vowels = "aeiouAEIOU"
digits = consonants = special_chars = 0
for char in s:
if [Link]():
digits += 1
elif char in vowels:
vowels += 1
elif [Link]():
consonants += 1
else:
special_chars += 1
print(f"Digits: {digits}")
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Special Characters: {special_chars}")

9. Array/List Operations (Find Max Element):

numbers = list(map(int, input("Enter numbers separated by spaces: ").split())) #taking input


max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(f"Maximum number is: {max_num}")

10. Basic String Operations (Count Occurrences of a Word):

text = input("Enter a string: ")


word = input("Enter a word to count: ")
print(f"The word '{word}' appears {[Link](word)} times.")

Quick Notes Page 6

You might also like