The Python Variables tutorial explains several types of variables in Python and how to use them.
In the heart of every good programming language, including Python, are the variables. Variables are an awesome asset to the dynamic world of the web. Variables alone are dynamic by nature. However, Python is pretty smart when it comes to variables, but it is sometimes quite a pain. Python interprets and declares variables for you when you set them equal to a value. Example:
Isn’t that cool how Python figured out how a and b were both numbers. Now, let’s try it with the mindset of wanting the 0 to be a string and the 2 to also be a string to create a new string “02”.
Ah, see! Now, it thinks they are both strings simply because we put them in quotations. Don’t worry if you don’t understand strings yet, just note that they are not numbers or integers. This is really awesome, but as with any element or practice in a programming language there is always the flip side, especially with this auto declaration thing. Suppose we started off with “0” being a string, but we change our mind and want it to be a number. Finally, we decide that we want to add it to the number 2. Python bites us with an error. This brings us to the idea of casting the variable into a certain type.
Whoa, what is that int() thing? This is how you cast one variable type into another. In this example, we cast the string 0 to an integer 0. Let’s take a quick peak at a few of the important variable types in Python:
- int(variable) – casts variable to integer
- str(variable) – casts variable to string
- float(variable) – casts variable to float (number with decimal)
Like I said, those are just the most commonly used types of casting. Most of the other variable types you typically wouldn’t want to cast to.
Let’s explore some more tutorials or topics!
Python If Statement
The Python If Statement tutorial explains how to use an if statement in python as well as using the elif and else.
In the heart of programming logic, we have the if statement in Python. The if statement is a conditional that, when it is satisfied, activates some part of code. Often partnered with the if statement are else if and else. However, Python’s else if is shortened into elif. If statements are generally coupled with variables to produce more dynamic content. Let’s cut to an example really quick.
So, we have the variable a that equals twenty. Now, we run it through our if statement that checks to see if a is greater than or equal to 22. It isn’t. So, we skip past the inner print statement and continue to the elifstatement. This conditional checks if a is greater than or equal to 21. It isn’t either, which brings us to the final leg of our expanded if statement. The else is the catch all, which means if the previous conditionals are not satisfied, we will run the code inside it. So, we run the print(“else”), and we see in the results, the string else.
The If Syntax
The most important thing you might have missed in the example above is how Python’s syntax is a lot cleaner than other languages. However, this also means it is very picky and tends to bite beginners with errors. After every conditional we have a colon. Next, you must proceed to a new line with 4 spaces to tell Python you only want this code with 4 spaces to be run when the previous conditional is satisfied. Ok, well it doesn’t have to be 4 spaces, but you must be consistent with the spaces you use to indent. You can use 3 every time if you want, but 4 is kind of a standard. Also, if you wanted to run more than one statement after the conditional is satisfied, you must have a new line with the same number of spaces before the next statement.
Functions in Python are super useful in separating your code, but they don’t stop there. Any code that you think you will ever use anywhere else, you should probably put in a function. You can also add arguments to your functions to have more flexible functions, but we will get to that in a little bit. You can define a function by using the keyword def before your function name. Let’s use our first Python function.
It is necessary to define functions before they are called. Even though we have to skip over the function while reading to see the first statement, someFunction(). This throws us back up into the def someFunction():, again with a colon following it. Then after we acknowledge that the function is being called, we create a new line with four spaces for our simple print statement.
Functions with Arguments
Simple functions like the one above are great and can be used quite often. However, there usually comes a time where we want to have the function act on data that the user inputs. We can do this with arguments inside of the () the follows the function name.
Using the statement someFunction(12,451), we pass in 12, which becomes a in our function, and 451, which becomes b. Then, we just have a little print statement that adds them and prints them out.
Python does support global variables without you having to explicitly express that they are global variables. It’s much easier just to show rather than explain:
This will cause an error because our variable, a, is in the local scope of someFunction. So, when we try to print a, Python will bite and say a isn’t defined. Technically, it is defined, but just not in the global scope. Now, let’s look at an example that works.
In this example, we defined a in the global scope. This means that we can call it or edit it from anywhere, including inside functions. However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope.
As with any programming language, strings are one of the most important things to know about Python. Also as we have experienced in the other languages so far, strings contain characters. Strings are not picky by any means. They can contain almost anything if used properly. The are also not picky by the amount of characters you put in them. Quick Example!
The type() is awesome. It returns the variable type of whatever is inside the parentheses, which is very useful if you have a few bugs that you can’t figure out or if you haven’t looked a large chunk of code for a while and don’t know what type the variable is. Back to the amount of characters in a string, we can see even an empty set of “” returns as a string. Strings are powerful and are very easy to declare. Let’s look into some common string methods so you can get your hands dirty.
Common String Methods in Python
- stringVar.count(‘x’) – counts the number of occurrences of ‘x’ in stringVar
- stringVar.find(‘x’) – returns the position of character ‘x’
- stringVar.lower() – returns the stringVar in lowercase (this is temporary)
- stringVar.upper() – returns the stringVar in uppercase (this is temporary)
- stringVar.replace(‘a’, ‘b’) – replaces all occurrences of a with b in the string
- stringVar.strip() – removes leading/trailing white space from string
One of the really cool things about Python is that almost everything can be broken down by index and strings are no different. With strings, the index is actually the character. You can grab just one character or you can specify a range of characters.
Let’s discuss the print (a[1:3]) because it is the easiest to explain. Remember that Python starts all indexes from 0, which would have been the ‘s’ in our variable a. So, we print out ‘tr’ because we printed everything up to our range of 3, but not 3 itself. As for the second example, welcome to a beautiful part of Python. Essentially, specifying a negative number after a : in an index means that you want python to calculate the index starting from the end and moving toward the front aka backwards. So, we tell python that we want everything from the first character to the second to last character. Take a breather, you earned it.
We don’t have arrays; we have Python lists. Lists are super dynamic because they allow you to store more than one “variable” inside of them. Lists have methods that allow you to manipulate the values inside them. There is actually quite a bit to show you here so let’s get to it.
The brackets are just an indication for the index number. Like most programming languages, Python’s index starting from 0. So, in this example 1 is the second number in the list. Of course, this is a list of numbers, but you could also do a list of strings, or even mix and match if you really wanted to (not the best idea though). Alright, now let’s see if we can print out the whole list.
I told you we would come back to see how awesome the for loop is. Basically, variable a is the actual element in the list. We are incrementing an implicit index. Don’t get too worried about it. Just remember we are cycling through the list.
Common List Methods
There are number of methods for lists, but we will at least cover how to add and delete items from them. All of the list methods can be found on Python’s documentation website. Methods follow the list name. In the statement listName.append(2), append() is the method.
- .append(value) – appends element to end of the list
- .count(‘x’) – counts the number of occurrences of ‘x’ in the list
- .index(‘x’) – returns the index of ‘x’ in the list
- .insert(‘y’,’x’) – inserts ‘x’ at location ‘y’
- .pop() – returns last element then removes it from the list
- .remove(‘x’) – finds and removes first ‘x’ from list
- .reverse() – reverses the elements in the list
- .sort() – sorts the list alphabetically in ascending order, or numerical in ascending order
Try playing around with a few of the methods to get a feel for lists. They are fairly straightforward, but they are very crucial to understanding how to harness the power of Python.
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.
Python’s dictionaries are not very common in other programming languages. At least at first, they don’t appear normal. Some super variables like lists, arrays, etc, implicitly have an index tied to each element in them. Python’s dictionary has keys, which are like these indexes, but are somewhat different (I’ll highlight this in just a second). Partnered with these keys are the actual values or elements of the dictionary. Enough with my terrible explanation, let’s go with an example.
See, it’s a little weird isn’t it? If you tried to be an overachiever, you might have tried something like print(myExample). Python will bite you for this. Dictionaries aren’t exactly based on an index. When I show you how to edit the dictionary, you will start to see that there is no particular order in dictionaries. You could add a key: value and, it will appear in random places.
A big caution here is that you cannot create different values with the same key. Python will just overwrite the value of the duplicate keys. With all of the warnings aside, let’s add some more key:values to our myExampledictionary.
Isn’t that crazy how dictionaries are unordered? Now, you might not think they are unordered because my example returns alphabetical order. Well, try playing around with the key names and see if it follows your alphabetical pattern. It won’t. Anyways, adding a key:value is really easy. Simply put the key in the brackets and set it equal to the value. One last important thing about dictionaries.
All we did here was to spit out our whole dictionary. In lists when we told Python to print our variable out (in our case, it’s a), it would print out the value. However, with dictionaries, it will only print out the key. To get the value, you must use the key in brackets following the dictionary’s name. Dictionaries are a little confusing, but they are well worth your patience. They are lightning fast and very useful after you start using them.
We waited a little bit to talk about formatting because it might get a little intense with how much you can do and how easily you can do things with variables in Python. Formatting in Python is a little bit odd at first. But, once you get accustomed to it, you’ll be glad you did.
Formatting Numbers as Strings
Ya, I told you it’s a little weird. The f following the first % is short for float here because we have floating numbers and Python has a specific way of dealing with formatting decimals. The left % tells Python where you want to put the formatted string. The value following the right % is the value that we want to format. So, Python reads through the string until it gets to the first % then Python stops and jumps to the next %. Python takes the value following the second % and formats it according to the first %. Finally, Python places that second value where the first % is. We can use a single value such as a string or a number. We can also use a tuple of values or a dictionary. Alright, this is great, but what about formatting strings?
Strings are just like how we were formatting the numbers above except we will use a s for string instead of anf like before. Usually, you will only want to format a string to limit the number of characters. Let’s see it in action:
In any programming, including Python, exceptions and error handling often becomes a necessity when you are dealing with a considerable amount of variables. When, I say variables I do not mean variables as a placeholder, but variables as in you are using file system processes (like reading a file), dealing with external input, etc. Sometimes, you just do not know what will be thrown at your code. So you being little genius, you plan ahead and use exceptions and error handling where appropriate. Typically, the goal is to execute the code as intended, but if an exception occurs, we would prefer Python not to spit out its own exceptions. Instead, we would like to inform the user what went wrong using our wording and possibly how they can maneuver around the obstacle.
Exceptions vs Errors
I know I keep babbling about exceptions and errors, but what in the heck are they and how are they different you might ask. Well, exceptions generally deal with small little issues that you would probably like to handle. For example, maybe you do not exactly know the type of the variable, but you would definitely like to do something with it. The differences in doing things with numbers and strings are pretty different. So, you might set up something like this:
Awesome! We totally caught the exception that python gave us. We simply put the code we wanted to execute under the try block. However, if an exception occurred (adding a string to and integer is an exception) we told Python to do everything in the except block.
So, what are errors? Bad news, that’s what they are. You normally do not want to handle errors, unless you are doing some dangerous things. When an error is generated, it typically means Python is blowing up the ship, Obviously, if the ship is blown up, we should jump ship and get out of the program.
Also, you might have noticed that the print() takes two arguments in this example. Well, it can take as many arguments as you want to give it. print() will keep on printing all of your arguments with a space in between them.
Elegant Error Handling
Let’s face it our try/except above, doesn’t do a whole lot for the usability of the program. Basically, if it messes up it just tells our users what is wrong. What is the point in that? We should attempt to handle our exceptions in a manner that helps the program to keep moving on. A better alternative would be something like this:
Ah, much better. In this example, we use our simple except to catch an exception. But, if you run the example, you will see something much more awesome happening. We actually catch the exception, and tell python, “Well, try casting it to an integer before adding”, where Python faithfully obeys. As the end result, Python prints out the number 2 and the user is none the wiser that the program had a small hiccup.
Python Reading Files
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 thatreadline() 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.
Python Writing to Files
Reading files is cool and all, but writing to files is a whole lot more fun. It also should instill a sense of danger in you because you can overwrite content and lose everything in just a moment. Despite the threat of danger, we press on. Python makes writing to files very simple. With somewhat similar methods to reading, writing has primarily 2 methods for writing. Let’s get to it!
Warning! The Evil “w” in the Open Method
…And whoops! There goes our content. As I said, we are in dangerous water here friends. As soon as you place “w” as the second argument, you are basically telling Python to nuke the current file. Now that we have nuked our file, let’s try rebuilding it.
If you were continuing from the last tutorial, we just rewrote the contents that we deleted to the file. However, you might be flipping out screaming, “but it’s not the same!” You are 100% correct my friend. Hit the control key a couple of times and cool off, I’ll show you the fix in a minute. Ultimately, the write() method is really easy. You just pass a string into it (or a string variable) and it will write it to the file following that one way process it does. We also noticed that it kept writing without using any line breaks. Let’s use another method to fix this.
Writing Lines to a File
We have the a fairly easy solution of just putting a new line character “\n” at the end of each string like this:
It’s just a simple text formatting character. Yes, even text files have a special formatting similar to how HTML documents have their own special formatting. Text files are just much more limited than HTML.
Appending to a File
Boom! While our text file makes absolutely no sense to a human, we both know we just had a big victory. The only big change here is in the open() method. We now have an “a” (for append) instead of the “w”. Appending is really just that simple. Now go out there and write all over the world my friend.
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 calledmyBuddy 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. Soon, we will dive deeper into object oriented programming.