Browsing Tag

how to program a computer

Classes

10 Lessons Needed To Learn Programming In Any Language*

October 19, 2015

Without farther delay, here is my top 10 lessons to learn programming in the order they should be taught:

  1. Environment Setup, Input/Output
  2. Integers and basic arithmetic (+,-,*,/,%) + order of operations ()
  3. Float Arithmetic
  4. Variables
  5. Booleans
  6. Conditional Statements & Control Structures
  7. Functions
  8. Strings & Arrays
  9. Classes
  10. Exceptions

Ok, I lied. A lot of these have to be broken down and cross referenced. However, I think that should be the order in which people are introduced to programming. Too often people try to learn everything all at once. You can’t learn how to swim by jumping into the deep end. Well, some of us can. Learning a new skill isn’t always as easy to other people as it was to the teacher. Whenever I get a chance to be a bookstore, I like to look at beginner programming books. They all promise to teach a lot in a very short time. The honest truth is there is no shortcut. It takes a couple of years of programming in order to become a half dissent programmer. It is not because it is hard, it is just because there are too many variables. There are so many different things that you need to learn, that it can’t occupy just one book. It can’t even occupy the whole Internet. New things come up everyday that change what you knew before. Becoming a programmer is just one of these thing that require time.

So what is with this list? I got asked too many times at this point how I started programming and where/how to start. I have decided to write my own intro to programming. Over the next weeks I will publish small lessons that will build up to an ebook on programming. I will use Python-ish style code and most of the content will be generalized for almost any language. By the end of the book, you will be able to learn the syntax to a new language and program in any language you want. Best of all, the ebook and lessons will all be posted on this site and will be FREE. No strings attached. I believe anyone can learn programming at any age and that education should be available to all.

I have taught a few students before and there are several reasons why my list is different from other learn programming classes. The main objective is to start with something familiar that everyone in the 5th grade should know. Basic arithmetic and numbers. Than slowly build up while introducing new ideas and concepts. The secondary objective is to fully learn a topic before moving forward. That means when we will talk about a new concept we will go back and see how it reflects on other topics we have learned before. We are going to aim to turn fragile knowledge into concrete building blocks that will help us move forward and ultimately complete our objectives.

It should be mentioned what this course will not achieve. Beyond all else, you will not become a certified programmer or a hacker. Like I said before, that will take time. There is no class in the universe that can teach time. After you have completed the lessons, you will have to continuously learn new skills and develop yourself as a programmer. Think about learning programming more like going to the gym. You will not get a six pack and lose 50 lbs. in one setting, it takes time. Same thing with programming. You need to invest time to become a programmer. Just like going to the gym everyday, it will pay off in the long run and you future self will look back and thank you.

There are a bunch of reasons of why you should learn programming, I don’t feel like repeating most of them. I will just mention one. Programming is everywhere and it is here to stay. Programming has become a tool that used in virtually every field, even philosophy and history. Programming is almost equivalent to using excel. It is a skill more and more employers are looking for and will make you more valuable and your job easier. There are endless examples of how programming can shorten your job and sometimes turn an impossible human task into a simple short snippet of code. I believe that if you are reading up until this point, you already have a goal to learn programming. Or maybe you have already been through a class, but feel like you have missed the points and you want to know more. In programming there is always more to learn. Remember that.

First lesson will be published within a week. Make sure to follow me on Twitter @CptDeadBones to get notified.

* Ok. So technical, the class will teach you how to program in almost any language.

Programming Languages, Python

A Lesson about History, Objects, Classes, Time and Python

December 3, 2014

Object Oriented Programming (OOP) became very popular in the last couple of decades. I do find that a lot of people can tell me what an Object is, but few know what is the difference between a class and Object. In fact, many use them interchangeably. So let us clear the air a bit. Here is a short nice story about the evolution of programming. Sort of.

In the dawn of programming we had variables. For a time it was good. Char, Int, Sting, Float all run along nicely. For us programmers that was not enough. We like to make life more complex than that. So we start writing code. A lot of code. Code that uses a lot of variables. As programmers, we love looking for patterns. Slowly we found one. We are writing the same code, over and over. Now, we the coders are a lazy bunch. We like to be challenged, not to write the same lines of code again and agin. So, we came up with the notion of functions. Function are in fact awesome!. for a long time, one could do anything with a few variables and functions. Not to long after, we found ourself copying entire library of functions and files were getting really big. then we came up with the idea of modules, or libraries if you will. How awesome is it to import a whole battery of functions at your finger tips? Most programmers thought this was the best thing since slice bread. Not the we were around back then. After a while, we thought, you know what, how about we put the data (variables) and the methods (functions) together (encapsulation) and use it as one thing, lets call it an object. Yay! Objects.

This of course is a very short description of what actually happy. Hopefully you go the point. So what are objects? They are instantiation (from the word instants) of Classes with particular attributes and behaviors. Attributes refer to the object variables, behaviors to it’s functions. In most cases, but not all, the behaviors involve the attributes. Classes are the code, the recipe for an Object. 1 Class can produces as many Objects as you computer memory can hold. Having the attributes and behaviors together gives a sense of encapsulation. In OOP, the Object attributes are accessed using getters and setters (Access Modifiers). Getters retrieve a copy of the attribute. Setter overwrite the attributes. Setters and Getters are behaviors that help keep the information help by the Object correct. That means that if there is and attribute of a class that has to be a number between 0 and 10. The setter will not allow any other value to be stored. OOP gives us a sense of abstraction since we normally can’t see the code, but we don’t need to. There are a couple of more terms you should hear for now, inheritance and polymorphism. Inheritance means a class can be extended by another class to enhance functionality. Polymorphism means “of many forms”. This applies to OOP since we can have man ors of a single class.

Wow that was a lot to take in all at once. It is time for an example. What better language to use then our favorite, Python. Yay.

We are going to work on a time module that could be helpful for future programs. we are going to start from our basic class, an instant. For our purposes, an instant of time is date and time up to minute accuracy. That means that we are going to write a class, in Python, for an instant. We will have a date (year, month, day) and hour (hour, minute) as our class attributes. To set this up will have to use some special syntax. It will look like this:


class Instant:

	def __init__(self,year,month,day,hour,minute):
		self.year = year
		self.month = month
		self.day = day
		self.hour = hour
		self.minute = minute

Ok. We start with the keyword class, followed by the class name. then we define a function named __init__. This is a special function called a constructor. This function has to be in every class in order to create an object. It is only called once to set the Object up. As the function arguments we pass in self and the reminder of the variables we want to pass in to set the Object up. Some leagues allow multiple constructors. Python does not. We will pass self from this point to every function in the class, so that they can have access to the Objects attributes. Note that self.year is not the same as year. Self.year is the class variable, while year is a function variable.

To use this class, or to get an object, we can use the following code:


def main():

	i = Instant(2014,12,3,2,11)
	print i

if __name__== "__main__":
	main()

If you run it, you will get something that looks like this:

wpid-instantclasspython-2014-12-3-01-39.png

That number is a memory location where our object is stored. If we crated more Object they all will have different hex memory addresses. This is useful to know but not ver particle. If we want to debug or do anything we will need to print out the individual attributes within the class. Thankfully, there is a special function we can write called a to-string. It is noted in Python __str__ and will be called when asked to print the object. For our example the code will look like this:


def __str__(self):
	return  "Year: " + str(self.year) + " " + \
	   	   "Month: " + str(self.month) + " " + \
		   "Day: " + str(self.day) + " " + \
		   "Hour: " + str(self.hour) + " " + \
		   "Minute: " + str(self.minute)

And the output (for the same main() function from before):

wpid-instantstrpython-2014-12-3-01-39.png

You could be fancy and change the function to return something else like:

wpid-instantstrpython2-2014-12-3-01-39.png

if you really want you could play around with colors and strings in Python all that you want, but that is not the point. Now we are going to add some getters and setters. Getters are easy, the just retrieve information, so a getter for year looks like this:


def getYear(self):
	return self.year

We define getters to avoid direct access to class attributes. However, if we go back to out main we can issue a command ‘print i.year’ without an error. In order to avoid that we will add 2 underscores to the attribute name in the constructor. That will make the attribute private so only within the class using self.year we can access thee variable. So our new constructor will look like this:


def __init__(self,year,month,day,hour,minute):
	self.__year = year
	self.__month = month
	self.__day = day
	self.__hour = hour
	self.__minute = minute

And our getter will look like this:


def getYear(self):
	return self.__year

And if we wanted to print just the year, we would use it like this:


i.getYear()

Ideally, we would have a getter for every attribute in the class. That is not a must, just a friendly suggestion. Now we can move to the setters. In a setter, we will put a new value in the Object attribute. We could start with a simple method like this:


def setYear(self,year):
	self.__year = year 

This would work. However, normally it is a good idea to check what the user is putting as a year. In Python, variables do not have a declared type. That means that a user can end up passing in something like a String, Boolean or another Object for all we now. In addition, even if the user entered a number, what if it is a negative number? for our purposes, we are going to say that a year must be between 1900 and 2100. So our new setter will look like this:


def setYear(self,year):
	if not ((type(year) != type(2000)) or (year < 1900) or (year > 2100)):
		self.__year = year 

If you were following along you would notice a problem. When we first set self.year we never checked that the value of year upholds the setter standards. In order to correct this we would need to modify our constructor to do the same check. This does get tricky, but it is necessary to maintain the integrity f the Object data. We will modify our constructor set year line to look now like this:


if not ((type(year) != type(2000)) or (year < 1900) or (year > 2100)): self.__year = year
else: raise Exception('Year is not in correct format or out of range')

This means that for each variable we will need to similar work an add a getter and setter. Assuming we got all this done we could move forward. There are 3 more function we will want to added to our instant class:

  1. beforeMe
  2. afterMe
  3. addToMe

The first 2 functions are booleans that take another instant and compare the 2 to see if the other instant is before the current one. Similar idea with afterMe. The method add to me, will take a quantity and add it to instant. Lets take a look at the functions beforeMe and afterMe:

def beforeMe(self,other):
	if self.__year > other.getYear():
		return False
	elif self.__year == other.getYear():
		if self.__month > other.getMonth():
			return False
		elif self.__month == other.getMonth():
			if self.__day > other.getDay():
				return False
			elif self.__day == other.getDay():
				if self.__hour > other.getHour():
					return False
				elif self.__hour == other.getHour():
					if self.__minute > other.getMinute():
						return False
	return True

def afterMe(self,other):
	return not self.beforeMe(other)

I did get a little laze. I could have re-wrttien afterMe as a reverse to beforeMe, this seemed smoother to me. This function really should be straight forward. Lets move on to the next one. In the next one, we can add X minutes to an instant. That is cool and useful because it does require a little math. Let us first take a look at how this is done:


def add(self,min):
	if type(min) != type(1): raise Exception("Invalid minutes to add")
		self.__minute += min
		if self.__minute > 60:
			self.__hour += self.__minute / 60
			self.__minute = self.__minute % 60
			if self.__hour > 24:
				self.__day += self.__hour / 24
				self.__hour = self.__hour % 24
				if self.__day > 30:
					self.__month += self.__day / 30
					self.__day = self.__day % 30
					if self.__month > 12:
						self.__year += self.__month / 12
						self.__month = self.__month % 12

Do note that at this point I am making a lot of assumptions. I did not account for leap years and odd months. This function should be re-wrriten better, but for our sake right now it serves it’s purpose. So after all this is said and done, we should end up with a very interesting class that represents and instant, or a moment if you will in time. That class could be used to create many Objects. Even objects that interact with each other since we can compare 2 instants using the beofreMe and afterMe functions. Maybe next time we can extend this class to be used for a TimePeriod and maybe even a meeting in a schedule book.

Here is a link to the complete instant class in Python in case you want to play around with it.

Python

The game of Tic Tac Toe in Python

January 29, 2014

The last time I wrote an article we talked about the properties of a list. Many of you have pointed out some improvements that we incorporated in a later post addressing the issues some have you had with the code. This time, I would like to take on a larger program that utilizes some techniques we talked about as well as some new ones. In this article we are going to program the game of Tic Tac Toe in Python. I trust most people, if not everyone, have heard of the game and played it as children. Like always, I will be using Python 2.7.3 to test run my code. Some modification might be required for newer versions of Python.

The game of Tic Tac Toe is a perfect assignment for any programmers. You will be surprised how many times we go back to this game from a different angle. From this game you can learn turn based gaming programming, artificial intelligence , user interaction and many others topics. For now we are going to limit the game to non computer players. Here is a brief description of our assignment:

You are to implement the two player game of Tic Tac Toe. The program should display the board and prompt each user a move. The program should validate each move and handle any incorrect input. The entire user interaction should be command line based. Upon winning or a draw of the game, an appropriate message should be displayed acknowledging such condition.

The specs for this game are intentionally vague for the purpose of this article. We are going to tackle this problem one thing at a time. Let’s start by breaking down the program into some smaller blocks. Here is some rough pseudocode for us to work with:

  1. Setup Game
  2. Ask for user input on each turn
  3. Check if win condition met or no more moves
  4. Display the appropriate message and quit the game.

Let’s get started. First, let us think about how we can represent the board. A Tic Tac Toe board is a 3 X 3 grid. We could use a 2 dimensional list, or we can use one list with 9 elements that correspond to our 3 X 3 grid. So we are going to end up representing the board in Python in 1 list. Further more, we will set a value, -1, for an unclaimed cell, 0, for ‘O’ and 1 for ‘X’. This means that at any point in the game the list, board, will contain all the information we need for the game. Let’s take a look at the initial setup for the game:


board = []
	for i in range(9):
		board.append(-1)

That is it. This alone gives us a board with 9 cells all empty. Now let us tackle the display part. Although it is nice that we can represent the whole game in 1 variable, it is not very practical for the user. We want to display the game just like we would if we were to be playing on a pice of paper. To do so we will need to to print out a 3 X 3 grid from a 1 dimensional list. Let us first look at a quick example.

Let us consider that we have the list of numbers 1 to 9, and we want to print them out like this:

tic_tac_toe_map

To do so we can use this code:


a_list = [1,2,3,4,5,6,7,8,9]

for i in range(3):
	for j in range(3):
		print a_list[i*3+j],
	print 

The output would be:

wpid-3x3matrixpython-2013-11-12-15-13.png

How did this happen? Well, let us think about the values i and j take within the inner loop:

i_and_j_map_python

Now we want the values to be 0 to 8 to correspond to the list indexes of a_list. After playing with the numbers a little bit I found out that the formula i*3 + j gives me the values 0 to 8. Like this:

formulated_i_and_j_map_python

Cool. Let us now use this information to print out our Tic Tac Toe board. We already had the code to generate our board. Now lets see if we can print it. Consider the following function:


def print_board(board):

	print "The board look like this: \n"

	for i in range(3):
		print " ",
		for j in range(3):
			if board[i*3+j] == 1:
				print 'X',
			elif board[i*3+j] == 0:
				print 'O',
			else:
				print ' ',

			if j != 2:
				print " | ",
		print

		if i != 2:
			print "-----------------"
		else:
			print 

What will the function output? This:

wpid-tic_tact_tow_empty_board_python-2013-11-12-15-13.png
It is empty because all I did is generated an empty board using the code above. What would have happened if we sent it another list? Let’s investigate the code. It has a double loop like before, only instead of just printing out a_list[i*3+j] we take a look at it and print the appropriate value. If the list at that index contains the value 1 we print ‘X’ if it is 0, we print ‘O’. Otherwise it is just an empty space. The rest of the print statements are used to generate the lines. Note that we also use the comma (‘,’) to suppress the carriage return. You can read this article to find out more about Strings in Python.

So we completed our first part. We have a method to display the board and we have a setup for the game. Now let us see what is asking a user for input. Remember that we need to validate that the move is legal, i.e. the spot is not taken, and that the move is numeric between 1-9. Recall we are using a list to store the board. That means that will little effort we can ask the user which cell he would like to place a move in. Before we take user input, we will need to let the user know about this mapping of his/her moves. To do so let’s print out some instructions regarding the cell enumeration. Since we already have a function to print the board, with a little modification to it we can add an elif and write a small function to print the instructions, like this:


def print_instruction():
	print "Please use the following cell numbers to make your move"
	print_board([2,3,4,5,6,7,8,9,10])

If called, this function will print out:

wpid-tic_tac_toe_board_map_python_w_instructions-2013-11-12-15-13.png

Now, consider the following function that takes a player’s move and validates that it is a number between 1 to 9 and of numeric type:


def get_input(turn):

	valid = False
	while not valid:
		try:
			user = raw_input("Where would you like to place " + turn + " (1-9)? ")
			user = int(user)
			if user >= 1 and user <= 9:
				return user-1
			else:
				print "That is not a valid move! Please try again.\n"
				print_instruction()
		except Exception as e:
			print user + " is not a valid move! Please try again.\n"
			print_instruction()

This function will keep asking the user for a spot to place their move. If it is not numeric, we use a try-except block to catch the exception. If not between 1-9, we use a simple if-statement. Either way we notify the user of their error with an appropriate message. This is pretty straight forward. You always want to make sure the any user input is indeed valid. You should except the user to err. In this case, we accept user input as a sting and we try to convert it to an integer. Any input that is not between the numbers 1 to 9 will be considered invalid input and an appropriate message will be displayed.

wpid-python_err_input_ttt-2013-11-12-15-13.png

Great. We are actually almost done. The next part is how to check if a someone the Tic Tac Toe game. The function is not pretty, in fact it is hard coded for all possible board situations. It simply works. If there is a winner, the winners symbol will be returned, namely ‘X’ or ‘O’. If there is no winner, the function will return -1. Let us take a look:


def check_win(board):
	win_cond = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
	for each in win_cond:
		try:
			if board[each[0]-1] == board[each[1]-1] and board[each[1]-1] == board[each[2]-1]:
				return board[each[0]-1]
		except:
			pass
	return -1

So far we have talked about all the parts we need to make the game. Now it is time to put it all together. We will use all the functions we talked about and add some more logic. For example, we will have the game login in a while-loop. The loop will keep going while we do not have a winner. We will also keep track of the number of moves made. If less than 4 move were made, there is no sense to check for a win condition. If there were 9 moves made and no winner, the game is a tie. Other than that, the code should be fairly simple by now.


def main():

	# setup game
	# alternate turns
	# check if win or end
	# quit and show the board

	print_instruction()

	board = []
	for i in range(9):
		board.append(-1)

	win = False
	move = 0
	while not win:

		# print board
		print_board(board)
		print “Turn number “ + str(move+1)
		if move % 2 == 0:
			turn = ‘X’
		else:
			turn = ‘O’

		# get user input
		user = get_input(turn)
		while board[user] != -1:
			print “Invalid move! Cell already taken. Please try again.\n”
			user = get_input(turn)
		board[user] = 1 if turn == ‘X’ else 0

		# advance move and check for end game
		move += 1
		if move > 4:
			winner = check_win(board)
			if winner != -1:
				out = “The winner is “
				out += “X” if winner == 1 else “O”
				out += “ ☺”
				quit_game(board,out)
			elif move == 9:
				quit_game(board,”No winner :(”)

Since the output of this will be a little long, I will let you have fun and download it yourself, download Command Line Tic Tac Toe for Python If I have time in the future, I will try to record my screen and add the output.

Have fun playing!

Computer Programming I, Programming Languages, Python

Compute the Average, Min, Max and Mode of a List in Python

October 24, 2013

Lists are by far the most common data type you will use in Python. I wanted to take a few minutes to see how easy Python make the use os lists. I also want you to notice how much ground we can cover by just thinking about these properties of a list. In this article we will talk about lists, functions, searching, return values, data tpes, diconaaries, try-catch try-except blocks and more interesting Python techniques.

So we will be finding the average, min, max and mode of a list. I won’t go into different theories on how to efficiently find these, but rather straight forward approach. Let us start by an assumption that all the values in our list are going to be integers and the data is already stored in a variable named list. As before, we will be using Python 2.7, here is a copy of Python2.7 documentation if you need it. Coming from that we can start by saying our main function looks like this:


def main():

	list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

	avg(list)
	min(list)
	max(list)
	mode(list)

This will simply call 4 different functions that will each find and print what we are looking for. First, lets go over some list basic properites. In all these function we will use for loops to iterate over the elements of the array. Lucky Python has a simple syntax that allows us to have a variable in the for loop that will take the values of the array.

What does this mean? You will recall that arrays have 0 indexing property that allows us to access the elements in the array directly. If we were to have the syntax list[0] is our example, the value will correspond to 3. the syntax list[1] will have the value 4. We can access each element individually and directly. We can use this to change values in the array. If we were to have list[0] = 55 in our code, the value of list[0] will change to be 55. Here is an example code:


list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

print list

print list[0]
print list[1]

list[0] = 55

print list[0]
print list

This code will output:

wpid-list_index_exampe_python-2013-10-24-15-30.png

Notice that the values of the list have changed after the assignment. Now let us recall the for loop syntax and properties in Python. The syntax is for element in sequence. That means that we need to provide a name of a variable, in this case element and a sequence such as a String, List, Tuple, etc. So if we wanted to print the numbers 1 to 10 in Python, we will need a list sequence with the numbers in a list and then we can just print element. Like this:


for element in [1,2,3,4,5,6,7,8,9,10]:
		print element

And the output:

wpid-1_to_10_python_for_loop-2013-10-24-15-30.png

Cool. However, what if we need the numbers 1 to 1,000? Well, you can either write them all in a list, or you can use the Python range function. This function has 3 variations. You can eithier call it with 1 integer, and the function will return the numbers from 0 to the number you requested in increments of 1. You can provide the function with a start number and end number (2 integers), and you will get back the numbers from the start to end in increments of 1. Finally you can give the range function 3 integers which will server as start, stop and increment. Here is an example to demonstrate:


# range with 1 argument, return a list with the numbers 1 to 10 in increments of 5
print range(10)

# range with 2 arguments, return a list with the numbers 5 to 10 in increments of 1
print range(5,10)

# range with 3 arguments, return a list with the numbers 5 to 50 in increments of 5
print range(5,50,5)

Output:

wpid-range_function_python-2013-10-24-15-30.png

Remember that the range function in not including the last number. So range(10) gave us the numbers 0 to 9 without 10. Lets combine the range function with indexing of the list to access and print the elements in a list.


list = [3,4,1,20,102,3,5]

for i in range(len(list)):
	print list[i]

This code will output:

wpid-python_list_example-2013-10-24-15-30.png

This is one way to do it. Note that we are using the Python len function to get the length of the list. Len is a built in function in Python and will return the length of any sequence.

Another way to accomplish the same task is to use Python and remove the indexing. Like this:


for element in list:
	print element

Both code output will be the same. There are some cases (as we are going to see) were we will need to use the first one and some where we are going to use the second. It all depends on your program. Now lets take a look and see how can we calculate the Average, Min, Max and Mode of a list. First what is the Average of a list? It is just the sum of the elements divided by the number of elements. Well, we can get the number of elements using the len function, and we can iterate through the elements and add them all up. Like this:


def avg(list):

	sum = 0
	for elm in list:
		sum += elm

	print “The average element of the list is: “ + str(sum/(len(list)*1.0))

That was very simple. Let me just clarify some things. You will notice that in the calculation we are multiplying everything by 1.0. We do this to make sure the length of a list, an integer is turned into a double. That way the result of the average element will not be rounded. We also need to convert the average from double to a string in order to concatenate it with a String.

Now let us move on to the Min/Max problem. Essentially both of these are two faces of the same coin. Here is our stragedy to solver this:

  1. Assume the fist element is our Minimum/Maximum value.
  2. For the rest of the elements in the array
  3. If you find a result smaller/larger than Minimum/Maximum, they are the new Minimum/Maximum
  4. return Minimum/Maximum

Hopefully that algorithm was easy enough to follow. Let us take a look how this looks like in Python:


def min(list):

	min = list[0]

	for elm in list[1:]:
		if elm < min:  			min = elm 			 	print "The minimum value in the list is: " + str(min) 	 def max(list): 	max = list[0] 	 	for elm in list[1:]: 		if elm > max:
			max = elm

	print "The maximum value in the list is: " + str(max)

And the output: (assume that: list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99])

wpid-min_max_output-2013-10-24-15-30.png

Now let us to get to the hard part, computing the mode. This will turn out to be not so hard. What is the mode of a list? It is the number (or numbers) that occur most often. Ok. Now we are going to use 2 powerful tools Python has in it’s dictionaries and try-catch try-except statements. Dictionaries in Python are essentially lists where you can define the key. You can think about them as lists, but instead of an index that starts at 0 and goes up, you can name the key anything you would like. I would love to spend some time on them, but this might have to be another post by itself. Try-Catch Try-Except blocks are another post all by themselves, but think about them as a way to avoid TraceBacks. In other words if Python were to execute a statement that will result in a TraceBack, you can specify what to execute and the program will continue instead of terminate. I would love to talk mode about these 2, but for the time being you will have to read more about them on the Python Documentation or Google it.

So what i our strategy to find the Mode of a list? Well, first we can count the number of occurrences of each element in the list. We can use a dictionary to store the count and use the element themselves as the key. Let us see what that we give us:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

d = {}
for i in t:
	try:
		d[i] += 1
	except(KeyError):
		d[i] = 1

print d

This will output the following:

wpid-dic_mode_python-2013-10-24-15-30.png

When we print out a dictionary we get all the keys and the values separated by a colon (:). We can also get all the keys in the list by typing d.keys(). That will give us a list of keys. Now the rest of the code involves finding the max of all values in the dictionary and then printing the keys that fit these values. Here is how that part looks:


for key in keys[1:]:
		if d[key] > max:
			max = d[key]

	print "The mode of the list is: ",
	for key in keys:
		if d[key] == max:
			print key,
	print " with the mode of: " + str(max)

wpid-mode_of_list_python-2013-10-24-15-30.png

Here is a link to the full code to Compute a Mode of a list in Python.

That’s it. We figured out everything we set to do in the beginning. But wait, there is more!

BOUNS Time: Find the range of the numbers in the list. That is super easy, especially now. The range of a list of numbers is simply the Maximum of your list minus the Minimum of your list. Since we alredy have function for that, this is super easy. Let’s take a look: (note a slight modification of the min/max functions is required to return values instead of print statements).


print "The range of the list is: " + str(max(list) - min(list))

By now you should have a better understanding of how lists work in Python. You will find out that all the tools we looked at are extremely useful and you will find them in every Python application. I am including here a full copy of the .py file I used to Compute the Mean, Min, Max, Mode and Range of a list in Python. I hope you have had some fun and learned something along the way. Here is the output of the complete program for:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

wpid-python_list_data-2013-10-24-15-30.png

Any questions?

Computer Programming I

A Quick Tutorial for Python Syntax

July 8, 2013

For some, Python is far from their first language. For others, it is where they had started programming. I have received several comments and emails from readers asking how to proceed after understanding the basic concepts in Python. I am hoping to put together a road-map into Python in the next few weeks. Whether you know Python already or want to learn the basic quickly, I hope you will find this post (and the rest) useful. This is a very quick paste, high overview of the language. You are expected to know the basics of programming. Think of this as fast Python syntax review. For this tutorial I will use Python2.7. I highly recommend you consult the Python2.7 documentation while coding or download Python2.7 documentation for offline use. Linux and Mac come with Python already pre-installed. If you require help setting up a Python environment, please consult the Python installation guide. I am going to assume from this point on you already have Python 2.7 at least installed on your system. So let us get to it:

Running Python

There are 3 ways to execute Python code:

  1. The Python Interpreter - an interactive terminal. Statements are evaluated as entered.
  2. Loading a file into the Python Interpreter - save any text file as a .py and execute the statements.
  3. Compiled Python - this is not for speed of execution, rather for sharing a program without sharing code.

For any of the ways, we are going to focus on command line only. There are IDEs for Python, however they are an overkill for this tutorial. To run Python, simply lunch your terminal and type ‘python’. If you want to run a .py file in the terminal type ‘python <file_name.py>’, where file_name should be replaced with your file name.

Comments

In Python, any line starting with the ‘#’ symbol is considered a comment and will be ignored by the Interpreter.

Python Basic Data Types

Similar to other languages, Python supports the idea of basic data types. Unlike most low-level languages, Python does not require the programmer to specify the type. Python interrupter takes case of the data type for you. You may also change to type throughout the program. Thankfully, Python has a built in function type() that can clarify what type of data Python ‘thinks’ the variable is. The basic data types are:

* integer
* long
* float
* complex
* string
* boolean

Here is an output from the Python interpreter:

wpid-pythonbasicdatatypes-2013-01-20-10-09.png

Python Data Structures

Python has 4 data structures that could be at your disposal. These are complex data types that are built from the basic data types we saw before. Each of the data structure types has different usage and attributes. We will discuss:

* Lists
* Tuples
* Dictionaries
* Sets

Starting from the top, Lists are the most common data structure used in Python. With Lists you can group basic datatypes or even data structures together. You can preform numbers standard library function on lists. The 2 (2things) most important things to remember about lists are:

* They are 0 and reversed numeric indexed
* They are mutable

Let us look at some list example operations:

wpid-pythonlists2-2013-01-20-10-09.png

Moving on to tuples, they are very similar to lists but with one thing apart. Tuples are immutable. You may think of tuples as immutable lists, in other words lists that can not be changed once you create them. All the operations we have done on lists apply to Tuples, however, we cannot remove or add elements. This means that when we initiate a Tuple we initiate it with values that may never change. Let us look at some simple Tuple operations:

wpid-pythontupleexamples2-2013-01-20-10-09.png

So now that we have some data types we can move on to the next vital piece of information you need to know, Python Standard Library. Python include a huge array of functions you can use without anything special. The type() and len() functions are some examples of the functions that are included in standard library. This also includes function such as input() and raw_input(), string and number manipulation and many more functions. The best advice if you are looking for a function, check if it is included in stadard library before going to far.

So now what do we do if a function is not in standard library. For example, lets say we need to comute a sin() of an angle, or require the value of pi for calculation, what do we do then? Well, in that case we can import a library. That is right, in addtion to the huge standard library there is also a "secondary library" with everything you might think about, at least in the beginning. Again, you can refer to the Python2.7 documentation for any reference to these libraries. In our case we can import the math library and directly call the math.sin() function or access the value of math.pi. Let us take a look:

 

python_math_import_example3

 

Python is truly a fun language to begin to code with. I did not begin with Python myself, but I highly recommend it to others. Why? well, first I do not think anyone should start in PASCAL any more. Although it was a good educational languages, it is pointless to learn today. Second, Python is natural. It is easy to ease in to programming with python far more than any other language. (This last point might be debatable on the person and the teacher).

Programming Languages

Programming Languages to a Non-Programmer

December 24, 2012

As a non-programmer, you have often heard programming languages names being used. Marketers have always tried to used technical words to market new products and to claim superiority using “fancy” words. Many have come across HTML, java, flash, but do not know what that means. It is to my intend to educate those who may not know.

As for the programmers among you, many of us do not go a day without using several programming languages. If you really think about it, after the first few languages, learning new ones become easier. This may not encompass human languages, but learning new computer languages became easier for me with time. One thing that helped me the most was learning about the different types of programming languages. Knowing where to categories a new language helped me relate things I already know with new information. Hopefully you too will find this true. Learning new programming languages is a vital tool any programmer needs to acquire.

A Programming language is a communication method for humans to interact with machines. That is a very high level view. Machines, computers to be exact, work on binary sequences. That is strings of 0’s and 1’s. At the end of the day that is all computers understand. Further more, the entire operations a computer knows how to do is limited to operations on those strings of 0’s and 1’s. Any more complicated operations is done via multiple operations on said strings. Thankfully, we can store and reuse a sequence of operations. This is the closet level of operations, Machine Language. In the early days of computing, computers were programmed in such method. However, it is very impractical to program anything complex in this matter. Every set of commands in any languages must end up as a Machine Language instruction set suitable for a target computer architecture.

To take a step farther form Machine Language, we created Assembly. Assembly is the attempt to combine machine language operations into symbolic ones. It often group several Machine Language instructions into a single Assembly command. This enables programmer to create more complex programs, however still resides close to Machine Language. It provides better readability, with the same efficacy of Machine language. Assembly instructions are compiled into their Machine Language representations in order to be executed on a target architecture.

The next step away from Machine Languages are the low and high level programming languages. Some are easy to specify as while others are in-between. Languages that allow direct access to memory are often considered low. Languages such as c, c++, java to some extend, are low level. High level languages include matlab, matamitica, php, and other. Python for example, could be argued to be somewhere in-between. Depending on the programmer and the libraries used, python could be utilized as a low level or a high level language.

There are many types of programming languages. The Wikipedia entry for List of programming languages by type counts 43 languages as of the date of this post. Some of the ones I highly recommend on learning are (in no particular order of preference):

  • c, java, python
  • Lisp
  • Prolog
  • web langs: php, javascript, mysql, html, css
  • matlab
Computer Programming I

Computer Programming I

September 4, 2012

After writing about the content of Computer Programming III and writing the assumptions for that, I had a friend take a look. The most obvious problem was that I didn't define part I and II. So the following is what I would use as a syllabus for Computer Programming I.

 

Please NOTE: The associated web pages with Computer Programming I are for absolute beginners. The key audience for these pages are people who want to start programming. Although some of the post may be relevant for non-beginners, please be patient when reading. As always if you find any errors, please do point them out via email or in the comments.

 

Assumptions

Going back to My first assumptions, the following assumptions still hold true.

Assumption #0: You can read and write.

Assumption #3: You have Internet access.

Assumption #4: MATH.

Assumption #5: Hardware & Software.

 

The main purpose of Computer Programming I is to peak your interest. By the end of the first programming class you should be at a point where Assumption #2: You want to know more is a constant. You will learn about what programming can do and what are the limitations. That being said, you will not get to a point where you need a super fast computer, or run out of memory. You might get the computer to freeze, but not because of computation. Before I get to the syllabus and the specific topics, the following are the topics in no particular order.

Topic #0: Basic Building Blocks. This is the most fundamental programming. types, conditionals, program flow, basic proof, etc. This is will give you all the tools to start writting programming.

Topic #1: Functions. I can not explain how important this part is. Ask any programmer in any language. Functions will become the biggest tool in you arsenal.

Topic #2: Object Oriented Programming.  An introduction to OOP concepts and basic maneuvering.