Palindrome Check
A palindrome reads the same forwards and backwards. This function normalizes the string and compares it to its reverse.
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("racecar"))
print(is_palindrome("A man a plan a canal panama"))
print(is_palindrome("hello"))
Try it Yourself →
Fibonacci Sequence
The Fibonacci sequence starts with 0 and 1. Each subsequent number is the sum of the two preceding ones.
def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
print(fibonacci(10))
Try it Yourself →
FizzBuzz
Print numbers 1 to 100. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", for both print "FizzBuzz".
for i in range(1, 21):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Try it Yourself →
Prime Number Check
A prime number is only divisible by 1 and itself. This function checks divisibility up to the square root for efficiency.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
for num in [2, 3, 4, 17, 29, 50]:
print(f"{num}: {is_prime(num)}")
Try it Yourself →
Factorial
The factorial of n (written n!) is the product of all positive integers up to n. Shown here with both iterative and recursive versions.
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_rec(n):
return 1 if n <= 1 else n * factorial_rec(n - 1)
print(factorial_iter(5))
print(factorial_rec(5))
Try it Yourself →
List Comprehension
List comprehensions provide a concise way to create lists. They combine a for loop and optional condition in a single line.
squares = [x ** 2 for x in range(10)]
print("Squares:", squares)
evens = [x for x in range(20) if x % 2 == 0]
print("Evens:", evens)
pairs = [(a, b) for a in range(3) for b in range(3)]
print("Pairs:", pairs)
Try it Yourself →