Data Structures — Part One
Welcome to the Data Structures tutorial! If you are joining me from my last post, Introduction to Programming With Python, I touched on data structures a tiny bit. Now we are going to expand upon this concept a bit more. Lets begin… In Python, there are to categories of data structures, primitive and non-primitive. An example of primitive data structures are stings, integers, float integers, and Booleans. We are also going to learn a few functions / methods that can be used to process these data types. Oh, almost forgot; if you haven’t already please go to this link and install notepad++. We will be using this text editor throughout the tutorial series.
Strings
Strings can be composed of letters, numbers or other characters surrounded by single or double quotation marks. Example: “12345678”, ‘12345678’, ‘This sentence is a string as well.’, “!@#$%^”. The key take away here is that any sequence of characters can be a string as long as you stick to the proper syntax of what a string is, the characters must be enclosed in either single or double quotations. Now lets us take a look at the various operations that can be performed on strings. Take a look at the image below and type the lines of code into notepad++:
This operation is called concatenation, it joins two strings together as you will see. But first, create a new directory/folder in your Documents folder and name it PyFiles. Now save your new notepad++ code file as concate.py in the PyFiles folder. Once that is done, open your cmd.exe and type this command >cd documents and press enter then type > cd pyfiles and press enter once more (don’t worry about capitalization, Windows cmd.exe is not case sensitive); This will put you in the directory/folder you’ve just created. Finally in cmd.exe, type this command and hit enter: >python concate.py. You should now see this output:
This operation concatenates or combines two strings using the “+” operator; it’s a pretty straight forward process and pretty self-explanatory. Lets move on to another operation. After having done the above example, can you guess the output of this expression?
Give up? Take a look below:
If you guessed that the statement would be printed to the console ten times, then congrats! Obviously it is the “*” operator that makes this possible. You can play around with this little program by following the steps above for creating and running the concate.py program. These operations, although handy and good to know, are quite simply boring. I think it’s time to take a look at something a bit more complex and interesting; String slicing.
This is the results after running the program:
Here’s the breakdown:
First, a little clarity on how computers count; All elements or items in a list be they letters, numbers or characters are counted starting with zero. In context of the figure above the letters in the string “Hello” are counted as 01234, where H is index position 0; e is index position 1; l is index position 2 so on and so forth. So in Figure 1 the 2 in the square brackets is actually telling the computer to to slice the string at index position 1 which is the 2nd element in the string. We then print out what is left over. This coding technique is called slicing using range; i.e. using the index range of the the elements of a list, string or tuple. In the case of the “Hello” string, the range would be 0–4. How about we experiment a little. I know by now you’ve asked, what's the space behind the colon used for? Well lets see what happens when we place a 4 behind the colon:
Ok now lets take a look at the results:
Hmm, this time only the middle two elements was printed out. Here's what happened:
In other words, the first two elements in the string (He) will be “sliced” off; Then the computer will print out all elements left over except the last element, which is the o. This is a pretty handy little technique to know and one you will probably use often in your own coding projects. So far, we went over both slicing and concatenation using the string data type. Now its time for you to experiment using both techniques in a program of your design. Programming problem: Can you concatenate elements from different strings using only the indexes?
You now know how to slice and concatenate a string; But what if you want to find out how long a string is? This is where Python’s built-in len() function comes in. Take a look at the code snippet below:
As the figure states the len() function counts the items in a string, list or tuple and then returns the total of those items as you can see below:
Now I know what you’re thinking, I counted twenty characters, how did the function come up with twenty-four? The reason is the function also includes the spaces in the count. Even spaces in the string are valid characters, keep this in mind when you use this function on strings. Now we come to the burning question, why would I need to know the length of a string, list, or tuple? Well one reason is you can have a line of code execute x number of times for each character / item in a string using a for loop. We will talk more about for loops later on in the series. Lets take a quick look at two more functions.
If you need a string / word capitalize, Python has got you covered with the capitalize() function. You will call this function a little differently than the len() function:
Once you start progressing in Python and programming in general, you will be using dot notation often in your own coding projects; Especially when you start writing complex programs that use classes. Don’t worry, we will go over the concept of classes later in this series. In the meantime, this is the output you should have once you run the program above:
There’s really nothing much to this program; however, the take aways are: 1) if you need to capitalize the first letter in a word, use Python’s built-in capitalize() function, and 2) The capitalize() function is called using dot notation.
There are many more function's / methods you can use on strings, too many to list here and I want to keep this post short and sweet. On that note, we will take a look at one more useful string function, isdigit(). Take a look at the example below:
As you can see, dot notation is used when invoking this method on an object. Note: variables are also called objects in Python; in fact almost everything is an object. We will learn more about objects later in the series. Moving on, after running the code above you should get this output below:
Our first variable returns True, it’s a string composed of digits. The second variable returns False because its a string composed of just letters. If any of the strings had a mix of both letter and digits, the function would return False. The isdigit() method is good for checking whether string data consist of digits or not. The opposite of this function is the isalpha() method, which checks for letters in strings. This is a perfect segue into our next three topics: Integers, floats and Boolean data types.
I will not go too deep into integers and floats; They’re very simple data type and if you have done any basic arithmetic, you already know most of the operations you can perform on them. Adding (+), subtracting (-), dividing (/) and multiplying (*) can all be done on integers in Python. The things to remember are: 1) integers are whole numbers (… -4, -3,-2, -1, 0,1, 2, 3, 4….) and 2) unlike strings, they’re expressed without quotation marks. Floats are really just integers expressed in decimal format (…-4.0, -3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0, 4.0…). You can do all the basic mathematical operations on floats as you can integers as well; However, know that if you add, subtract, divide etc. a float to an integer the resulting output will be a float. If want more details on floats and integers, click here. Now on to our final topic, Booleans.
Booleans come in two values, True and False, this is also comparative to the integers 1 and 0. They’re useful when you need to check if an expression is true or false in a comparison. Also, Booleans are useful in conditional expressions, example: if-statements which we will go over soon. For now, let us take a look at Booleans in action:
Note: You will use “==” to see if two values are equal; a single “=” to set a value to a variable.
Here is the output:
True, False, and False are the results after running this program. There is nothing much to say about this simple concept; The three expressions in the code example are comparing two values to one another, whether the values are greater-than, less-than or equal-to. Only one comparison, the greaterThan variable, evaluated to True; All the other variables evaluated to False. As a bonus, I will give you a glimpse into how a conditional expression is used in an if-statement. Type this into your code editor and save the file under any name you want, however, you can save the file as “bonus_code.py” to avoid confusion.
We are going to take a quick look at if statements; These statements allow you to create programs which can make simple to complex decisions. Bleow is an example of a basic decision making script:
The conditional symbol “>”(less than) is what allows the computer to make a less than or greater than decision based on the user’s input. Other conditional symbols include: “<”(less than), “==”(equal to), “<=”(less than or equal to), “>=”(greater than or equal to), “!=”(not equal to). We will dive into if-statements more later on in this series.
Once you run this program in cmd.exe, this will display to your console:
You have programmed instructions which allowed your computer to make a decision, congrats! Although, the overall purpose of this tutorial is not to teach you about if-statements but to expose you to how conditional expressions can be used in programs.
We have now reached the end of this tutorial; I hope that it was clear, concise enough for you to learn something of value and put you on the course to being competent in Python / programming. This is just the beginning and we still have a long way to go; I will be there to guide you through your learning. Now go and experiment; be creative and most importantly have fun. Next week, I will continue this tutorial in Data Structures — Part Two. In the mean time, practice what you have learned!