Saturday, November 12, 2011

String operations - Part 2 of 3

I introduced Python strings in an earlier post. A string is a sequence of characters.


In the example above, "a", "b" and "c" are strings. "a" contains the value "jack"

You can extract each character in the string using the [] operator. The first item is at an index value of zero (0). The letter "j" in the string "jack" is at index value zero (0).


The word "jack" has four (4) letters. "j", "a", "c" and "k". The first letter is in position zero (0), the second at position 1, the third at position 2 and the fourth letter is at position 3. When we try to access a letter beyond the length of the string, we get an error message.

The Python len() function will tell you the length of a string. The last character of a string is at the position indicated by len() minus one.


We can iterate through this string, using the for loop and print out each letter.


Notice the comma at the end of the print statement so that we keep the letters on the same line. So that Python does not print the carriage return (or newline).

String slices

Just as you can extract a single character from a string by specifying its index, you can also slice out a sequence of characters by specifying two indices. The starting index and the index after the last character you want.

For example in "jack" if you want to extract "ja" you'd specify zero (0) as the first index and 2 (the index of "c") as the index after the last one. This is counter intuitive to most other programming languages where the second index would be the index of the last character you want. In Python, the second index is the index of the character you don't want.


In the example above, the letter "o" is at index zero (0). The letter "a" is at position 3. So we take everything from the letter "o" and stop before we get to "a". So we get "ont".

The second print statement has a[0:4]. Once again, the letter "o" is at position zero (0). The letter "r" is at position 4. So we'll take everything from the letter "o" and stop before we get to "r". We get "onta".

The third print statement has a[1:3]. The letter "n" is in position 1. The letter "a" is in position 3. So we'll take everything from "n" and stop before we get to "a". We get "nt"

Strings are also numbered from the end. The character at the last position is at index -1. The way to remember this is to think of the fact that index zero (0) is already taken by the first character. So numbering from the end of the string starts at -1. The second-last character is at index -2. And so on.

Each character therefore has two indexes. One index defines its position from the front of the string and a second index that defines its position from the back.


So now its easy to print a string backwards using a loop.


In the loop above, we iterate backwards from -1, down to -4 printing each character in the string.

Slices using negative indices

Slices are always taken forward. You specify a starting index, a second index to stop the slice. The character at the second index is not included.

You can therefore slice using negative indices as long as you remember this. Here are the same three slices we performed on the string "ontario" using negative slices.


We're using the same slice positions, but this time from the back of the string. To get the slice "ont" in the first example we used positions 0:3. In this example we used positions -7:-4. They represent the same characters. The "o" is represented by zero (0), or -7.

One last word about slices. You can omit any of the indices. If you omit the first index, it's assumed that you want to slice from the beginning of the string. If you omit the last one, it's assumed that you want to slice to the end of the string.


Iteration

To iterate means to "do again." In programming, iteration performs a series of actions, over and over, until a specific condition is met.

There are two main types of iterative statements in Python.

  • while loops
  • for loops

In this example, we set a variable "i" to the value 5.

We then start the while loop. The statement reads, while the value of "i" is greater than zero (0), perform the following statements. The statements to be performed are indented under the while loop. There are two things to do. First, print the value of "i". Secondly, set "i" to the value of "i" less one (1). The second statement will reduce the value of "i" successively until it reaches zero. Until that happens Python will start the loop again.

So the first time around, "i" is 5. So the loop prints "5". Then "i" becomes "4". This is still greater than zero so the loop prints "4". Then "i" becomes "3". And so on.

Here's another example.


In this example, we set a variable "i" to 5. Once again, we're going to iterate two statements, until "i" becomes zero or less. The statement "while i > 0" instructs the loop to continue iterating till that condition is met. The two statements to be carried out are; assign the variable "c" to the value "c + 'a'". Essentially this means, concatenate the letter "a" to the existing value of "c" and then assign that to a variable "c". It's not the same one as we'll see later. But Python takes the existing value of "c" which is blank initially, does the concatenation, and then assigns it to a variable "c". Once that's done, it reduces the value of "i" by one.

Once the loop is completed, we print out the value of "c". As you can see, it has five "a"'s. 

If you forget to include the statement "i = i - 1", then the value of "i" never gets reduced. You'll run into what is called an "infinite loop." This is when the loop continues on forever. Infinite loops are an example of a common programming error with both novice and experienced programmers.

The other type of loop is a for loop. For loops are particularly interesting in Python because they operate on a list of items. The list has to be predefined. For example, the following is a list of numbers that the for loop will print. We haven't discussed the list object in Python yet, this list is a special type of list in Python called a Tuple and it's enclosed in parentheses.


Quite simply, what this does is assign each element of the list to the variable "i" at each iteration of the loop.

Here's another one, using a string. Yes, Python iterates strings!


The print statement in Python adds a carriage return to each output. This is normally OK. However, if you don't want each letter to print on it's own line, add a comma at the end of the print statement.


That's it for loops for now.

Having fun with keyboard input

Time to take a small break, a quick detour. How do you interact with Python? Up to this point we've written instructions in the Python interpreter and Python has displayed the results immediately. We'll soon get to the point where we need to write programs, more than a single or a few lines, that will require that we write the programs outside the Python interpreter and ask Python to load them from there.

But in this note, I'd like to concentrate on Python's ability to accept input from the user. You.

Look at the following example.


We use the Python function raw_input(). raw_input() takes a single argument, a prompt that you wish to display. The argument isn't necessary. If you don't provide one, then Python won't display a prompt.

In our example, we call raw_input() and provide the prompt "Type something: ".

We then store the result in a variable, "a".

Here's an example where we get two numbers from the user, and then add them.


A few things to note from this example.

The return value of the raw_input() function is a string. Even though we typed in numbers, 12 and 5, they were stored in the string variables a and b. So, in order to add them, we have to use the built-in int() function, convert them to integers, so that we can do the integer math.

Notice what happens when we try to add "a" and "b." Instead we get string concatenation. The string "12" is concatenated with the string "5", not what we want. When you use the type() function to see what data type the variable "a" is, you can see that it's a string.

How would you permanently convert them to integers?


And the entire program, reading and converting to integers in one swoop.


Note how we use the return value of the raw_input() function as the argument for the int() conversion function, finally assigning that conversion to the variable "a".

Logical operators

This is a short section to introduce the logical operators in Python. If you've programmed in C, you'll recognise these immediately.


==    Equals
!=Not equal
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to


Here's a few examples of their usage.


Mostly self explanatory. You can store the value of the test in a variable by assigning it with the equals sign. As in:

c = x > y

If you examine the value of c, it will contain the boolean answer "False" because x = 1 and y = 2 and therefore x > y is False.


Functions

In computer programming, a function is a set of operations that perform a generic function. A function consistently does the same thing.

Python has functions, and we've seen one of them already, that perform type conversion. Converting from one type of data to another. For example, we saw that if we want to perform floating point division, and we have two integers, Python will automatically perform integer division, truncating anything on the right side of the decimal point, unless we tell Python that we'd like to perform floating point division. We tell Python that we'd like to do floating point division by converting one, or both, of the numbers to a floating point number.


In the example above, the answer to 20/3 would result in the number 6. However, if we use the function float(), then we get the right answer.

float() is a Python function that takes an argument and returns a floating point number, if it can.


The float() function normally works to convert integers to floating point, or to extract floating point numbers from strings. In the example above, the integer 7 is converted to 7.0. The string "7" is converted to the floating point number 7.0. Two things happened to the string. First, the number was extracted from the sequence of characters. And secondly, the number was converted.

The float() function will also convert floating point numbers. However, look at the last conversion. When trying to convert the string "jack" to a number, we get an error message. The string "jack" doesn't contain a valid number that can be converted.

The str() function converts its argument to a string.


In the examples above, the str() function takes the integer, 1, and returns the string '1'. Similarly, it takes the floating point number 1.1 and returns the string '1.1'

The str() function will also convert strings, back to strings. This might be useful in the case where you're writing data to a file and don't want to test each type before writing it out. You can be sure that the str() function will faithfully take your strings and write them unchanged.

Notice the statement:

'jack' + 1

This results in a Python error. Python does not know what to do. In the next statement:

'jack' + str(1)

Python converts the integer, 1, to a string first, now python knows that we need to use the string concatenation operator, the "+", to concatenate the string "Jack" to the new string "1".

Python allows you to create your own functions. To create your own functions, you prototype them as follows:

def function_name(parameter_list):
    body of function

Here's an example where we define a function.


The function name is sayHi. This function has no parameters, but the parentheses are important. The function body has a single line of code. The line prints a string, "Hello World!".

When we call the function, we simply use it's name with the arguments it requires.

Let's redefine the function so that it takes an argument. In this case, an argument that tells it how many times to say hello.


Now when we call the function sayHi(), we need to pass an argument. The argument will be used to repeat the string "Hello World! " a number of times. Note the space after the exclamation mark in the string "Hello World! ".

Arguments versus Parameters

In most programming language texts, the word argument and parameter are used interchangeably, but there is a difference. The parameter is defined in the function prototype. In our example above, "n" is a parameter defined in the prototype:

def sayHi(n)

Each time we call the function sayHi() we pass an argument. In our example above, the numbers, 3, 2 and zero (0) are arguments.


String operations - Part 1 of 3

Strings are sequences of characters. Python has a native string type that is used to hold character sequences.

The String data type in Python is immutable. This means that once a string is created, you cannot change it. You can make another string using operations on the string you created, but you cannot change the contents of a string.

More about this later.


We've created four (4) strings, a, b, c and d. And assigned some values to them. The first thing to notice is that you can use single (') or double (") quotes to delimit the string. For example, you might use double quotes if you have a single quote as part of the string as in the example below.


The second thing you'll notice is that the Python interpreter also displays the string with double or single quotes as necessary. This isn't very important, but notice when you use the print keyword to display the strings, the quotes aren't displayed.

The quotes are NOT part of the string. If you want to include quotes in your string, you would have to also include them inside the outside pair of quotes.

You can, surprisingly, use some of the mathematical operations on strings. Look at the following examples.


The "+" operator for strings represents concatenation. So, "jack" + "jill" becomes "jackjill" There are no spaces since the concatenation joins one string at the end of the other.

You can also see how a, b, c and d, "jack" "jill" "peter" and "wolf" are concatenated. If spaces are important in your programs, then you have to manually provide them.

The "*" operator for strings represents repetition. In the example a * 3 becomes "jackjackjack" The string "jack" is repeated three times.

We'll come back to strings later and do some more interesting things such as counting characters, extracting portions of the string, searching them and so on.

Friday, December 10, 2010

Hello World!

Every computer book has one, so let's get this out of the way.


Start the Python interpreter. You should see the ">>>" prompt.


Here's Hello World in Python.

>>> print "Hello World!"
Hello World!

The ">>>" represent the prompt in Python.


Explanation:
the print keyword instructs Python to display the string that follows. A string in Python is a sequence of characters, enclosed in quotes. The quotes can be single quotes, or double quotes. In the example above I use double quotes.