Count Numbers Divisible by 3

Count numbers from 1 to n that are divisible by 3.

BeginnerPhase 2 - Level 1: Basic LoopingExample 11 of 14
count-numbers-divisible-by-3.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Count divisible by 3
5count = 0
6for i in range(1, n + 1):
7 if i % 3 == 0:
8 count += 1
9
10print(f"Numbers divisible by 3: {count}")

Output

Enter n: 20
Numbers divisible by 3: 6

What's going on

Check each number for divisibility by 3.

Key Concepts:

Loop from 1 to n
Check if divisible by 3 using modulo
Count matches