07

Phase 2 - Level 2: Number-based Looping Logic

Chapter 7 • Intermediate

90 min

Phase 2 - Level 2: Number-based Looping Logic

Introduction

Combine loops with number manipulation to solve complex problems. This level focuses on digit operations, number properties, and mathematical sequences.

Key Techniques

Digit Operations

  • Extract digits using modulo and division
  • Reverse numbers by processing digits
  • Sum and product of digits
  • Count digits

Number Properties

  • Prime number checking
  • Perfect numbers
  • Armstrong numbers
  • Palindrome numbers

Mathematical Sequences

  • Fibonacci series
  • Arithmetic progressions
  • Geometric progressions

Common Patterns

  1. Digit Extraction Loop: Process each digit of a number
  2. Range Iteration: Check all numbers in a range
  3. Accumulation: Build up results (sum, product, count)
  4. Conditional Accumulation: Add only if condition met

Hands-on Examples

Count Digits in a Number

# Take a number
num = int(input("Enter a number: "))

# Count digits
count = 0
temp = abs(num)  # Handle negative numbers

if temp == 0:
    count = 1
else:
    while temp > 0:
        count += 1
        temp //= 10  # Remove last digit

print(f"Number of digits: {count}")

Repeatedly divide by 10 (integer division) to remove the last digit. Count iterations until number becomes 0.