Showing posts with label Python cover to cover. Show all posts
Showing posts with label Python cover to cover. Show all posts

Saturday, September 12, 2009

IndentationError: expected an indented block

IndentationError: expected an indented block

Indentation is a big part of writing Python code, and it is a good thing in my opinion because it makes you write better and cleaner code. indentation is used to place code more to the right. so instead of writing your code like below;


#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"


you have to write your code using indentations to make it work in python. Meaning a functioning code will look like this;


#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"


As you can see it will make your code more readable because you can see what is inside a while look and what not. This is directly the reason why it is used in Python coding, not to make your code look nice, it has a functional part to it. In some languages you indicate the begin and end of a codeblock like a while loop with brackets, a { to start and a } to end the while block. In python you use indentations. If you do not make sure your indentation is correct you will most likely end with a " IndentationError: expected an indented block" error. Lucky for you a line number will be given so you can debug your code quickly.

Personaly I think that the use of indentation for codeblocks is great. It will learn you to write your code in a way that it is more readable for other developers. That is at least on this part. I remember re-writing code from other developers and first making sure all the indentation is correct so it becomes more readable, in in python that is no longer needed because if you have your indentation not set correct in your code you will not be able to run it in the first place. Meaning that, if your process is correct, no developer can commit code into production if the indentation is incorrect. That is to say, for the parts where it is needed.

Final word, indentation in Python code,….. a good thing.

Friday, September 11, 2009

Python while loop

As I will go cover to cover in a book about Python coding I will have to touch the loop section. A loop is in basics a repeating command until a criteria is matched. You will see loops in almost every language.

This is what Wikipedia has to say on it:
In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages, Fortran's do loop is actually analogous to the for loop.

The do while construct consists of a block of code and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed.

It is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that allows termination of the loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a "repeat until" loop, which continues to run until the control expression is true (and then terminates) — whereas a "do-while" loop runs while the control expression is true (and terminates once the expression becomes false).




As can be seen below you can also nest a loop inside a loop:


#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"




Tuesday, August 25, 2009

Python if elif else


In almost every programming language you have some basic commands and functions, basic construction options so to call. "if" is one of those, "the if statement is used to check a condition and if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional." So we can have a check and if this check is returning a true we can take some action. Lets see in a very basic example how this works, I will show this with a very small python script.

#-----------------------
#!/usr/bin/python

#set some variables
var0 = 2
var1 = 1

if var0 > var1:
print "var0 IS larger than var1"
elif var0 < var1:
print 'var0 IS smaller than var1'
else:
print 'var0 is not larger or smaller than var1, maybe they are the same?'

print 'and we have left the if elif else'
#-----------------------

Sow with this very simple script we can show what action is taken, or what text is printed to the console. You can test this by playing with the values of var0 and var1 and see for yourself what the result is. Basically I do not want to spend to much time on the "if" part as this should be a very basic part of programmers knowledge. The only part that can be tricky is that in some languages elif is written as "els if" or "elsif" or even "if else". In Python it is if, elif and else. Just something you have to know when you start with Python.

So as you can see making decisions with if statements is a very basic way of making decisions. Another thing which is good to know is that you can nest if statements. So if you come into if-block you can create inside this block another if-block to make your decision even more precise. In the script below I first determine if var0 and var1 are equal. If this is not the case we "open" a new if-block to see what is exactly the case. Is var0 larger or smaller than var1. Just play arround with the values of var0 and var1 and you will see what it can do.

#-----------------------
#!/usr/bin/python

#set some variables
var0 = 2
var1 = 2

print 'starting some nesting'

if var0 != var1:
print 'var0 is not the same as var1'
if var0 > var1:
print 'var0 is larger than var1'
elif var0 < var1:
print 'var0 is smaller than var1'
elif var0 == var1:
print 'var0 is the same as var1'

print 'done with the nesting'
#-----------------------

Also something that you might know from other languages is that the content of if-block should be within brackets and that it is constructed something like below:

#-----------------------

if(condition){
action
}
else if (condition II){
action
}
else{
action
}
#-----------------------

In Python this is not used, you might like it or you might not like it that this is not in place however the people who developed the Python language did not see the need of it. I personally think it is a missing part, this is simply because I am within the group of bracket lovers who like to have it nice and tidy inside a couple of brackets. If you are in the same group.... you will get used to it finally.. I did also. Upside, you will never have to count opening and closing brackets again... remember those long nights of debugging a bracket problem?

Sunday, August 23, 2009

Python, comparing variable values

I have started some time ago with the Python cover to cover serie on this weblog however for some reason, namely, working on other projects I have not posted a Python cover to cover for some time now. So time to pick it up again and to all who like to follow the Python cover to cover... I will keep working on it more as I have finished some of the projects that where holding me back.

The past posts on Python I have been explaining about variable types. Now we will look on what we can do with variables on the comparing part. First we define some variables to play with:

var0 = "a"
var1 = "b"
var2 = 100
var3 = 50
var4 = float(1.1)
var5 = float(50.0)

So now we have some variables to play with. First we will use the string variables var0 and var1 . Lets compare if they are the same, to do this you use == so in this example we will be using the expression var0 == var1 which will return a boolean value which in this case this will be false. so as a small coding example you can check the code below:

>>> var0 = "a"
>>> var1 = "b"
>>> var0 == var1
False
>>>

we can also some other types of compare. For example the "not like" compare can be done by a using != as can be seen below:

>>> var0 != var1
True

And now something that you might expect on float and int values only maybe a greater or smaller than compare on a string which takes the alphabet into account:

>>> var0 > var1
False
>>> var0 <>
True
>>>

When you are comparing String values in python with greater than or smaller than functions you have to take into account that you might run into troubles because of upper and lower case characters. So it is a good thing to make sure that when you compare like this you make all characters upper or lower case before you start comparing. for this you can use the upper() and lower() functions. So if you want to turn a string into uppercase in Python, or lowercase you can use the following:

>>> "THIS IS A TEST".lower()
'this is a test'
>>> "ThIS Is A TeSt".lower()
'this is a test'
>>>


Basically all can also be done on numbers and not only on strings, Al Lukaszewski has also written some about it for about.com which you might want to read.

Sunday, May 31, 2009

Python dictionary variables

A dictionary variable in Python is not that much different as a normal dictionary as you might have on your bookshelf. So first have a quick glimpse into the definition of a dictionary, accoording to wikipedia a dictionary is:

"A dictionary is a book or collection of words in a specific language, often listed alphabetically, with definitions, etymologies, pronunciations, and other information; or a book of words in one language with their equivalents in another, also known as a lexicon."

And this is somewhat the same as a dictionary variable we know in Python, it is a list with keys and a set of values. The keys are the index like the integer indices in a "normal" Python list variable. For example I want to make a dictionary containing all the employees per department like in the example below where you use the department name (dep0, dep1,.. in this case) as the key and the names of the people as the value. As you can see we first define the dictionary with a set of curly brackets. After that we define the key dep0 and the values attached to the key...than we take dep1.... dep2....

>>> empPerDep = {}
>>> empPerDep["dep0"]= "John","Carl","Vick"
>>> empPerDep["dep1"]= "Mark","Carl","Tom"
>>> empPerDep["dep2"]= "Tom","Bob","Jack"

Now we would like to do something with it so we can simply enter empPerDep to see what is in the dictionary however in a common situation most likely you will not want to print the entire dictionary.

>>> empPerDep
{'dep1': ('Mark', 'Carl', 'Tom'), 'dep0': ('John', 'Carl', 'Vick'), 'dep2': ('Tom', 'Bob', 'Jack')}

More likely you want to show something based upon a key like all the people in department zero. Which can be done with a statement like the one below:

>>> empPerDep["dep0"]
('John', 'Carl', 'Vick')

And in a case like this you will almost certainly want to go even more deeper and define which part of it you want to show, for example you want to show only the employee Carl, this can be done with a statement like the one below:

>>> empPerDep["dep0"][1]
'Carl'

This is all very usefull when you know what is where and you live in a very organized and structured world where everything is very predictable. However in normal world you will not be coding something is such a hardcoded way that if you want to print the name 'Carl' that you can hardcode empPerDep["dep0"][1] . You will have to make sure carl is in the dictionary and you have to find out where he is. We take a new example and use a phonebook application this time.

>>> empPhoneBook = {}
>>> empPhoneBook[12345]="Colin Aitken"
>>> empPhoneBook[12346]="Natalia A. Bochkina"
>>> empPhoneBook[12347]="Michael J Prentice"
>>> empPhoneBook[12348]="Sotirios Sabanis"
>>> empPhoneBook[12349]="Chris M Theobald"
>>> empPhoneBook[12350]="Bruce J Worton"

Now lets say we have to create a application around it, one of the things people will like to know is how many people in this university phonebook system are listed? You will be happy to see that also the len() function in Python will work on a dictionary.

>>> len(empPhoneBook)
6

now lets say you want an option where you will be able to check who has been assigned a certain number. What you can do is a empPhoneBook[76435] where 76435 is the number you want to have more details about. This is a valid option and will work as long as 76435 is a key in your dictionary. If it is not your code will generate a very nasty error.

>>> empPhoneBook[76435]
Traceback (most recent call last):
File "", line 1, in
KeyError: 76435
>>>

A better way to do this is to check before you try to retrieve. You can check if a key is in the dictionary by using the in option. This will give you a boolean back on which you can decide to try and retrieve the value.

>>> 12348 in empPhoneBook
True
>>> 76435 in empPhoneBook
False
>>>

Even do this is very useful you also want to do something like this the other way around. This is especially for a phonebook where you would like to search by name however the unique identifier is the phonenumber. So now we would like to know for example if "Colin Aitken" is in the dictionary so we do the following:

>>> "Colin Aitken" in empPhoneBook
False

Surprisingly this is giving a false, this is because it is looking into the keys not into the values. So if we want to check if the name is in the values we have to use empPhoneBook.values() instead of empPhoneBook which will only take the keys in account.

>>> "Colin Aitken" in empPhoneBook.values()
True

You will have to play around it little with dictionaries in Python to start loving them however when you do you will never give up that love to dictionaries again.

Monday, May 18, 2009

Python, nesting tuples

As already discussed in a previous post you can use a tuple in Python. A tuple is in basic a list which content can not be changed. A tuple can have elements of all kind of variable types. This includes an other tuple. What this means is that a list can have a list as one of the list items, or a tuple because we handling tuples in this post.

this sounds useful however you have to keep track of what is nested and where it is nested. in the example below you can see how a tuple is nested in an other tuple. First we create a tuple named sometuple and after that we create a second tuple which as first element will have the tuple sometuple as a element.

sometuple = ("value0","value1","value2","value3","value4")
someothertuple = (sometuple,"value5","value6")

Now if we do a print of "someothertuple" like in the example below we get all the elements. which will be in this case:

print someothertuple[:]
(('value0', 'value1', 'value2', 'value3', 'value4'), 'value5', 'value6')

As we know that the first element of the tuple is a tuple we can get only the first element and get a other result:

print someothertuple[0]
('value0', 'value1', 'value2', 'value3', 'value4')


now if we want the second element of the tuple which himself is a element of a tuple we can do this as followed:

print someothertuple[0][1]
value1

As you can see this can become quite confusing when you start nesting a lot of tuples in tuples so in most cases this is not a good idea. However there are some situations where it can be used. Think about creating a static table which holds basic information about a chess board and what fields are black and which are white. You can calculate this also but you can also use nested tuples. You can also use it for example to create a layout for a playfield for a game... where can a player stand and where not. You have to remember that a tuple can NOT be updated so you can not use it to keep track of where a player is or how chess pieces are arranged. However for basic layout of your grid it can be used.


Wednesday, May 13, 2009

Python, using a list variable

In this post I will be discussing the use of lists in Python. In a previous post I already discussed the use of a tuple, where a tuple is fixed a list is dynamic. When you define a tuple the content is set for the rest of the program, when you use a list instead you can change the content.

First start with defining a list variable and placing some data in the list, in this case it will be dutch names. As you can see in the example below we define a list almost the same as a tuple, the difference is the sort of brackets.

As can seen in the example above the variable type in Python can be checked with the type command. In this case we do a type(thelist) and we get a . Now if we want some things out of the list, for example we like to print the entire list we can do a print and the name of the list. However, in most cases you only want a part of the list displayed and not all the content of the list.

The same as we could do with a tuple is what we can do with a list in Python. See the example below:

As you can see you can do a listname[x] where listname is the name of your list variable and x is the number of the element in the list. Now in this case we use positive numbers because we will move in a positive direction. It might be that you do not want this so you can also use negative numbers like in the example below.

As you have been reading the blogpost on using a tuple in Python you might already expected it, you can also get parts of more than one element from a list. this is done via for example a [0:3] extension after the name of the list. This will slice your list and provide you the results.

However, there are more ways on slicing your list, like for example you can use negative numbers or only a endpoint or startpoint for the slice you want from the list.

When you play around with those options you will quickly learn how to get your data out of a list just the way you want it and just the way you need it. That is for the data that is in the list, as already stated you can modify the content of the list. You can for example add data to the list. In python we use for this basically 3 commands. append, insert and extend with all their own characteristics.

listname.append()
append will add a given element to the end of the list so if we do a thelist.append("kees") this will be added at the end of the list. Remember, you can append also add a list variable to a list, this will not result in all the single elements of the list you append to be incorporated into the target list variable. It will add the given list variable to the list. If you want the single elements of a list to be added to a list and become elements of the target list variable you have to use the .extend() function for lists. A mistake quickly made, however only made once after you have been debugging for some time.

listname.insert(x,x)
insert also will add a new element to the list however with the insert command you can define the location of the new element where append will always add it at the end. for example we can do a thelist.insert(2,"piet") will make sure that the new element piet will be at location 2 in the list. You can easily think of some situations where this can come in handy.

listname.extend([])
The extend command will add a list to a list, in basic it will concatenate two lists into one which can be very handy in some situations where you build separate lists and finally have to combine the results. Think about parallel processing for example where in the end you will have to combine results to provide a complete overview. As shown in the example you can extend it with a list you build on the fly or a predefined list and just add the list variable as a extension on the list.

Even do it is important that you can remove elements from a list it is also important that you can remove items from a list. For this we have the list.remove command which enables you to remove a element from a list, you can see this in the example below:

The tricky part of removing a element from a list in Python is that if you try to remove a element which is not in the list it will give you a clean message, it will crash. So if you are writing some code it is a good thing to check first if the element is (still) in the list. This can be done by using a "in" command. for example if you want to be sure that element a is in the list you do a "a" in list
where list is the name of your list and a the value to be removed. This will return a boolean value upon which you can decide to execute the remove or not.

Saturday, May 09, 2009

Python, using a tuple

In Python, as can been seen in some post I posted before this one, one can make use of tuples. A tuple is nothing more than a list. Wikipedia states the following on the subject of tuple:

In mathematics, a tuple is a sequence (or ordered list) of finite length. An n-tuple is a tuple with n elements. Tuples are usually written within parenthesis. For example, (2, 7, 4, 1, 7) is a 5-tuple. Tuples are often used to describe mathematical objects that consist of specified components. For example, a graph is commonly defined as the 2-tuple (V, E) where V is the set of vertices and E is the set of edges. The edge set E is a subset of the cartesian product V × V, hence a set of 2-tuples.

A tuple can widely be used within Python for all kinds of tasks, a first simple example is using a tuple to construct a sentence. The use of this example might not be clear at first for a day to day usage however it will illustrate the use of a tuple.
In the above example we make use of a 2-tuple to construct the sentence. Now this example is not really useful in this setup because we could simply construct the entire sentence in one go and did not really have to make use of a tuple. However, in the below example you can see that if we define the content of a tuple first it already makes more sense.

Now we understand that we can define a tuple outside the print function as shown in the first example it suddenly will make a lot more sense. Even do we could still construct the above statement by using 2 string variables in this case the use of a tuple will make things more easy.

In the examples above we have used tuples to store strings, however in basic a tuple can hold any type of variable you need, so for example you can use it store also a int or a float. When you define a int or float inside a tuple it will also be in this variable type when you request it from the tuple. A example of this is below:

All of this is working just fine as long as you know the length of the tuple, in some cases you will encounter a situation where you do not know the length of your tuple, aka you do not know how many "items" it contains. in this case the len() command comes in handy. You can do a len(x) where x is the name of your tuple. This will return the number of "items" in your tuple. Remember, when accessing a tuple we start with "item" 0 and NOT 1. so if you need to get the last "item" from the tuple it will be n -1 where n is the number of items inside the tuple. You can see this in the example below:

In the last statement of the example above we do not a -1 on the len(x) in this case it is asking for unknowntup[7] which is not inside you tuple and this will result in the indexerror tuple index out of range.

Format numbers in Python

We have already been discussing rounding of numbers in Python in a precious post, also I have been discussing the use of the math.ceil and math.floor functions that can be used in Python. However, there are some more places where rounding is done and that is when you use number formats when you print something.

for example we have the value 30.6475 which we would like to print to the screen as a dollar value like $30.65. What we could do is a rounding of the value 30.6475 and print it in combination with the dollar sign. It can also be done as shown below with a command like print "$%.02f" %30.6475

the 2f is used to define the amount of numbers behind the point. so we can make it for example 3 if we want a output like $30.648.



Sunday, May 03, 2009

Rounding numbers in Python

A couple of post ago I was talking about int and float variables and I showed how you can play with numbers and variables. When working with floating point variables one of the things you most likely will be doing at some point is rounding. when you have a float variable holding a value like 123.783635 you most likely do not want to present this in this form to the users, you most likely want to represent this like 123.78. In this case you will be needing the round function.

In this case we will be executing a command like round(123.783635, 2) because we like to have to numbers behind the digit. if we would like to have 1 number behind the digit we change the last number, something like; round(123.783635, 1).

This is quite easy and strait forward, however there are some more nice tricks you can do with the round function in Python. For example if we have the number 1259 and we like to round it to 1300 we can also use the round function by executing something like round(1259, -2). You can just play around with it some more to get a good idea on how it is working like in the example below.



Friday, May 01, 2009

int and float variables in Python

When you start working and coding with python and this is your first experience with coding you will lost likely be puzzeld at first. Playing with numbers in coding can sometimes be somewhat strange because we can create different type of variables for numbers. manly you will be using FLOAT and INT values. where float numbers contain decimals int values will not.

some examples, lets first define some variables. We will create a variable A which will have the value 1 and we will create a variable B which will hold the value 2. When the are created we will divide A by B which by all common sense will give you 0.5 however as you can see in the example below it will give you 0 as the result instead of 0.5

The reason for this is that we have defined variables A and B as int values, we did not explicitly defined them as int however based upon the content of the variable it is defined as a int and a int value is not able to hold decimals. Because Python is now thinking we are working with only int values the answer is also a int value. We can define variables explicitly as a type of variable, for example if we wanted to have them represented as float values we define this with float(). Notice the example below.

Now the result will also be a float value and it will state 0.5 instead of 0. However if you do not want to define your variables explicitly as a float you can always "change" this when you do a operation on them. As you can see in the example below we have a variable a and b and they are int values as we can see at the outcome of dividing a by b. However now we do the same calculations and now we state that variable b is a float and the answer is suddenly a answer in float format. however, this is only limited to the operation as you can see because if we divide a by b again it is again a int value.

You can change the type of variable of variables a and b permanently, you can state that a = float(a) and then you will have them changed (until you change them to something else) You can see a example of it below.

Now you can come to a point that you are no longer sure what your variable is exactly, the type() function can help you with this. Just use the type() function in combination with your variable and you will be presented with the type of variable.



Monday, April 27, 2009

Python Format Specifier for Strings

When you are coding in python you can make use of the Format Specifier for Strings to format the output. In basic it is very simple to use when you like to manipulate your output. For example if we want to make "Your name is; Johan" we can do a print command as seen in the previous post however we can also do it a little different.

we can do a print "your name is: %s" % ("Johan") as seen in the example below

this will give us some more freedom in formating we now can for example manipulate the position of the first string which is represented by %s by adding a 10 between the % and the s which will make sure that there is space for a word of 10 characters. However he name Johan is 5 characters wide so it will leave space for 5 more characters.

you can also play around with adding a + or a - in front of the 10 so it will read +10 or -10. Just try it out and have some fun finding out how it works in detail.

Python string printing

Learning basic Python, it is a new task I am starting, I want to learn myself some basic Python programming. I have already knowledge of nuerous other programming language and python is in basic skills one of them. However, this evening something new happend, my girlfriend started to skim my books and started to read one of the Linux books I have. She is already for some time a Linux user however only on the GUI side and now wanted to learn all about the system she started to love including how the system was buildup from the kernel and the way she was able to manipulate it. based upon the books we started a discussion about reading a computer book cover to cover. I stated that if she was going to finish a 600 page Linux book and work here way from cover to cover I would also start reading a computer book and finish it from cover to cover. My choice was a book on Python programming. As I will go along in the book I will blog about it.

So here is the first blogpost about me learning Python from reading the book cover to cover. I will tag those posts with "Python cover to cover" so you can keep up. And please do remember, nothing is to basic to blog about because there is always someone who is not knowing what you write down.

First part, basic string printing. As for most languages Python has a function called print to write output to your screen. In our case it will write a string value to the screen, so if I want to print the text This is a test. to the screen in Python I will use print "This is a test." with the result as can seen below:
So this is quite simple, now we can do some basic manipulations on the printing of the text, for example let say that behind the text we would like to have a tab and then some more text. this can be done with the escape character of Python \ and the command for a tab a t. So we will be using print "This is a test.\tSome more text." or even a couple of \t commands.

As we now understand the tab command we can also use the command for a new line which is \n which will give us a new line. so for example if we want to have a This is a new text. and on a second line the text "This is text on a new line" we will be using the command print "This is a newtext.\nThis is text on a new line"