Python After Hours

Posted by Neville on August 7, 2016 under How To, Links, Python, Resources, Training | Be the First to Comment

After Hours Programming

There are lots of sites that will tell you that they will help you get started with learning the python programming language.
Many of them will take you a few steps and then ask for you to pay them for access to the rest of the course.
The site on this link is a little different. You can work through all of the stages for free. It seems that they can do this by displaying ads for related books on Amazon. Each book has strong recommendations that you purchase, but with sufficient determination you can work through all stages without purchasing the book.
However, the learning that you do will be quite basic, and you will most likely need to look elsewhere to fill any gaps or topics that were not covered comprehensively.
Have a go, and share your experience.

Have A Go

Posted by Neville on June 23, 2016 under How To, Python, Resources, Training, Uncategorized | Comments are off for this article

A console to share:

Python is an interpreted language. That means that it needs an interpreter to take the code that a user has produced and translate it so the computer’s processor can work on it.
One way to get access to the python interpreter is by using a console. Often it is necessary to download and configure python on your machine.
The frame below, however, will provide you with a console that is shared from the pythonanywhere site.

After the console loads and displays some information about python and the version being used you can type some commands at the cursor in the current input (In) line.

Try some of these:

Use the console as a calculator. For example type some of the following math statements, or use your own. After each one press the enter(return) key to see the result.

  • 5 + 6
  • 45 * 5
  • 81 / 9
  • 2 ** 3 (don’t type this:  2 to the 3rd power)

Playing with strings (words and letters).

  • print(“Hello”)
  • name = “Tom”
  • print(name)

 

 

Use this pythonanywhere console:

Some more examples to try: Remember to hit Enter at the end of each line. For multiple lines as below, hit Enter on the blank line after you finish to send the lines for processing.

1: for count in range(5):

print(count)

2: Creating and displaying a list:

mylist = [8, 9, 6, 5, 4]

mylist

3: Sorting the list.

mylist.sort()

mylist

 

 

 

 

Add A Little Randomness

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

For Variety

As the little project for building an application that gives users a phrase to guess after the vowels have been removed has developed we have been through these stages.

  1. Build code for removing vowels from a phrase.
  2. Use that code to build a function that can be used repeatedly in the application.
  3. Giving more phrases to use, and then asking the user to guess each one.

Adding Randomness

Up to this point the phrase to be decoded will be the same each time the module is run.

To add variety we need a bigger list of phrases to choose from and a way to randomly select select from that list.

To achieve this  the random module needs to be imported as it is not included by default in the Python code. The random module is one of a library of modules that can be imported for use when needed.

The import random statement is at the top of the code in the figure below.

In this post the application is expanded to:

  • Read phrases from a separate file and make a list of them that can be used for decoding.
  • Randomly select from those phrases to present to the user
  • Screen the phrases so that all phrases for guessing are different.
  • Provide feedback after each guess. The correct phrase if the user did not guess correctly, and a score of how many were correct.

 Reading A File

For this task a text file is read into the code. That text file is a list of movie titles with each title being a line in that file. Read File

A function (loadWords) has been defined to return a list of the movie titles in the text file. In the example shown a constant value for WORDLIST_FILENAME has been given and it is assumed that the text file (movies.txt) is in the same folder as the code for program. If the file is located elsewhere the full address would have to given.

The function loadWords() then does the following:

  1. Prints a note to the console saying that titles are being added.
  2. Opens the file for reading.
  3. Prepares an empty list that will store the movie titles.
  4. Reads each line and appends that line in Title Case (ie a movie title) to the list.
  5. When all titles are added, it prints out the length of the list, which is the number of titles added.
  6. Returns the list of titles for processing.

The Guessing Game.

Guess TitlesAnother function (guessTitle(words)) is defined in the code. This function takes a list of words (in this case, movie titles) and randomly chooses one of the movie titles and passes that title to the previously defined removeVowels function.

It then prints the movie title with the vowels removed and waits for the player to try to type out the name.

If the player guesses correctly 1 point is added to the score. If the guess is incorrect, the right answer is printed out and the player is then able to move on.

The above steps are included in a loop that has a range of 5 steps, so that at the end the player has a score out of 5. The score is initially set to 0, and 1 point is added for each correct guess.

To prevent the same movie title being presented the function has a list of used titles, initially empty, that has the titles used appended. While the random selection produces a used title, that title is ignored and another selection made for the player to guess.

At the completion of the loop the program stops.

2 Commands

After all of the preparation work is done with the variables being given values and the functions defined, it takes just 2 simple commands to set the process rolling.

Those 2 commands come right at the end of code:

  • titles = loadWords()  sets up the list of movie titles to choose from.
  • guessTitle(titles) takes that list, presents titles to guess and prints out a score.

 

Small Changes, Big Progress

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

Going Loopy

The previous post presented code that will produce the same content on each run. Not a particularly useful outcome.

It would be preferable to provide some variation to the input and then to get a more varied output. Before getting into random selection of content to operate on let’s give the user some extra phrases to try to decode, and then ask them to try to work out what each phrase is.

def removeVowels(word):

vowels = ‘aeiouAEIOU’
for j in range(len(word)):

if str(word[j]) in vowels:

wordCopy = word.replace(word[j], ‘*’)
word = wordCopy

return (wordCopy)

words = (‘Lord of the Rings’, ‘Star Wars’, ‘The Jungle Book’, \
‘The Lion King’, ‘Toy Story’)
score = 0
for h in range(len(words)):

hidden = removeVowels(words[h])
print (hidden)
print(‘Can you recognise the movie?’)
respond = input(‘Type it here ‘)
if respond == words[h]:

score += 1

print (‘Score %2d/%d’ % (score, len(words)))

The first few lines (the removeVowels function) is the same as in the previous post, and that code had its last 2 lines removed so that the words variable could be give its value, a tuple containing 5 strings, with each string being a movie name.

To help keep score of the correct guesses a score variable is set to start at 0.

Now to get loopy.

A loop that steps through each string in the words tuple then takes each move title in turn, removes the vowels, prints the phrase minus the vowels, provides instructions to the user and waits for their response. If the response matches the original phrase the score is upgraded and the loop moves on to the next phrase.

When all phrases have been guessed, the code ends.

Moving on.

The next phase of development for this task is to add some randomness since the way that the code is set up right now, the result will always be the same. For now the simplest method for getting different phrases to work on would be to edit the words variable. Although relatively simple, that is inconvenient.

That’s for next time.

 

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.

 

Wanna Learn To Code In Python

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

Start Here

There are lots of online sites that will help you get started with your efforts to learn coding with Python.

eBooks and pdf training resources

Learning by doing is often favoured by many learners. Some of the resources named here allow to do just that.

For example, if you want to learn to code to build games, a book that takes you through the steps for building some simple games would be a great place to start. If that book also provides the code for you build some games, and details how the code works, while you learn the building blocks of the language, you have the potential to learn by doing.

Invent Your Own  Computer Games  with Python, is just one example of the this style of learning to code.

The author, Al Sweigart, is the author of several books for people interested in learning to code in Python.

In his own words:

My motivation for writing this book comes from a gap I saw in today’s literature for kids interested in learning to program. I started programming when I was 9 years old in the BASIC language with a book similar to this one. During the course of writing this, I’ve realized how a modern language like Python has made programming far easier and versatile for a new generation of programmers. Python has a gentle learning curve while still being a serious language that is used by programmers professionally.
The current crop of programming books for kids that I’ve seen fell into two categories. First, books that did not teach programming so much as “game creation software” or a dumbed-down languages to make programming “easy” (to the point that it is no longer programming). Or second, they taught programming like a mathematics textbook: all principles and concepts with little application given to the reader. This book takes a different approach: show the source code for games right up front and explain programming principles from the examples.

You can download the latest edition from the Invent With Python site, that also has other books that may interest you.

This book takes you from installing and setting the environment for you start programming in Python, then begins with some simple games, including classics such as Hangman and TicTacToe.

Initially the games are played in a simple text-based format, which introduces the basic language features without the distraction of having to learn processes for displaying in graphic environments.

 

 

Going with Google

Whenever you get stuck while trying to work out just how to get the code you are working on to perform in the way you want, there is always the opportunity to do a search in your favourite search engine for the solution. Most times you find that you have to try several of the results before you find something that can be adapted for your problem.Python Tutorial

But occasionally it will throw up a resource that answers your question, and here’s one that looks like it will be very useful.

Python Tutorial

This site has been online for some time and has a range of topics available for beginners and more advanced coders.

 From The Source

What better place than the home of all things Python?

Python OrgIt may be a little daunting and the learning curve a little too steep with the assumptions made about the reader’s ability to understand the vocabulary used, it is possible to pick your way through the wealth of information. There are some sections specifically for the beginning coder.

Python.org is the website of the Python community, and has many valuable pages for the beginning or experienced coder.

If you are not sure of how Python is used, check out the Success Stories.

This site is also one from which Python can be downloaded to your machine.

 

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.

A First World Problem

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

Going With Python

After a break of more than 2 years, this site is back in action. The course mentioned in the last post was completed, but unfortunately other things got in the way and nothing much was done to build on the learning that came from participation.

Python CodingUntil about a month ago, when the second part of the MIT MOOC began. That course relies on having a reasonable knowledge and ability to program with Python. Consequently I have not been able to keep up with the Problem Sets and quizzes for the current course.

Being enrolled in the second part has encouraged me to go back to the original and brush up on the content, while attempting to code some simple (or what I thought would be simple) little tasks. There is SO MUCH to come to grips with, but the challenge is worth the effort.

Hello World: A First World Problem

As is usual for most early lessons in courses that teach computer programming, the first instructions get the student to print the phrase “Hello World”.

For those who have become a little jaded by having to do that for programming and other coding tasks this first step will give the student the option to bypass that trivial task.

The code below, written using Python, that can be run in the Python Interactive DeveLopment Environment (IDLE), will be used an example from which many different aspects of the Python language, and programming with Python (in the early stages).

 

The following links will take you to pages where the snippets of code will be explained and further examples and practice task will be presented.

First we will look at the last 2 lines of code. These are user-defined commands that tell the computer to go to to those 2 functions, that were defined earlier in the code above.

introDisplay()
userInput()

 

”’ Step01:

This file will run on Python version 3.5 and would need to be
edited for running on earlier versions.
”’

import random
#imports the random methods to use later.
def helloWorld():

    #helloWorld is a simple function that prints the string ‘Hello World!’ to the screen.

    print(‘Hello world!’)
    print(‘What is your name?’)
    myName = input()
    myName = myName.title()
    print(‘It is good to meet you, ‘ + myName)
    return

def fibNums(x):

     if x == 0 or x == 1:
         return 1
     else:
         return fibNums(x-1) + fibNums(x-2)

def getFib(n):

    for i in range(n+1):

        print(‘fib of ‘ + str(i) + ‘ = ‘ + str(fibNums(i)))

def introDisplay():
     #prints the introduction to screen
     print (‘Learn To Program courses usually start with ‘)
     print (‘teaching how to print “Hello World” on the screen.’)
     print (”)
     print (‘In this course you can skip that step….’)
     print (‘Or you can take to usual path.’)
     print (”)
    return

def userInput():
     # This function asks if the user wants to print “Hello World”,
     #   If so it does that, otherwise simply exits the function.
     print(‘Do you want to see Hello World printed on the screen? (yes or no)’)
     if input().lower().startswith(‘y’):

        helloWorld()
     else:
         print (‘You skipped the Hello World step…..’)
         print (‘Or did you?’)
        

          if random.random()> 0.4:
            #get some fibonacci numbers
             print (“Here’s some Fibonacci numbers to look at….”)
             getFib(10)

        else:
            print (‘Computer says “No”‘)
            helloWorld()

    print (“That’s it! I’m Done.”)

    return

introDisplay()
userInput()

First steps into coding

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

Ruby and/or Python?

That seems to be the question right now.

Maybe the answer is both!

So where have I been, and do you want to take the journey too.

First Code School for Ruby. Not a bad place to start, but you are working in their online console and not really building up you own battery of coding examples to play with.

Then it was on to Codecademy, for more of the same. Working in their console, having to pass each step to progress to the next. The process is not too fast, but once again you are working on the problems they set and not those of your own.

Ruby on Rails TutorialThe next step for me was to do the Rails Tutorial to learn building a web application using Ruby on Rails. Now that is a challenge! But as with most things, anything worth achieving requires some effort. The results from following this tutorial are a much better understanding of Ruby ( and Rails), with still lots of gaps to fill. A side product is a twitter-like social networking site that I will work on linking to another of blogs. When I get time between learning Python!

Currently I have enrolled in and EdX MOOC(Massive Open Online Course) 6.00X, that has a focus on computation, with the Python language as the tool to use for building on that aspect of computing. So far it has just started week 2, and is beginning to get down to the nitty gritty. As  a back-up I am also working my way through the Python curse at Codecademy.

That’s it for now. More study to do, and some Problem Sets to submit. Looking forward to seeing where thus takes me.

The Prodigal Returns

Posted by Neville on October 13, 2013 under Uncategorized | Comments are off for this article

Where have you been?

After a few months of neglecting this blog, as a result of dis-illusion with the world of world of advertising with safelists, this site is about to get a new lease on life.

All of the old posts will stay, so that you can wander through them, and hopefully learn something from my journey.

So where am I at now?

Coding.

Hoping to show some results soon, but it is early days right now.