For loop Programs 15th Class

 Sum of the first n natural numbers 

n = int(input("Enter a positive integer: "))
sum = 0

for i in range(1, n + 1):
    sum += i

print(f"The sum of the first {n} numbers is: {sum}")

Explanation:

  1. Input: The user is prompted to enter a positive integer n.
  2. Initialization: A variable sum is initialized to 0 to store the cumulative sum.
  3. For Loop:
    • The loop runs from 1 to n (inclusive) using range(1, n + 1).
    • In each iteration, the current number i is added to sum.
  4. Output: The final sum is printed.

Example:

If the user inputs 5, the program calculates:

text

1 + 2 + 3 + 4 + 5 = 15

and prints:

text

The sum of the first 5 numbers is: 15

Factorial using for loop

python

n = int(input("Enter a positive integer: "))
factorial = 1

for i in range(1, n + 1):
    factorial *= i

print(f"The factorial of {n} is: {factorial}")

Explanation:

  1. Input: The user enters a positive integer n.
  2. Initializationfactorial is initialized to 1 (since 0! = 1 and 1! = 1).
  3. For Loop:
    • The loop runs from 1 to n (inclusive) using range(1, n + 1).
    • In each iteration, factorial is multiplied by i.
  4. Output: The final factorial value is printed.

Fibonacci Series in Python using for Loop

The Fibonacci series is a sequence where each number is the sum of the two preceding ones, starting from 0 and 1.

Example:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...


Approach:

  1. Initialize the first two terms (a=0b=1).
  2. Loop from 2 to n (since the first two terms are already known).
  3. Update values in each iteration:
    • c = a + b (next term)
    • Shift a and b to move forward (a = bb = c).

Python Code:

python

n = int(input("Enter the number of terms: "))

a, b = 0, 1  # First two terms

if n <= 0:
    print("Please enter a positive integer.")
elif n == 1:
    print(f"Fibonacci sequence up to {n} term:")
    print(a)
else:
    print(f"Fibonacci sequence up to {n} terms:")
    print(a, end=", ")
    print(b, end=", ")
    
    for i in range(2, n):  # Loop from 2 to n-1 (since first 2 terms are printed)
        c = a + b
        print(c, end=", ")
        a, b = b, c  # Update a and b for next iteration

Explanation:

  1. Input: n (number of terms).
  2. Check for invalid inputs (n ≤ 0).
  3. Print first two terms (0, 1) if n ≥ 2.
  4. Loop from 2 to n-1 (since first two terms are already printed).
  5. Compute next term (c = a + b) and print it.
  6. Update a and b (a takes b‘s value, b takes c‘s value).

Finding Factors of a Number in Python

Factors of a number n are integers that divide n exactly without leaving a remainder.

Example:
Factors of 12 → 1, 2, 3, 4, 6, 12


Approach:

  1. Loop from 1 to n (inclusive).
  2. Check divisibility (n % i == 0).
  3. Store/print the factors.

Using for Loop (Brute Force)

python

n = int(input("Enter a positive integer: "))
#factors = []

for i in range(1, n + 1):
if n % i == 0:
print(i)

#print(f"Factors of {n}: {factors}")

Output:

plaintext

Enter a positive integer: 12
Factors of 12: [1, 2, 3, 4, 6, 12]

Check if a Number is Prime in Python using for Loop

prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Examples:

  • 5 → Prime (divisors: 1, 5)
  • 6 → Not Prime (divisors: 1, 2, 3, 6)

Approach:

Otherwise → Prime.

Check if n ≤ 1 → Not prime.

Check divisibility from 2 to √n (optimization to reduce checks).

If any divisor found → Not prime.

n = int(input('Enter a Number'))

count = 0

for i in range(1, n+1):
if n % i == 0:
count += 1

if count == 2:
print('Its a Prime')
else:
print('Its Not a Prime')

Print First n Prime Numbers in Python (Using for Loop)

Approach

  1. Start checking numbers from 2 (the first prime number).
  2. For each number, check if it’s prime (by testing divisibility up to its square root).
  3. If prime, add it to the list and increment the count.
  4. Stop when we’ve found n primes.

Solution Code

python

n = int(input("Enter how many primes you want: "))
primes = []
num = 2  # Start checking from the first prime number

while len(primes) < n:
    is_prime = True
    # Check divisibility up to √num (optimization)
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        primes.append(num)
    num += 1

print(f"First {n} prime numbers: {primes}")

Explanation

  1. Input: n (number of primes to generate).
  2. Initialize:
    • primes = [] (stores prime numbers).
    • num = 2 (start checking from 2, the smallest prime).
  3. While loop: Runs until we collect n primes.
  4. Prime Check:
    • Assume num is prime (is_prime = True).
    • Check divisibility from 2 to √num (optimization).
    • If divisible, mark is_prime = False and break.
  5. If prime: Append to primes.
  6. Increment num: Check the next number.
  7. Output: Print the list of primes.

Similar Posts

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Python Primitive Data Types & Functions: Explained with Examples

    1. Primitive Data Types Primitive data types are the most basic building blocks in Python. They represent simple, single values and are immutable (cannot be modified after creation). Key Primitive Data Types Type Description Example int Whole numbers (positive/negative) x = 10 float Decimal numbers y = 3.14 bool Boolean (True/False) is_valid = True str…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

Leave a Reply

Your email address will not be published. Required fields are marked *