In this post we are going to write our first program. Most programming tutorials start out with a program called "Hello World". I find that boring so my first program in Python was a "mad lib" that I then emailed to all of my friends at work to see who could come up with the funniest result. If you are unfamiliar with mad libs you can find information about them here. The goal with this post is to get you able to write your own mad lib program.
What we will need is a way of getting input from the user and then insert that input into our story. To start, let's become acquainted with a new and complex type of object known as a "string". Strings are what we know as letters and anything made up of letters (words, sentences, novels, etc).
String objects are a little too complex to discuss in their entirety in one post. A sufficient definition for the purposes of this post is that a "string" object is a collection of one or more "characters". Let's play around with strings a little before beginning our program.
Open your python interpreter and create an object called myString and set it equal to "word". In order to declare a string object, the letters or numbers must be enclosed in single or double quotes. If you like, use the type() function we discussed last time on your object to see that it is a "str" object, short for "string".
Now that we have a string object, we have access to all sorts of methods for getting information and/or manipulating the information in the object. For instance, because our object is a collection of characters we can use a length function by typing:
len(<object name>)The return value will tell you the number of characters in your string. Additionally you can call a sorting method on your string by typing sorted(<object name>). This will return a different type of collection called a list (more on them in a later post). Notice that the items in the new return list are sorted in alphabetical order.
One of the most common and useful operations that can be done on a string object is called slicing. Slicing is a method of getting pieces of information from a string object. In order to access a single character of a string simply type <object name>[index number], where index number is whole number that refers to the position of the character in the string. In order to access the first character of our string object type:
myString[0]
All collection style objects start with an index number of 0. Because our string object has four characters, the possible index values are 0 through 3. Additionally, you can use negative index values to access the elements from end to start. myString[-1] will return the last character in our string, 'd'.
Confusingly enough, the negative index values begin at -1, so the negative index values possible on our string are -1 through -4. Don't worry, it'll eventually become second nature. Trying to access an index value that is outside of the range of the string object will result in a "IndexError" saying "string index out of range". These errors will also become all to familiar while you learn to program.
To summarize:
positive index 0 1 2 3
string characters w o r d
negative index -4 -3 -2 -1
One last thing about slicing, you can enter two indexes separated by a ':' to specify a start and end point of the data you want. For example: myString[1:3] will return 'or'. myString[-4:2] will return 'wo'. The index in front of the colon determines the starting character and the index after the colon determines the last character that will be printed.
[ first character to be printed : character to stop at ]
The colon can also be used with only one index like so:
[index:] means start at index and continue to end. (Equivalent to myString[index:-1])
[:index] means start at beginning and continue to index. (Equivalent to myString[0:index])
Like I said, strings are a very complex type of object, but this should act as a good introduction into using them. I'll talk about them in greater detail in a future posts.
Now we need to get input from the user. This can be done by simply using the built in python function, raw_input(). In order to use raw input, type: raw_input(<input message>). The <input message> should be a string, meaning it has to be enclosed in quotes or double quotes. When run, the function will prompt the user with the message and wait for the user to input a response. For example, if I type:
raw_input("How old are you?")
The interpreter will print "How old are you?" and wait for me to input a response. When I respond by typing 300 and pressing 'enter'. The interpreter will then print out my response. Note, that my response is printed as a string, even though I put in a number. (Yes, strings can have numbers in them) I know it is a string because it is enclosed in quotes. The raw_input() function will always take a user's input and creates a string object.
To start fitting some pieces together, we will now use the raw_input() function to assign values to variables. Doing so will allow us to take the user's response to our prompts and save it to use later when we print out our mad lib. In order to do this, we simply need to assign variable to have the value of the raw_input() function.
noun = raw_input("Input a noun")
That's all that is required, now the variable noun will be set to the string value that the raw_input() function will return once the user types something in.
We now need to deal with printing out the final mad lib. In order to that, we will use python's native print command. Print is pretty easy to get started with. A basic print command might be:
print "fish face"
But you can also print variables:
a = "fish face"
print a
Notice that when I first printed fish face I put it in quotes to signify that it was a string. The second time I told python to print a, it already knew was a string object, so I didn't need to put it in quotes. You can even combine what you print.
a = "fish face"
print a, "for the win!!"
print a + "for the win!!"
The first print statement above will print "fish face for the win!!", while the second statement will print "fish facefor the win!!". That is because the '+' will print both items out with no space in between while the ',' will add a space between the two items being printed. The '+' and ',' are known as concatenators; a fancy term meaning they combine things together.
The final piece of the puzzle is actually writing the program so it can be run over and over. In order to do so you'll need to open up your text editor of choice. I'll use Notepad++. Create a new document and save it as "madlibs.py". (If you're using Notepad++ you can go to "Language > P > Python" to enable Python language highlighting)
First, you'll want to know what your story is going to be, then you'll know what words you need to get from the user. Mine is only going to be two sentences long in order to provide an example for you. My story will read something like the following:
A guy walked down the road thinking about the cost of cheese in Wisconsin. As a result he was hit by a car.
I will replace the following words: guy, cheese, Wisconsin, hit, car. So I will need five variables, three nouns, a place, and a verb. See my code below.
Usually, if you run a python script it will open in a console and immediately close when finished. In order to keep the window from closing before you can read the result, I added an extra raw_input() function at the end with no user prompt. That way the program will remain open until the user presses enter.
Save your program. Then find it in your file browser and double click the file to run it.
Conflatulations, you've now written your first python program. If you come up with a hilarious mad lib feel free to post it in the comments section.
No comments:
Post a Comment