0% found this document useful (0 votes)
8 views25 pages

For & While Loops

The document provides a comprehensive guide on using for and while loops in Python, detailing various tasks such as printing numbers, calculating sums, generating patterns, and checking for prime numbers. It includes basic, intermediate, and advanced examples for both loop types, explaining the theory behind each task and the steps required to implement them. The content serves as a practical reference for programming exercises involving loops.

Uploaded by

harshit sharma
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)
8 views25 pages

For & While Loops

The document provides a comprehensive guide on using for and while loops in Python, detailing various tasks such as printing numbers, calculating sums, generating patterns, and checking for prime numbers. It includes basic, intermediate, and advanced examples for both loop types, explaining the theory behind each task and the steps required to implement them. The content serves as a practical reference for programming exercises involving loops.

Uploaded by

harshit sharma
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
You are on page 1/ 25

FOR LOOP & WHILE LOOP

Basic For Loops

1. Print Numbers from 1 to 100


• Theory: A for loop can iterate over a range of numbers
using Python’s range() function.
• Steps:
1. Use for i in range(1, 101):.
2. Print each number.
• Example Output: 1, 2, 3, ..., 100.

2. Print Even Numbers in a Range


• Theory: Even numbers are divisible by 2. Use range(start,
end, step) with a step of 2 to get only even numbers.
• Steps:
1. Input a range (start and end).
2. Use for i in range(start, end+1): and check i % 2
== 0.
3. Print even numbers.

3. Sum of First n Numbers


• Theory: Add numbers from 1 to n using a loop.
• Steps:
1. Input n.
2. Initialize sum = 0.
3. Use for i in range(1, n+1): to add i to sum.
4. Print sum.

4. Print a Multiplication Table


• Theory: Use a loop to generate multiples of a number.
• Steps:
1. Input the number.
2. Use for i in range(1, 11): to calculate and print
number * i.

5. Reverse a String
• Theory: Strings can be reversed by iterating backward
using range(len(string)-1, -1, -1).
• Steps:
1. Input a string.
2. Use a loop to iterate backward.
3. Append characters to a new string.

6. Count Vowels in a String


• Theory: Check each character for membership in the set of
vowels.
• Steps:
1. Input a string.
2. Use for char in string: to check char in ['a', 'e', 'i',
'o', 'u'].
3. Count vowels.

7. Find the Factorial of a Number


• Theory: Factorial of n is the product of integers from 1 to n.
• Steps:
1. Input n.
2. Use a loop to multiply numbers from 1 to n.
3. Print the result.

8. Generate Fibonacci Series


• Theory: Fibonacci sequence starts with 0, 1, and each
subsequent number is the sum of the previous two.
• Steps:
1. Initialize a, b = 0, 1.
2. Use a loop to calculate the next numbers.
3. Print the series.

9. Check Prime Numbers in a Range


• Theory: A number is prime if divisible only by 1 and itself.
• Steps:
1. Loop through the range.
2. For each number, use another loop to check
divisibility.
3. Print primes.
10. Reverse a Number
• Theory: Reverse digits of a number using a loop.
• Steps:
1. Input a number.
2. Use while to extract and reverse digits using num
% 10.
3. Print the reversed number.

Intermediate For Loops


1. Print Patterns (Triangle, Inverted Triangle)
• Theory: Use nested loops to create rows and columns of
symbols.
• Steps:
1. For a triangle, use for i in range(1, n+1): and print * i
times.
2. For an inverted triangle, iterate downward.

2. Count Words in a String


• Theory: Words are separated by spaces. Split the string and
count the elements.
• Steps:
1. Input a string.
2. Use len(string.split()) to count words.
3. Find the Sum of Squares of Numbers
• Theory: The square of a number is number**2. Add squares
using a loop.
• Steps:
1. Loop through the range.
2. Add squares to a sum.

4. Generate Prime Numbers up to n


• Theory: Use a helper function to check primality.
• Steps:
1. Loop from 2 to n.
2. Use another loop to check divisors.

5. Check if a Number is Perfect


• Theory: A perfect number equals the sum of its divisors
(excluding itself).
• Steps:
1. Loop through numbers up to n.
2. Sum divisors and compare.

6. Find the Sum of Digits in a Number


• Theory: Use num % 10 to extract digits and add them.
• Steps:
1. Use a loop to extract and add digits.
7. Identify Armstrong Numbers in a Range
• Theory: An Armstrong number equals the sum of its digits
raised to the power of their count.
• Steps:
1. Loop through the range.
2. Check and print Armstrong numbers.

8. Calculate the Sum of Multiples of 3 and 5 Below 100


• Theory: Use a loop to check and add multiples.
• Steps:
1. Loop from 1 to 100.
2. Add numbers divisible by 3 or 5.

9. Count Frequency of Characters in a String


• Theory: Use a dictionary to store character counts.
• Steps:
1. Loop through the string.
2. Increment the count in a dictionary for each
character.

10. Merge Two Lists Element-Wise


• Theory: Use a loop to iterate over two lists simultaneously.
• Steps:
1. Use zip() to pair elements.
2. Append pairs to a new list.
Advanced For Loops

1. Identify Palindromes in a List


• Theory: A palindrome reads the same forward and backward.
For example, “madam” and “racecar” are palindromes.
• Steps:
1. Input the List:
• Accept a list of strings from the user or predefined
input.
2. Loop Through Each String:
• Use a for loop to iterate over the list.
3. Check if the String Equals Its Reverse:
• Compare the string with its reverse using slicing
(string == string[::-1]).
4. Output the Palindromes:
• If the condition is true, store or print the palindrome.

2. Generate Pascal’s Triangle


• Theory: Pascal’s triangle is a triangular array where each
number is the sum of the two numbers directly above it.
• Steps:
1. Input Number of Rows:
• Accept the number of rows from the user.
2. Start with [1]:
• Initialize the first row as [1].
3. Use Nested Loops to Generate Rows:
• Use a for loop for each row.
• Use another loop to calculate the elements of the
row:
row[i] = previous\_row[i-1] + previous\_row[i]

• Append the row to the triangle.


4. Print Each Row:
• Display the triangle row by row.

3. Encrypt a String Using a Caesar Cipher


• Theory: A Caesar cipher shifts each character by a fixed
number of positions in the alphabet. For example, shifting “a”
by 2 gives “c”.
• Steps:
1. Input the String and Shift Value:
• Accept the plaintext string and the shift value.
2. Loop Through Each Character:
• Use a for loop to process each character.
3. Shift ASCII Values:
• Convert the character to its ASCII value using
ord(), add the shift, and convert it back using chr().
• Ensure the result wraps around for alphabets
using modular arithmetic.
4. Build the Encrypted String:
• Append each shifted character to the result
string.
5. Output the Encrypted String:
• Display the final result.
4. Count Unique Elements in a List
• Theory: A set in Python automatically stores unique
elements by ignoring duplicates.
• Steps:
1. Input the List:
• Accept a list of elements.
2. Initialize an Empty Set:
• Create an empty set to store unique elements.
3. Loop Through the List:
• Use a for loop to iterate over each element.
4. Add Each Element to the Set:
• Add elements to the set using set.add().
5. Output the Unique Elements:
• Convert the set back to a list if needed and print.

5. Generate All Substrings of a String


• Theory: A substring is any contiguous sequence of
characters within a string.
• Steps:
1. Input the String:
• Accept a string from the user.
2. Use Nested Loops:
• Use one loop to select the starting index and
another loop for the ending index.
3. Extract Substrings:
• Use slicing to extract substrings
(string[start:end]).
4. Store or Print Substrings:
• Append each substring to a list or print directly.

6. Sort a List Without Using Built-In Functions


• Theory: Bubble sort repeatedly swaps adjacent elements if
they are in the wrong order.
• Steps:
1. Input the List:
• Accept a list of numbers.
2. Use Nested Loops:
• Outer loop iterates through the entire list.
• Inner loop compares adjacent elements.
3. Swap Elements if Out of Order:
• If list[i] > list[i+1], swap their positions.
4. Repeat Until Sorted:
• Continue looping until no swaps are needed.

7. Transpose a Matrix
• Theory: Transposing a matrix means swapping its rows and
columns.
• Steps:
1. Input the Matrix:
• Accept a 2D list representing the matrix.
2. Initialize a Result Matrix:
• Create an empty matrix of appropriate size.
3. Use Nested Loops to Rearrange Elements:
• Outer loop iterates through rows.
• Inner loop iterates through columns to swap
elements (result[j][i] = matrix[i][j]).
4. Output the Transposed Matrix:
• Print the result.

8. Find the GCD of Two Numbers


• Theory: The Euclidean algorithm repeatedly subtracts the
smaller number from the larger until one becomes 0.
• Steps:
1. Input Two Numbers:
• Accept two integers, a and b.
2. Loop Until One Number is 0:
• While b != 0, calculate a % b and assign the result
to b.
3. Output the GCD:
• The remaining value of a is the GCD.

9. Check If Two Strings Are Anagrams


• Theory: Two strings are anagrams if they contain the same
characters with the same frequency.
• Steps:
1. Input the Strings:
• Accept two strings.
2. Remove Non-Alphabetic Characters (Optional):
• Strip spaces and convert to lowercase.
3. Sort Both Strings:
• Use sorted() to arrange characters.
4. Compare the Sorted Strings:
• If they are equal, the strings are anagrams.
5. Output the Result:
• Print “Anagrams” or “Not Anagrams.”

10. Simulate a Dice Roll Multiple Times


• Theory: Use the random module to generate random
numbers simulating dice rolls.
• Steps:
1. Input the Number of Rolls:
• Accept how many times the dice should be
rolled.
2. Import the Random Module:
• Use import random.
3. Roll Dice in a Loop:
• Use for i in range(n): and generate random
numbers using random.randint(1, 6).
4. Track Outcomes:
• Store the results in a list or dictionary for
frequency analysis.
5. Output the Results:
• Print each roll and summarize the outcomes.
Basic While Loops

1. Print Numbers from 1 to n


• Theory: Use a while loop to increment a counter from 1 to n.
• Steps:
1. Initialize a variable i to 1.
2. Use while i <= n to iterate.
3. Print i and increment it (i += 1).

2. Calculate the Sum of Digits of a Number


• Theory: Extract digits using num % 10 and add them up.
• Steps:
1. Initialize sum = 0.
2. Use while num > 0 to process each digit.
3. Add the last digit (num % 10) to sum and update
num = num // 10.
4. Print the result.

3. Print a Reverse of a Number


• Theory: Reverse digits using num % 10 to extract digits and
build the reversed number.
• Steps:
1. Initialize reversed_num = 0.
2. Use while num > 0 to process digits.
3. Multiply reversed_num by 10 and add the last
digit.
4. Update num = num // 10.

4. Identify if a Number is a Palindrome


• Theory: A number is a palindrome if it reads the same
backward and forward.
• Steps:
1. Reverse the number using the steps in task 3.
2. Compare the reversed number with the original.

5. Find the Greatest Common Divisor


• Theory: Use the Euclidean algorithm, which repeatedly
replaces the larger number with the remainder of dividing the
larger by the smaller.
• Steps:
1. Use while b != 0 to iterate.
2. Replace a with b and b with a % b.
3. The remaining a is the GCD.

6. Reverse a String
• Theory: Reverse a string by iterating backward.
• Steps:
1. Initialize an empty result string.
2. Use while i >= 0 (where i is the index of the last
character).
3. Append each character to the result.
7. Find the Smallest Divisor of a Number
• Theory: Find the smallest number greater than 1 that
divides the given number.
• Steps:
1. Initialize i = 2.
2. Use while i <= num and check if num % i == 0.
3. Print i and break.

8. Print Fibonacci Sequence


• Theory: Each number is the sum of the previous two,
starting with 0 and 1.
• Steps:
1. Initialize a = 0, b = 1.
2. Use while to calculate the next number (c = a + b).
3. Update a = b, b = c.

9. Find the First n Multiples of a Number


• Theory: Multiply the given number by 1, 2, …, n.
• Steps:
1. Initialize i = 1.
2. Use while i <= n and calculate num * i.
3. Print the result and increment i.
10. Count Digits in a Number
• Theory: Divide the number by 10 repeatedly and count
iterations.
• Steps:
1. Initialize count = 0.
2. Use while num > 0 to divide num by 10.
3. Increment count in each iteration.

Intermediate While Loops

1. Print Factorials of Numbers


• Theory: The factorial of n is the product of all integers from
1 to n.
• Steps:
1. Input the number n.
2. Use a while loop to multiply numbers up to n.
3. Print the result.

2. Sum Even Numbers in a Range


• Theory: Even numbers are divisible by 2.
• Steps:
1. Input the range.
2. Use while to iterate through the range.
3. Add numbers divisible by 2.
3. Implement a Guessing Game
• Theory: Continuously prompt the user until they guess a
randomly generated number.
• Steps:
1. Generate a random number.
2. Use while to prompt the user.
3. Give hints (“too high” or “too low”).

4. Find Perfect Numbers up to n


• Theory: A number is perfect if the sum of its divisors equals
the number.
• Steps:
1. Iterate through numbers up to n.
2. Sum divisors for each number.
3. Print if the sum equals the number.

5. Calculate the Sum of Cubes of Digits


• Theory: For each digit, calculate its cube and sum them.
• Steps:
1. Extract digits using num % 10.
2. Cube and add them.
3. Update num = num // 10.
6. Sort a List Using Bubble Sort
• Theory: Repeatedly swap adjacent elements if out of order.
• Steps:
1. Use a while loop to iterate through the list.
2. Swap elements if needed.
3. Repeat until no swaps are made.

7. Generate Combinations of a String


• Theory: Generate all subsets of the characters.
• Steps:
1. Use nested loops to select start and end indices.
2. Extract substrings.

8. Implement Linear Search Manually


• Theory: Search for an element in a list by checking each
element sequentially.
• Steps:
1. Use while to iterate through the list.
2. Compare each element to the target.
3. Print the index if found.

9. Print Prime Numbers in a Range


• Theory: A prime number is divisible only by 1 and itself.
• Steps:
1. Use a loop to iterate through the range.
2. Check divisors for each number.
10. Count Frequency of Words in a String
• Theory: Split a string into words and count occurrences.
• Steps:
1. Split the string using .split().
2. Use a dictionary to count occurrences.

Advanced While Loops

1. Implement a Basic ATM Program


• Theory: Simulates ATM functionality, allowing the user to
check balance, deposit money, withdraw money, or exit.
• Steps:
1. Initialize Balance: Start with a variable to store
the user’s balance.
2. Display Menu: Show options like “Check
Balance,” “Deposit,” “Withdraw,” and “Exit.”
3. Use a While Loop: Keep looping until the user
chooses “Exit.”
4. Handle Each Option:
• Check Balance: Display the current balance.
• Deposit: Add the entered amount to the balance.
• Withdraw: Subtract the entered amount if it
doesn’t exceed the balance.
5. Input Validation: Ensure deposits and
withdrawals are valid numbers.
2. Simulate a Vending Machine
• Theory: A vending machine program allows users to select
items and deducts the item’s price from their balance.
• Steps:
1. Create a List of Items: Include items with names
and prices.
2. Initialize Balance: Input the user’s available
money.
3. Display Menu: Show available items with their
prices.
4. Use a While Loop: Let the user select items
repeatedly.
5. Deduct Price or Handle Errors:
• Deduct the price of the selected item from the
balance.
• Check if the balance is insufficient and display an
error.
6. Exit Option: Allow the user to exit the vending
machine.

3. Encrypt and Decrypt a String


• Theory: Implements Caesar Cipher, where each character is
shifted by a fixed number of positions in the alphabet.
• Steps:
1. Input the String and Key: Ask the user for the
string and the shift value (key).
2. Loop Through Each Character:
• Convert characters to ASCII using ord().
• Add the shift for encryption or subtract for
decryption.
• Use modulo (%) to handle wraparounds (e.g., ‘z’
to ‘a’).
3. Build the Result:
• Append each shifted character to the result
string.
4. Output the Result:
• Display the encrypted or decrypted string.
• Example:
• Input: "hello", Key: 2
• Output: "jgnnq"

4. Implement a Basic Calculator


• Theory: Performs continuous calculations (addition,
subtraction, etc.) until the user exits.
• Steps:
1. Display Operations: Show options like “Add,”
“Subtract,” “Multiply,” “Divide,” and “Exit.”
2. Use a While Loop: Keep taking inputs until the
user selects “Exit.”
3. Perform Calculations:
• Based on the operation, perform the required
arithmetic.
• Handle division by zero and invalid inputs.
4. Output the Result: Display the result after each
operation
5. Generate Random Numbers Until a Condition is Met
• Theory: Continuously generate random numbers until a
specified condition is satisfied.
• Steps:
1. Import the Random Module: Use import random.
2. Define the Condition: For example, stop when the
random number is greater than 90.
3. Use a While Loop:
• Generate numbers using random.randint().
• Print each number.
• Break the loop if the condition is met.
4. Output the Count: Track how many iterations it
took to meet the condition.

6. Find Twin Primes


• Theory: Twin primes are pairs of prime numbers that differ
by 2 (e.g., 11 and 13).
• Steps:
1. Define a Function to Check Primality:
• A number is prime if divisible only by 1 and itself.
2. Use a While Loop:
• Start from 2 and check each number for primality.
• Compare it with the previous prime to check if
they differ by 2.
3. Store and Print Twin Primes.
7. Implement Euclid’s Algorithm for GCD
• Theory: The GCD is calculated by repeatedly finding the
remainder of dividing two numbers until one becomes zero.
• Steps:
1. Input Two Numbers: Accept a and b.
2. Use a While Loop:
• Replace a with b and b with a % b.
• Continue until b == 0.
3. Output the GCD: The remaining value of a is the
GCD.

8. Generate a Magic Square


• Theory: A magic square is a square matrix where the sum
of each row, column, and diagonal is equal.
• Steps:
1. Initialize an Empty Matrix: Create a 2D list of
zeros.
2. Fill Numbers Sequentially:
• Place numbers using specific rules (e.g., start
from the middle of the first row and move diagonally).
3. Adjust for Boundaries:
• If the position goes out of bounds, wrap around
or shift positions.
4. Print the Matrix.
9. Simulate a Card Shuffling Program
• Theory: Simulates shuffling of a deck of cards using
randomness.
• Steps:
1. Create a Deck of Cards: Represent cards as a list
of strings.
2. Use random.shuffle(): Shuffle the list.
3. Allow Drawing Cards:
• Use a while loop to let the user draw cards until
the deck is empty or they choose to stop.
4. Output the Results.

10. Calculate Square Roots Using the Newton-Raphson Method


• Theory: Approximates the square root of a number
iteratively.
• Steps:
1. Input the Number: Accept the number and an
initial guess.
2. Use the Formula:
• x = \frac{x + \frac{S}{x}}{2} .
3. Iterate Until Convergence:
• Repeat until the difference between successive
approximations is small.
4. Output the Square Root.
11. Create a Spiral Matrix
• Theory: Fill a matrix in a spiral pattern (e.g., clockwise).
• Steps:
1. Initialize the Matrix: Create a 2D list.
2. Use Nested Loops:
• Fill the matrix layer by layer.
3. Adjust Row and Column Indices:
• Change directions when hitting boundaries.
4. Output the Matrix.

You might also like