Skip to main content

๐Ÿ’› โ€” Loop Drill I: Count 1..N

Taskโ€‹

  • Create a file named count_to_n.py.
  • Read an integer N.
  • Print the numbers 1..N (one per line).
  • If N <= 0, print a message instead of looping.
  • (Optional) Also print N..1 (countdown).
  • (Optional) Print the sum of 1..N at the end.

Example runโ€‹

$ python count_to_n.py
N: 5
1
2
3
4
5
sum = 15

Solution (ATTEMPT FIRST)โ€‹

Show spoiler code (count_to_n.py)

Basic loop practice. Also shows how to accumulate a sum.

count_to_n.py
"""count_to_n.py

Loop drill: count up to N (and maybe back down).
"""

N = int(input("N: ").strip())

if N <= 0:
print("N must be positive to count. (Try 1, 2, 5, ...)" )
else:
total = 0
for i in range(1, N + 1):
print(i)
total += i # add i into the running total

print(f"sum = {total}")

# Optional countdown (commented):
# for i in range(N, 0, -1):
# print(i)

Docs / Tutorialsโ€‹