Skip to content
Tutorials Center
My learning

Topics

Lesson 148 of 149 ยท Practice and Review

Classic Python Programs

Work through the short Python programs every learner meets - maximum, interest, Armstrong numbers, primes and sieve, Fibonacci, list rotation and swapping, and date arithmetic.

Small, well-known programs are the best way to practice the basics, because each one is short enough to hold in your head and still needs a decision or a loop. This lesson collects the classics in six groups: comparing and arithmetic, number properties, primes, Fibonacci, list operations and dates. For each program you get a clear idea, a runnable solution and the reasoning behind it, and often a second way to do the same thing.

Try to solve a program on your own before reading the solution. Once it works, ask whether a built-in could replace half of it. Python rewards knowing its standard library and list methods, and for most of these tasks a simple version and a built-in version are both worth knowing.

Comparing and basic arithmetic

The larger of two numbers

The most direct solution is an if/else. A conditional expression says the same in one line, and the built-in max() is the shortest. All three give the same answer, so choose the one that reads best in your code.

Python Maximum of two numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Area of a circle

The area is pi * r ** 2. You could hard-code 3.14159, but math.pi holds the full double-precision value, so prefer it.

Python Area with a hard-coded pi and with math.pi

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Simple and compound interest

Simple interest is principal * rate * years / 100. Compound interest adds the interest back each period, so the amount is principal * (1 + rate/100) ** years and the interest is the amount minus the principal.

Python Simple versus compound interest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Properties of numbers

Armstrong numbers

An Armstrong (narcissistic) number equals the sum of its digits, each raised to the power of the number of digits. For example 153 = 1**3 + 5**3 + 3**3. Turn the number into a string to get its digits and its length.

Python Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For factorials see Recursion, which also shows the loop version.

Prime numbers

A prime is a whole number greater than 1 with no divisors other than 1 and itself.

Trial division

If n has a divisor, it has one no larger than sqrt(n), so you only test candidates up to the integer square root. Skip even numbers after 2 to halve the work.

The sieve of Eratosthenes

To list every prime up to a limit, don't test numbers one at a time. Start with a table that marks everything as prime, then for each prime cross out its multiples, starting at its square. What survives is prime.

Python isprime and the sieve

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use trial division for a handful of numbers and the sieve when you need many primes. Third-party libraries ship ready-made helpers, for example sympy.isprime(n) (which uses faster probabilistic and deterministic tests for huge numbers) after pip install sympy.

Fibonacci numbers

Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13... The iterative version keeps just two variables, which is far cheaper than naive recursion.

A related puzzle asks for the n-th Fibonacci number that is a multiple of k. Generate the sequence, count the ones divisible by k (skipping the leading 0), and stop at the n-th. Every k has Fibonacci multiples because the sequence taken modulo k repeats.

Python n-th Fibonacci number and its multiples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Working with lists and arrays

A Python list covers what other languages call an array. For arrays of one numeric type see Arrays. These tasks come up constantly.

Length, largest value and membership

len() gives the number of items, max() the largest, and in tests membership. Membership on a list scans it, so for many lookups convert to a set.

Swapping and interchanging elements

Python's tuple assignment swaps two positions with no temporary variable. The first and last elements are positions 0 and -1.

Python Swap, interchange and test membership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rotating a list

To rotate left by d positions, the first d items move to the end. Take d % len(items) so that large values wrap around. There are three standard approaches:

  1. Slicing: items[d:] + items[:d], the shortest.
  2. Reversal algorithm: reverse the first d items, reverse the rest, then reverse the whole list. It works in place using only swaps.
  3. collections.deque.rotate(), which rotates in place and takes negative numbers for the other direction.
Python Three ways to rotate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Split a list and move the first part to the end

This is the same operation as a left rotation by k, phrased differently: split at index k and put the first part after the second.

Python Split and add the first part to the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Remainder of an array's product

Multiplying a long list can create an enormous integer. Because (a * b) % n == ((a % n) * (b % n)) % n, reduce after every step and the numbers stay small.

Python Product of an array modulo n

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dates and times

The datetime module handles all of the usual date questions. The examples use fixed dates, so the output never depends on today's date. Replace them with date.today() or datetime.now() to work with the present.

Python Date and time programs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does trial division only need to test divisors up to the square root of n?

    If n = a * b, then a and b cannot both be larger than sqrt(n), so a divisor, if one exists, appears at or below the square root.
  2. 2. In the sieve of Eratosthenes, where does crossing out the multiples of a prime p start?

    Smaller multiples such as 2*p have a smaller prime factor and were already crossed out, so p * p is the first new one.
  3. 3. What does items[d:] + items[:d] do to a list?

    The part from index d onward comes first and the first d items follow, which is a left rotation.
  4. 4. Why reduce modulo n after every multiplication when computing a big product's remainder?

    (a * b) % n equals ((a % n) * (b % n)) % n, so intermediate results can be reduced safely.
  5. 5. How can you subtract two dates to get a number of days?

    Subtracting two date objects gives a timedelta, whose days attribute holds the difference.

Summary

  • Use max(), conditional expressions or if/else to compare, and math.pi rather than a typed-in approximation.
  • Armstrong checks, primes and Fibonacci all follow the same pattern: write the rule as a small function, then test it on a range.
  • Trial division up to isqrt(n) tests one number; the sieve lists all primes up to a limit.
  • Swap with a[i], a[j] = a[j], a[i]; rotate with slicing, the reversal algorithm or deque.rotate().
  • Reduce modulo n at each step when multiplying many values.
  • date subtraction, timedelta, strftime and strptime cover most date tasks.

Next: Python Interview Questions, where these building blocks appear as short questions.