Thursday, April 25, 2013

How to Learn Programming


Many people have asked me: "How do I learn programming". Where should I start. Programming can be a very enjoyable and rewarding field of study. You can learn how to program to become a better computer user and to satisfy your strong urge to learn something "cool".

Have and Idea about computer architecture

You can't be a good programmer if you don't understand how a computer works. You need to at least have an idea about the fetch-execute-cycle. You need to have a basic understanding of how the binary number system works. Basically, you must have a general idea of how computers work and how they execute your program.
Most people in a hurry skip learning about basic computer architecture and dive into a language directly. This is ok, in the beginning. But once you try to write any large program worth its value you'll find that your lack of understanding of the machine causes a lot of trouble. 

Understand What a Programming Language Is

Computer hardward on its own is very limited and can only perform extremely basic and almost useless functions (on their own). For example are computer can read numbers from its memory (RAM) and read numbers from a hard disk, and read numbers from network card and it can write numbers to RAM, to a hard disk and to a network card and to peripheral devices such as a printer for example. The circuit boards on each device are taught to understand instructions that are written as numbers. 

This could be similar to you and me inventing a common language in numbers. If I say 01 that means HI and if I say 10 that means BYE. If I say 02 it means my name is. A conversation might go to be something like the following:

01 
02 Yasser
10

This is a very simple program that does nothing but introducing myself.
Computres are very good at processing numbers i.e. doing calculations and they only directly and natively understand numbers. Everything has to be coded as a number for them to understand it. This native language of computers is called machine language or machine code.

The very first computers where programmed in binary. They had switches that you could toggle either up or down and according to the pattern of witch positions you would load a special numbers that have a meaning into the computers RAM.

This was how things were done in the days gone by. At a certain stage programmers found that it was difficult to work with numbers and easier to work with text.




Programming Languages are Born

Computer scientist then invented the concept of translation. They thought why not write a program in a language that is easy for human programmers to understand and then use another program that will translate that programming language into something the computer can understand.Because as you know computers can only understand their machine language and nothing else.

Understand What a Variable Is

All program need to store data either for its own internal use or the data it is working with. For example if you're writing a primitive program to calculate the class averages, you need somewhere to store the numbers. The place where you store numbers in memory is called a variable, because it can vary from one execution of the program to the other.

Understand the if statement, loops, lists

Computer scientist figured out that almost any process can be programmed if it can be expressed in a series of steps that include selection and repetition. 

Conditional Selection : If statement

An if statement implements selection, that means that certain code will only run/execute get done only when the if statement is answered to with a yes.
Example:

if trial_period > 30:
    refuse_to_run()
else:
    show_registration_message()

A program that you download and run for a trial period will refuse to run after the trial period is over. It keeps track of the number of days it has been running and uses an if statement somewhere in the program logic that will execute / activate only when a condition is true. The condition is a question. Is the trial period greater than 30 days? If yes , then refuse to run, otherwise show a registration message.

Reptition: Loops

Another "construct" is looping. Where something is repeated several times as long as a condition is true. For example, you might loop on a list of numbers to find out the sum of the numbers in that list.

Advanced topics:

Understand Threads

Primitive computer programs can only do one thing at a time, for example download a streaming video from the internet, or play that video. It can't download and play the video in parallel. It has to do one thing, finish it and then move on to the next. This is very limited and restrictive. Operating systems have given us the ability to multi-thread, that is split a computer program into several tasks than can be switched back and forth and thus give the illusion of parallel execution.

Understand Data Structures

computers store data. Different data might need to be stored in different ways, because it might get accessed in a number of different styles. Depending on how much data you expect to store and how fast you want to access it and how the data is structured. For example are you accessing lists, or dictionaries or trees. Python is a very easy language to use because it does all those complicated data structure magic without you needing to implement its code yourself or understand its intricate details. 

You can't be a great programmer if you don't know Algorithms

An algorithm is a recipe for finding a solution to a well-defined problem. If you don't understand algorithms and algorithm analysis you will write terrible code that is super-inefficient and slow. But this is for those who want to take their programming knowledge to the next level. Starting with python will only require you to understand the basics only. More advanced programs require more advanced knowledge.

Write a lot of your own code

You can't be good at a language if you only study its rules from books. The best way to learn a language is to have a solid theoretical understanding and then go apply that understanding through small scripts and programs that do useful tasks and you find interesting. You have to practice a lot to get good at writing Python or any other computer programming language.

Read a lot of good code

Browse the internet for code written by others and study it to learn from them techniques and ways of doing things in code.



{link to tutorial 1}
{link to tutorial 2}

Wednesday, April 24, 2013

Program Online Without any Tools on Your Computer

If you've never programmed before and you want to get an idea of how the process works I suggest you go try the tools at : http://ideone.com/.

First you select which language you're going to program in from the list box that's on the left. Select Python.

Move your cursor to the right side and enter some code (programming instructions)  and hit the submit key.

The ideone website will execute your code and send you back the results. !!

I suggest the following little program:

for i in range(1,11):
    print i

The above code snippet will display the numbers 1 to 10 each on a line l

A screen shot of the output of ideone



Comming Post - How to Write a Directory Walker in Python

Python has the ability to walk directories as a built in library function somewhere. But I wanted to write my own implementation just for fun and to improve my understanding of recursion, so here's what I managed to whip up:


'''
Created     15th April 2013
@author: Yasser Al - Jammal
Directory traversal test
'''
import os

''
#--------------------------------------------------------------
#prefixes must end with a \\
#returns a list of subfolders each appended to its parent folder  and with a \ in the end
def BuildSubFoldersList(path):
    folders = []
    #build subfolders list
    for f in os.listdir(path):
        if(os.path.isdir(path + f) == True):
            #print str(f) + "\\"
            folders.append(path + f )
    return folders
          
#----------------------------------------------------------------
#folder must end wit h \\       
def ListFilesInFolder(path):
    n = 0
    #Add slash if missing
    if path[-1] <> "\\":
        path = path + "\\"
       
    for f in os.listdir(path):
        if os.path.isfile(path + f):
            n = n + 1
            print path + f
    print str(n) + " Files in folder " + path        
#################################################################
def main():
    DirWalk("d:\\")
################################################################# 
      
#Here is where the magic happens   
def DirWalk(path):
    if path[-1] <> "\\":
        path = path + "\\"
   
    ListFilesInFolder(path)
    subfs = BuildSubFoldersList(path)
   
    if len(subfs)>0:
        while(len(subfs) > 0):
            DirWalk(subfs[0])
            subfs.pop(0)
    else:
        return

if __name__ == "__main__":
    main()  

Why I LOVE Python

Python is such an amzaing language. I'm sure it will have a huge impact on how programming is done in the future. The brevity of expression is astounding. Python is "a higher level" language.

  • Lists can be indexed backwards. E.g. list1[-1] points to the lists last item, list1[-2] , points to the second last item and so on.
  • Dictionaries are built in the language itself.
  • Threading is EASY
And a million other reasons that make Python such an amazing programming language. Everything is straightforward, everything works straight out the box. Everything is clean and tidy and easy to use. 

Some macho type dude will come up and tell me no , Python is a toy language, real programmers program in C. Python is the future I say, C has done its job and done it very well in my opinion. If you want to get any real work done, you'll have to do it in Python..

I think Python has been limited in its growth due to the following reasons: There is no way to guarantee the safety of source code. Byte code can be easily de-compiled with easily available tools.No commercial software company will want to expose its trade secrets to the whole world.
Weak type checking
When you have a huge project made up of a couple hundred modules , each sending parameters back and forth you're destined to make a mistake passing a variable here or there. 

It would be nice if we could add some sort of voluntary type checking that would catch such errors.

I feel Python is a very powerful language and a very beautiful one for that matter.