Skip to main content

Command Palette

Search for a command to run...

Humble Py(thon)

Published
2 min read
G

Software engineer at the UK Astronomy Technology Centre, currently developing instrument control software for MOONS, a next-generation spectrograph for the Very Large Telescope (VLT).

I’ve been doing some Python re-learning. The specific course that I am working my way through starts from the very beginning - a very good place to start. This may feel pointless, but sometimes the material can raise features and concepts that I have forgotten about, or not made the most of. Indeed, this happened today through one of the exercises in this course.

The Exercise

Write a simple program that calculates the end time after a given number of minutes. The start time is provided as hours (0 to 23) and minutes (0 to 59). For example, if an event begins at 12:17 and lasts for 59 minutes, it will finish at 13:16.

The exercise gave the hint to use the modulus operator % to solve the problem.

After some time, and some internal debate surrounding the exercise being labeled as easy, and a small identity crisis on being a professional software engineer, I arrived at a solution. Easy!

start_hour = int(input("Enter start hour (0-23): "))
start_minute = int(input("Enter start minute (0-59): "))
duration_minutes = int(input("Enter duration in minutes: "))

total_minutes = start_hour * 60 + start_minute + duration_minutes

end_hour = (total_minutes // 60) % 24  
end_minute = total_minutes % 60

print(f"{end_hour}:{end_minute}")

Utility of the Modulus Operator

The modulus operator is not unique to Python; it just so happens that this exercise was done in Python. My new-found respect for this operator resulted in a short investigation into its potential uses. I’ve summarised a few that I came across here:

  • Checking for even or odd numbers

    • if num % 2 == 0: (even number)

    • if num % 2 != 0: (odd number)

  • Looping with wraparounds

    • index = (index + 1) % len(arr)
  • Task scheduling (e.g. do something every 5 iterations)

    • if iteration % 5 == 0:
  • Divisibility tests (e.g. checking if a number is divisible by 3)

    • if num % 3 == 0:
  • Extracting digits from a number

    • last_digit = num % 10

Thanks to this humbling exercise, I am now more aware of this operator and its usefulness. I think this is a good example of how revisiting the basics can be quite helpful. When writing code to solve future problems, I will hopefully recognise and use the modulus operator when appropriate.

Today I Learned

Part 7 of 7

Short write-ups on the cool little things I learn over time across different languages and technologies.

Start from the beginning

Why use HashiCorp's Nomad?

A Junior Software Engineer's Perspective