Sliding into Python Coding

Posted by Neville on April 25, 2016 under How To, Python, Resources, Training | Comments are off for this article

Coding In Python

Although the task I am about to outline is quite trivial, it does demonstrate some of the benefits of using Python for coding.

Missing Vowels

The task I set myself was to modify an example from the first MIT Computational Thinking Massive Open Online Course (MOOC) that I completed 2 years ago, and then promptly ignored. That task asked students to code a function that could be used to identify if a particular letter of the alphabet is a vowel.

Looking back at the code I saved from that exercise there were a couple of ways that I achieved that, and so I decided to try to extend the exercise and see if I could use that to extract all of the vowels from a phrase. Yes, I know, a trivial task, but in doing so it provided me with an opportunity to hone some skills.

First I had confirmed for me the benefit of working from something like a flow-chart, that helped to lay out the steps needed, to get them into some sort of order and perhaps improve the efficiency. The flow-chart shown here is a result of that pre-planning. (Actually it was not pre-planning, but a bit of an afterthought, that helped to reduce the amount of coding to produce the same result. That coding is actually easier to read, and much more concise than the first attempts.)Flow Chart

The code that came from that flow chart is actually much less wordy, but still relatively easy to follow, even for a novice with little experience at working out what code is meant to achieve. That is a result of the almost natural language that can be used to code, as can be seen from the actual working code for this trivial problem.

The following code achieves the task of removing the vowels from the phrase given, and printing out to the shell the phrase without the vowels. The example used is the phrase “Lord of the Rings” which prints out as “L_ord _f Th_ R_ings”.

The Code: (Please excuse the bullet points. They seem to be the only way I can format the code with indents.)

 

  • word = “Lord Of The Rings”
  • vowels = ‘aeiouAEIOU’
  • for j in range(len(word)):
    • if str(word[j]) in vowels:
      • wordCopy = word.replace(word[j], ‘_’)
      • word = wordCopy
  • print wordCopy

 

As you can possibly see, this is much less wordy than the flow chart, and certainly shorter than a written description of the task, or the comments that I originally wrote in the code. Just 7 lines of code! With the comments the code was originally more than 20 lines, and that was without being too verbose.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Comments are closed.