Computer Science Canada An Overview of Python: Tutorial 4 - Data Types and Repetition (Looping)

Author:  apython1992 [ Fri Apr 01, 2011 1:51 pm ]
Post subject:  An Overview of Python: Tutorial 4 - Data Types and Repetition (Looping)

Hello again! First off - I apologize if there are any typos in this one. I'm not cool enough to own a pair of 3D specs, so I have to write this relying on regular ol' naked eye vision. Last tutorial, we looked at how we can assign variables on the fly in Python, and afterwards how to give our programs a bit of control using Python's version of the if/else clause. Here, Python's basic data types will be introduced in a little more detail (maybe I should have done this earlier, but it's here now anyway) and then lists as well so we can look at repetition.

Data Types
Python has a small number of basic data types - only four. This might seem weird if you're coming from C/C++, but it's actually really fantastic, as we don't ever have to worry about how much space in memory our values might need to take up. Here is the list along with a brief description:

integer - whole numbers, either positive or negative (e.g. -12, 0, 23)
float - real numbers with a floating point (e.g. 3.1, -2.000023432, 0.0)
string - a series of characters contained in quotes (e.g. "", "5", "hello")
boolean - true or false (True, False) ***resolves to an integer anyway, where True is any number other than zero. False is zero.

Python also has a None type, which is like null in C/C++.

All of the data structures we can use in Python are based on these basic types, so make sure you're comfortable with them. Unlike C/C++ (I can't speak for Turing), we don't need to worry about data type value boundaries; an integer can be as large as you need it to be, so if you have the memory, Python will keep on giving. Variables can be assigned with any of these types, along with structures that are made from them, like lists.

Lists
The Python list is a mighty powerful tool. New programmers - a list is exactly that. A list. Python's list is a mutable sequence, which means that it is a container that can hold a series of values (integers, strings, lists, dictionaries, objects, etc.), and that the contents are modifiable. The list is quite flexible; it can be considered a generic container, because we don't need to care about the type of objects it holds. You can mix it up if you'd like. You can have objects, integers, and strings all in a single list. Like arrays in C, C++, and Turing (and whatever else), we can access elements of a list using index notation, starting at 0 for the first element.

"But woah, hold on! I'm a new programmer, and I have no idea what you mean by any of this. When would you even require a list?" Well, good question. When programming, very often we want to hold a series of related values together in an ordered manner for various reasons - things like days of the week, numbers part of a set, etc, and using lists to contain them makes certain programming tasks very straightforward when combined with repetition. You'll see some examples coming up.

Making a list in Python is child's play.
 code: my_list = [1, 2, 3, 4, 5, 6] some_names = ["Bob", "Smith", "Jay"] mix = ["string", 2, 2.3, None, [1, 2, 3]]

Nesting lists is not such a horrible task either, as you can see with the last example. If you want a list of integers, you can even make things easier for yourself by using the built-in range function:

 code: >>> x = range(10) >>> print x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x = range(4, 10) >>> print x [4, 5, 6, 7, 8, 9] >>> x = range(2, 10, 2) >>> print x [2, 4, 6, 8] >>>

When only one argument is specified, range() will generate a list of numbers from 0 to (not including) the number specified. With two arguments, it will generate a list starting from the first argument (inclusive) to the last argument (exclusive). And with that third parameter, you can tell it to skip numbers as well.

List Methods
Python's lists are a powerful tool, largely because there is so much you can do with them.
 code: >>> my_list = range(10) >>> print my_list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> my_list.append(10) >>> print my_list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> my_list.pop() 10 >>> print my_list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> my_list.index(3) 3 >>> my_list.pop(3) 3 >>> my_list.index(5) 4 >>> my_list.reverse() >>> print my_list [9, 8, 7, 6, 5, 4, 2, 1, 0] >>> print my_list[4] 5 >>> my_list.sort() >>> print my_list [0, 1, 2, 4, 5, 6, 7, 8, 9] >>> cube_list = filter(lambda x: x >=5, my_list) >>> print cube_list [5, 6, 7, 8, 9] >>> new_list = [i*i for i in cube_list] >>> print new_list [25, 36, 49, 64, 81] >>>print new_list[1:3] [36, 49]

That's just a taste of the neat things you can do with lists. You don't need to understand it all yet, but just be aware that Python's lists are mighty. They provide a nice stack structure with a lot more flexibility. That last example I showed uses slice notation; it's similar to list indexing, but returns a new list that is a "slice" of the old list. Like the range function, the value before the colon is inclusive (starts with index 1, the second element of the list), while the value after is exclusive. Lists can be indexed with negative numbers too - list[-1] would return the last value of the list, list[-2] the second last value, and so on. List slicing can use a combination of positive and negative indices, or optionally none at all! list[:] would return a copy of the old list, while list[1:] would copy the cold list from the second element to the end. Flexibility for the win!

If you're a newcomer to programming and find yourself confused at this point, don't fret. I didn't cover the general concept of arrays and indexing very thoroughly, so feel free to post any questions you have on this thread. Well, let's move on to repetition.

While
To start, repetition is a very convenient way for programmers to repeat sections of computation over and over again, either repeating until a certain condition exists or iterating over a sequence of values. The former is generally accomplished with a while loop. In Python, it is structured as such:
 Python: while {condition}:     {execute block}

Where the condition would be much like those we talked about in the last tutorial, always evaluating to True or False. It's like the if statement, but it will execute the block over and over again until the condition fails. Here's a simple example:
 Python: name = "" while name != "Andrew":     name = raw_input("Please enter your name. ") print  "You're Andrew?! Alright. You are free to carry on with your day."

Note that the != operator means "is not equal to". The output:

This would have carried on for as long as the user didn't type in "Andrew". And that's really it for the while loop. While loops are used generally when we don't know how many times we will have to repeat the computation, but know when we want to stop repeating. This is in contrast with the slightly more complicated for loop.

for
The for loop is a counted loop, because we know how many times the block will be repeated (or at least know what this number depends on). The for loop lets us do work on a sequence of values, repeating the block for every value in the sequence. For loops have various implementations across different programming languages, but in Python, for loops always involve iterating over a sequence, most commonly a list or a tuple (a Python tuple is basically an immutable, less flexible list). It is structured as follows:
 Python: for {value} in {sequence}:     {execute block}

The sequence used here can be a list previously stored in memory, or an in-line list created using the range function. For example, if we want to print the square of all the numbers from 0 to 9:

 Python: for i in range(10):     print "The square of {0} is {1}".format(i, i*i)

The output:

 code: The square of 0 is 0 The square of 1 is 1 The square of 2 is 4 The square of 3 is 9 The square of 4 is 16 The square of 5 is 25 The square of 6 is 36 The square of 7 is 49 The square of 8 is 64 The square of 9 is 81

In fact, you've already seen how for loops act over a list. This did the exact same thing as this:
 code: >>> print cube_list [5, 6, 7, 8, 9] >>> new_list = [i*i for i in cube_list] >>> print new_list [25, 36, 49, 64, 81]

This is a list comprehension, which implements a for loop over a list, just like in the previous example! List comprehensions are always preferable to imperative for loops, as they are much more compact and Pythonic in nature. They let you copy a list, while doing something with the values at the same time (like taking the square). Of course, there are times where explicit for loops are needed for heavier tasks. Well, I suppose that's all I'll cover today. Iteration techniques are crucial to programming, and the problems they can solve are much more rigorous and challenging to solve without them when you delve into anything but the most simple scenarios. If you're a new programmer, get used to it! You'll need it for almost any programming problem. Of course, recursive techniques make iteration look really uncool, but that's a later topic to explore

An exercise: Write a program that prints the cube of all the even numbers from 10 to 25. Solve the problem with a for loop, and then with a while loop. Create the list using the range function, rather than explicitly assigning values.

And the challenge question for this tutorial (10 bits, open to everyone I suppose): What can you infer from the statement "cube_list = filter(lambda x: x >=5, my_list)" regarding how functions can be treated in Python? Look not at filter, but the lambda expression.

That's all guys. Next up we'll talk about functions and more data structures.

 Author: SNIPERDUDE [ Fri Apr 01, 2011 5:02 pm ] Post subject: RE:An Overview of Python: Tutorial 4 - Data Types and Repetition (Looping) A pain to read without 3D glasses (I'm sure this statement will confuse those who read it later), but it's good to see (albeit a little fuzzy) this tutorial series continue.

 :