Building Python Code

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

Building From Existing Code

A recent post on this site presented a short example of how Python coding can, in just a few lines, take a piece of text and remove the vowels. That may be a trivial task but it does provide a starting point to help discover some of the first steps to coding in Python.

In that seven line snippet of code has examples of:

  • variables and assignment of values
  • loops, and the use of iteration
  • use of indexing to locate items
  • manipulating a string
  • printing a result

That piece of code was developed to test the code to see if it produced the result intended. Each time it is run it will produce the same result, and to do the vowel removal from a different phrase it would be necessary to adjust the value of the variable that contains the phrase from which the vowels are to removed.

The next phase would be to to either allow the user to supply phrases, or for the code to provide samples of phrases on which to work. That could then be further built on perhaps develop for a part of a word game.

But for now let’s just take a small step. And for that we will reuse most of the code and set it up as a function that can be reused easily. That then makes it easy to export that code to a completely different coding activity, although here we will still be doing the vowel extraction task.

The code now looks like this:

python codeThe function removeVowels(word) has been defined by re-using most of the code from the previous example.

In the code to the left the function is not called (or activated) until the last 2 lines. The def section of code defines the function. A callĀ  to the function is made when the variable hidden is assigned the value of the result of calling the function.

The result of that call (the value returned) is then printed to the screen.

In this example there is only one phrase that is examined and modified. The next step will be to either allow the user to provide phrases or for a bank of phrases to be provided.

That’s for next time.

 

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.