Learning Python with my Daddy!

A friendly coding journey with problems, Python examples, and simple explanationsโ€”one day at a time.

Day 1

Finding the minimum using a for loop

Problem

Given a non-empty list of numbers, find and print the smallest value by scanning the list once with a for loop (no built-in min).

Code

numbers = [4, 2, 9, 1, 7]
smallest = numbers[0]

for n in numbers:
    if n < smallest:
        smallest = n

print(smallest)

Description

The program starts by assuming the first element is the minimum, then walks the list. Whenever it sees a smaller number, it updates smallest. After the loop, that variable holds the minimum.

Day 2

Finding divisors of a positive integer (for + if)

Problem

For a positive integer n, list every positive integer from 1 to n that divides n evenly (no remainder).

Code

n = 12

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

Description

The loop tries each candidate divisor d from 1 through n. The condition n % d == 0 is true exactly when d divides n; those values are printed.