In Python, tuples are almost identical to lists. So, why should we use them you ask? The one main difference between tuples and lists are that tuples cannot be changed. That is to say you cannot add, change, or delete elements from the tuple. Tuples might seem odd at first, but there is a great reason behind them being immutable. As programmers, we mess up occasionally. We change variables that we didn’t want to change, and sometimes, well, we just want things to be constant so we don’t accidentally change them later. However, if we change our minds we can also convert tuples into lists or lists into tuples. The fact is we need to make the conscious effort to say Python, I want to change this tuple into a list so I can modify it. Enough babbling, let’s see a tuple in action!
List vs. Tuple
So, we see that the list clearly works as expected. We just append a 4 onto the end, and Python doesn’t miss a beat. Next, we test out our tuple declaration and it works as well. But when we try to append to the tuple, Python give us a nasty little error. Like I said, you cannot change a tuple! Python will bite you if you try using things like append on a tuple. But, let’s say “Hey, I really want to add a four to that tuple.” Let’s do it:
Boom! We have successfully undone what Python was trying to teach us not to do. We just casted the tuple into a list, then once it was a list, we used it’s append method to add the 4. It should be reiterated that the purpose of a tuple is to be immutable. If you are planning to change the variable, just use a list instead.
First, off Python usually requires some setup by downloading the Python IDLE. The Python IDLE is basically a text editor that lets you execute Python code. If you want to use Python as a server-side language, you certainly can. Python can output HTML just like other languages can, but Python is more commonly used as a module rather than intertwined like some PHP or ColdFusion. As for right now, I recommend you download the IDLE to help you debug your code while we learn the fundamentals offline. One really quick note, we are using python 3.2. Before we go to an example, please understand that Python is space sensitive. This means you must have 4 spaces for each indentation every single time. We’ll get into this more later, now let’s go to an example.
You can see right off the bat, that we use print() a whole lot. Basically, all it does is output whatever is inside the parentheses. You will be doing lots of printing so, you can get more comfortable with it as we go. Print is a function that we will go into later, but just understand that it can take a value. On the first line, we provide a string value “My first Python code!”, which is a string because of the quotes. So, you just told Python to output that string to the console. Python completes that task and moves onto the next line where it prints out a different string.
See how simple that was? Well, get used to it. Python is probably one of the simplest looking languages that can do some of the most powerful things you can imagine. You can see from the example how clean Python’s syntax is without all of the extra stuff that other languages add. That covers the easiest Python statement you will ever write. In the following sections, we will be using more advanced functions and teaching you the fundamentals of Python.
Many times, a programmer finds a reason to read content from a file. It could be that we want to read from a text file, such as a log file, or an XML file for some serious data retrieval. Sometimes, it is a massive task to figure out how to do it exactly. No worries, Python is smooth like always and makes reading files a piece of cake. There are primarily 2 ways in which Python likes to read. To keep things simple, we are just going to read from text files, feel free to explore XML on your own later. XML is a pretty cool markup, but as you get deeper, it is kind of a headache. Enough of my tangents, to the coding board:
Opening a File in Python
This is pretty simple to explain. We have our awesome little test.txt file filled with some random text. Now, in the example we have our code. Just like you click a file to open it, Python needs to know what file to open. So, we use the open method to tell Python what we want to open and to go ahead and open (make a connection to) it. The “r” just tells Python that we want to read (it is “w” when we want to write to a file). And, of course, we set this new connection to a variable so we can use it later. However, we have only opened a file, which is not all that exciting. Let’s try reading from the file.
Python File Reading Methods
file.read(n) – This method reads n number of characters from the file, or if n is blank it reads the entire file.
file.readline(n) – This method reads an entire line from the text file.
Woot woot! So, this might be a little confusing. First, we open the file like expected. Next, we use the read(1), and notice that we provided an argument of 1, which just means we want to read the next character. So, Python prints out “I” for us because that is the first character in the test.txt file. What happens next is a little funky. We tell Python to read the entire file with read() because we did not provide any arguments. But, it doesn’t include that “I” that we just read!? It is because Python just picks up where it left off. So, if Python already read “I”, it will start reading from the next character. The reason for this is so you can cycle through a file without have to skip so many characters each time you want to read a new character. It’s complicated, I know, but think of reading like a one way process. Python is lazy, it doesn’t want to go back and reread contents. Let’s take this one step further with reading lines.
Ha! This time we were prepared for Python’s trickery. Since we just used the readline() method twice, we knew that we would get first 2 lines because of Python’s reading process. Of course, we also knew that readline() reads only a line because of it’s simple syntax. Alright, one last important, complicated, and awesome thing about Python’s reading abilities.
What!? Python just blew our minds! First, don’t freak out with the \n. It is just a newline character, since those lines are on a different file, Python wants to keep that format (you can always strip them out later).We open the file like normal, and we create a list, which we have mastered by now. Then, we break the file into lines in our for loop using the in keyword. Python is magically smart enough to understand that it should break files into lines. Next, as we are looping through each line of the file we use myList.append(line) to add each line to our myList list. Finally, when we print it out, Python shows us its glory. It broke each line of the file into a string, which we can manipulate to do whatever we want.
Wait! Don’t forget to close the file!
The important thing I saved until the end is that you should always close your files using the close() method. Python gets tired running around opening files and reading them, so give it a break and close the file to end the connection. It is always good practice to close files, your memory will thank you. Next, let’s do some construction by writing to files.
Commenting in Python is also quite different than other languages, but it is pretty easy to get used to. In Python there are basically two ways to comment: single line and multiple line. Single line commenting is good for a short, quick comment (or for debugging), while the block comment is often used to describe something much more in detail or to block out an entire chunk of code.
One Line Comments
Typically, you just use the # (pound) sign to comment out everything that follows it on that line.
Multiple Line Comments
Multiple line comments are slightly different. Simply use 3 single quotes before and after the part you want commented.
Alright, we are done with comments, but don’t forget them. They are your best friend in debugging complex Python code. Now onto the actual programming stuff.
Well, I’m not going to lie to you. The next few tutorials are going to be rather complicated if you have never had any experience with object oriented programming (OOP). Classes are awesome because of a few reasons. First, they help you reuse code instead of duplicating the code in other places all over your program. Classes will save your life when you realize you want to change a function. You will only change it in one spot instead of 10 different spots with slightly different code. Another important part of Classes is that they allow you to create more flexible functions. First, we need to get our hands dirty and start figuring out how to make a class.
Creating Classes in Python
Now, I’m not going to be like everyone else and start bombing terminology at you. Quite frankly, object oriented programming is rather difficult for a beginner and throwing these abstract concepts at you is just going to make you learn slower and hate OOP. So, a class is kind of like a function. We just establish it using the class keyword and following it up with whatever we want to name our class. In our case, we are making a calculator, so that’s what I called it. How original! Next, we throw in the argument of object. This is just simply a class above this class. Don’t worry much about it. It involves some serious terminology to explain. So, just type it and we will talk about it later.
Next, we get into this little guy def __init__ (self):. Abstract concept time! Objects are made from classes. So, if we had a class named cake. We could make cake objects. However, whenever you make a cake it’s not the same as the previous cake you made. Sure, it may look like it and taste like it, but it’s not that identical cake. So, in our class we have instances so that we know that they are two different cakes. Why do we need this you ask? Well, let’s make two cakes from the same class. Now, I take a big bite out of one of the cakes. Now, you definitely want to know which cake is which right? That’s why instances are so important! So, def __init__ (self): just says let’s create an instance of this class. But, why do we pass in a parameter of self, you might ask. Well, it is pretty related to what we just discussed. Classes make objects and the functions in a class become the object’s methods. However, we do need to know which class function belongs to which instance of the class, so we just implicitly pass in the objects property of self (discussed further in later example). Finally, we get down into the heart of the initialize function. Where we use self.current to create an instance variable equal to zero. Woo! We are done with the toughest part.
Next stop is the add function. We just pass in self and another parameter called amount. Again, self is so we know which instance. The amount is hopefully some number that was passed in. Using our previous knowledge, we understand that we are just adding whatever the amount is to the current variable.
Last, but certainly not least, we move onto this idea of “getting” variables from a class. To get the value of our self.current variable, we should use the best practice of putting it in a function and then calling the function to get the value so that we don’t mix up our instances. We set up the function and pass in the instance, and just tell Python to return the value.
Using Classes in Python
In another file, we put in this code. Once we run it, we see it prints 2 to our screen. All of that work just to get the result of 2! Anyways, let’s break this guy down. First, I have assumed that both of your classes are in the Python directory. Next, we use from ClassOne, which basically gives Python a reference to which file we are talking about. Then, we polish the statement off with import *. It just means that we want all of the classes in the file. In our case, we only have one class, the Calculator class. Next, we create an Calculator object called myBuddy by assigning it to the Calculator class with myBuddy = Calculator() . Now, this gives myBuddy all of the functions and variables in the Calculator class. (Note: once myBuddy gets those variables and functions, we call them properties and methods). Since we already initialized myBuddy, it has a property of current, and we see that property as a variable called self.current in the Calculator class that is set to 0. So, now we just call myBuddy.add(2) method, which is the add function in our Calculator class. Put simply, this is just 0 + 2. Finally, we output our instance class variable self.current by using the myBuddy.getCurrent() that returns our variable.
Well done! That was a long one. Take a breather. That’s one of the toughest concepts in programming to wrap your mind around. Believe it or not, when you use strings, lists, dictionaries, etc., they all are made from classes. From here, you should take some time and study object oriented programming and attempt to apply it in Python.