Classic number programs
These short programs come up again and again in classes, tests and interviews. Each is a small puzzle built from loops and conditions. Run each one, then change the numbers and run it again.
Even or odd
for n in [7, 12, 0, -3]:
print(n, "is even" if n % 2 == 0 else "is odd")Leap year
Divisible by 4, except century years, which must also divide by 400:
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
for y in [2024, 2026, 1900, 2000]:
print(y, "is a leap year" if is_leap(y) else "is not a leap year")Prime numbers
A prime has exactly two divisors: 1 and itself. Try dividing by every number from 2 up to the square root of n: if n had a bigger factor, it would also have a smaller one you'd already have found.
def is_prime(n):
if n < 2:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False # found a divisor: not prime
d += 1
return True
print(is_prime(29), is_prime(91), is_prime(2), is_prime(1))
primes = [n for n in range(2, 51) if is_prime(n)]
print(primes)
print(len(primes), "primes up to 50")The Fibonacci series
Each number is the sum of the two before it. Python can slide both values along in one line:
a, b = 0, 1
series = []
for _ in range(10):
series.append(a)
a, b = b, a + b
print(series)Palindromes
A palindrome reads the same both ways. For a number, reverse its digits and compare; for text, compare the string with its reverse s[::-1]:
def is_palindrome_number(n):
original, reversed_n = n, 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
return reversed_n == original
for n in [121, 12321, 123]:
print(n, is_palindrome_number(n))
for word in ["level", "python", "racecar"]:
print(word, word == word[::-1])Armstrong numbers
An Armstrong number equals the sum of its digits, each raised to the power of the number of digits: 153 = 1³ + 5³ + 3³.
def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d) ** power for d in digits)
print([n for n in range(1, 1001) if is_armstrong(n)])GCD and LCM
The GCD (also called HCF) is the largest number dividing both. Euclid's method replaces the pair with (b, a % b) until the remainder is 0. The LCM is then a × b ÷ GCD:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
x, y = 48, 36
print("GCD:", gcd(x, y))
print("LCM:", x * y // gcd(x, y))
import math
print("math.gcd agrees:", math.gcd(x, y))Swapping two values
Python swaps in one line; the temporary-variable way is what most other languages need:
a, b = 5, 9
a, b = b, a
print("after the swap:", a, b)
temp = a # the classic way
a = b
b = temp
print("swapped back:", a, b)Factorial
n! multiplies every whole number from 1 to n. Start the product at 1 (not 0, or everything becomes 0):
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(5), factorial(10))
import math
print(math.factorial(20)) # the built-in, for checkingFactors and perfect numbers
The factors of n are the numbers that divide it exactly. A perfect number equals the sum of its factors other than itself: 28 = 1 + 2 + 4 + 7 + 14.
def factors(n):
return [d for d in range(1, n + 1) if n % d == 0]
print(factors(28))
print([n for n in range(2, 1000) if sum(factors(n)) - n == n])Counting and adding digits
Two ways: turn the number into text, or peel digits off with % 10 and // 10:
n = 90417
print(len(str(n)), sum(int(d) for d in str(n))) # the string way
count, total, m = 0, 0, n
while m > 0: # the arithmetic way
total += m % 10
count += 1
m //= 10
print(count, total)Decimal to binary by hand
Divide by 2 again and again; the remainders, read backwards, are the binary digits:
def to_binary(n):
if n == 0:
return "0"
bits = ""
while n > 0:
bits = str(n % 2) + bits # each new remainder goes on the left
n //= 2
return bits
for n in [5, 10, 255]:
print(n, to_binary(n), bin(n)[2:])Your turn
n = int(input("Pick a whole number: "))
digits = str(n)
print(n, "is even" if n % 2 == 0 else "is odd")
print("prime:", n >= 2 and all(n % d != 0 for d in range(2, int(n ** 0.5) + 1)))
print("digit sum:", sum(int(d) for d in digits))
print("reversed:", int(digits[::-1]))
print("palindrome:", digits == digits[::-1])
print("Armstrong:", n == sum(int(d) ** len(digits) for d in digits))