Formatting

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

Example
print('The order total comes to %f' % 123.44)
print('The order total comes to %.2f' % 123.444)
Result The order total comes to 123.440000
The order total comes to 123.44

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?

Formatting Strings

Strings are just like how we were formatting the numbers above except we will use a s for string instead of an f like before. Usually, you will only want to format a string to limit the number of characters. Let’s see it in action:

Example
a ="abcdefghijklmnopqrstuvwxyz"
print('%.20s' % a)
Result abcdefghijklmnopqrst

Strings

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!

Example
myString = ""
print (type(myString))
Result <class ‘str’>

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 awhile 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

String Indexes

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.

Example
a = "string"
print (a[1:3])
print (a[:-1])
Result tr
strin

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.

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

Example
f = open("test.txt","w") #opens file with name of "test.txt"
f.close()

…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.

Example
f = open("test.txt","w") #opens file with name of "test.txt"
f.write("I am a test file.")
f.write("Maybe someday, he will promote me to a real file.")
f.write("Man, I long to be a real file")
f.write("and hang out with all my new real file friends.")
f.close()

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:

Example
f.write("Maybe someday, he will promote me to a real file.\n")

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

Example
f = open("test.txt","a") #opens file with name of "test.txt"
f.write("and can I get some pickles on that")
f.close()

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.

Python Quiz

The Standard Python Quiz

It’s Python quiz time. You have finally finished our current tutorials for Python. No worries, more tutorials are still being developed, but for now, we have to rest. I would first like to congratulate you on working through those tutorials. Your dedication to learning a new language like Python is impressive, but you might be wondering exactly what you learned or how well you paid attention. That is precisely why we have crafted a quiz. The questions that compose this quiz are designed to test if you understand the basics of Python, but it will not quiz advanced topics. However, this quiz is probably the beginning of a series of quizzes for each tutorial category.

Start the Python Quiz

Python Tests and Exams

Currently, we only have a standard quiz that is not intended to be a professional test. There is a possibility to integrate a testing system into After Hours Programming, but we are not actively working towards that goal at the moment. For now, we have created a simple quiz to check your understanding of Python. Good luck and I hope you enjoyed our Python tutorial. Please contact us if you would like more Python tutorials.

Exceptions

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:

Example
var1 = '1'
try:
    var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
except:
    print(var1, " is not a number") #so we execute this
print(var1)

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:

Example
var1 = '1'
try:
    var2 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
except:
    var2 = int(var1) + 1
print(var2)

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.