HaCkErS PaGe
Intro
First things first
So, you've never programmed before. As we go through this tutorial I will attempt to teach you how to program. There really is only one way to learn to program. You must read code and write code. I'm going to show you lots of code. You should type in code that I show you to see what happens. Play around with it and make changes. The worst that can happen is that it won't work. When I type in code it will be formatted like this:
##Python is easy to learn
print "Hello, World!"
That's so it is easy to distinguish from the other text. To make it confusing I will also print what the computer outputs in that same font.
Now, on to more important things. In order to program in Python you need the Python software. If you don't already have the Python software go to http://www.python.org/download/ and get the proper version for your platform. Download it, read the instructions and get it installed.
Installing Python
First you need to download the appropriate file for your computer from http://www.python.org/download. Go to the 2.0 link (or newer) and then get the windows installer if you use Windows or the rpm or source if you use Unix.
The Windows installer will download to file. The file can then be run by double clicking on the icon that is downloaded. The installation will then proceed.
If you get the Unix source make sure you compile in the tk extension if you want to use IDLE.
Interactive Mode
Go into IDLE (also called the Python GUI). You should see a window that has some text like this:
Python 2.0 (#4, Dec 12 2000, 19:19:57)
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
IDLE 0.6 -- press F1 for help
>>>
The >>> is Python way of telling you that you are in interactive mode. In interactive mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive mode allows you to test out and see what Python will do. If you ever feel you need to play with new Python statements go into interactive mode and try them out.
Creating and Running Programs
Go into IDLE if you are not already. Go to File then New Window. In this window type the following:
print "Hello, World!"
First save the program. Go to File then Save. Save it as 'hello.py'. (If you want you can save it to some other directory than the default.) Now that it is saved it can be run.
Next run the program by going to Edit then Run script. This will output Hello, World! on the *Python Shell* window.
Using Python from the command line
If you don't want to use Python from the command line, you don't have too, just use IDLE. To get into interactive mode just type python with out any arguments. To run a program create it with a text editor (Emacs has a good python mode) and then run it with python program name. Instant Hacking
This is a short introduction to the art of programming, with examples written in the programming language Python. (If you already know how to program, but want a short intro to Python, you may want to check out my article Instant Python.) This article has been translated into Italian, Polish, and Japanese, and is in the process of being translated into Korean.
This page is not about breaking into other people's computer systems etc. I'm not into that sort of thing, so please don't email me about it. For more information about what hacking is really about, take a look at hackerethic.org.
Note: To get the examples working properly, write the programs in a text file and then run that with the interpreter; do not try to run them directly in the interactive interpreter - not all of them will work. (Please don't ask me on details on this. Check the documentation or ask on the tutor list).
Hacking using python
The Environment
To program in Python, you must have an interpreter installed. It exists for most platforms (including Macintosh, Unix and Windows). More information about this can be found on the Python web site. You also should have a text editor (like emacs, notepad or something similar).
What is Programming?
Programming a computer means giving it a set of instructions telling it what to do. A computer program in many ways resembles recipes, like the ones we use for cooking. For example [1]:
Fiesta SPAM Salad
Ingredients:
Marinade:
1/4 cup lime juice
1/4 cup low-sodium soy sauce
1/4 cup water
1 tablespoon vegetable oil
3/4 teaspoon cumin
1/2 teaspoon oregano
1/4 teaspoon hot pepper sauce
2 cloves garlic, minced
Salad:
1 (12-ounce) can SPAM Less Sodium luncheon meat,
cut into strips
1 onion, sliced
1 bell pepper, cut in strips
Lettuce
12 cherry tomatoes, halved
Instructions:
In jar with tight-fitting lid, combine all marinade ingredients;
shake well. Place SPAM strips in plastic bag. Pour marinade
over SPAM. Seal bag; marinate 30 minutes in refrigerator.
Remove SPAM from bag; reserve 2 tablespoons marinade. Heat
reserved marinade in large skillet. Add SPAM, onion, and
green pepper. Cook 3 to 4 minutes or until SPAM is heated.
Line 4 individual salad plates with lettuce. Spoon hot salad
mixture over lettuce. Garnish with tomato halves. Serves 4.
Of course, no computer would understand this... And most computers wouldn't be able to make a salad even if they did understand the recipe. So what do we have to do to make this more computer-friendly? Well – basically two things. We have to (1) talk in a way that the computer can understand, and (2) talk about things that it can do something with.
The first point means that we have to use a language – a programming language that we have an interpreter program for, and the second point means that we can't expect the computer to make a salad – but we can expect it to add numbers, write things to the screen etc.
Hello...
There's a tradition in programming tutorials to always begin with a program that prints "Hello, world!" to the screen. In Python, this is quite simple:
print "Hello, world!"
This is basically like the recipe above (although it is much shorter!). It tells the computer what to do: To print "Hello, world!". Piece of cake. What if we would want it to do more stuff?
print "Hello, world!"
print "Goodbye, world!"
Not much harder, was it? And not really very interesting... We want to be able to do something with the ingredients, just like in the spam salad. Well – what ingredients do we have? For one thing, we have strings of text, like "Hello, world!", but we also have numbers. Say we wanted the computer to calculate the area of a rectangle for us. Then we could give it the following little recipe:
# The Area of a Rectangle
# Ingredients:
width = 20
height = 30
# Instructions:
area = width*height
print area
You can probably see the similarity (albeit slight) to the spam salad recipe. But how does it work? First of all, the lines beginning with # are called comments and are actually ignored by the computer. However, inserting small explanations like this can be important in making your programs more readable to humans.
Now, the lines that look like foo = bar are called assignments. In the case of width = 20 we tell the computer that the width should be 20 from this point on. What does it mean that "the width is 20"? It means that a variable by the name "width" is created (or if it already exists, it is reused) and given the value 20. So, when we use the variable later, the computer knows its value. Thus,
width*height
is essentially the same as
20*30
which is calculated to be 600, which is then assigned to the variable by the name "area". The final statement of the program prints out the value of the variable "area", so what you see when you run this program is simply
600
Note: In some languages you have to tell the computer which variables you need at the beginning of the program (like the ingredients of the salad) – Python is smart enough to figure this out as it goes along.
Feedback
OK. Now you can perform simple, and even quite advanced calculations. For instance, you might want to make a program to calculate the area of a circle instead of a rectangle:
radius = 30
print radius*radius*3.14
However, this is not significantly more interesting than the rectangle program. At least not in my opinion. It is somewhat inflexible. What if the circle we were looking at had a radius of 31? How would the computer know? It's a bit like the part of the salad recipe that says: "Cook 3 to 4 minutes or until SPAM is heated." To know when it is cooked, we have to check. We need feedback, or input. How does the computer know the radius of our circle? It too needs input... What we can do is to tell it to check the radius:
radius = input("What is the radius?")
print radius*radius*3.14
Now things are getting snazzy... input is something called a function. (You'll learn to create your own in a while. input is a function that is built into the Python language.) Simply writing
input
won't do much... You have to put a pair of parantheses at the end of it. So input() would work – it would simply wait for the user to enter the radius. The version above is perhaps a bit more user-friendly, though, since it prints out a question first. When we put something like the question-string "What is the radius?" between the parentheses of a function call it is called passing a parameter to the function. The thing (or things) in the parentheses is (or are) the parameter(s). In this case we pass a question as a parameter so that input knows what to print out before getting the answer from the user.
But how does the answer get to the radius variable? The function input, when called, returns a value (like many other functions). You don't have to use this value, but in our case, we want to. So, the following two statements have very different meanings:
foo = input
bar = input()
foo now contains the input function itself (so it can actually be used like foo("What is your age?"); this is called a dynamic function call) while bar contains whatever is typed in by the user.
Flow
Now we can write programs that perform simple actions (arithmetic and printing) and that can receive input from the user. This is useful, but we are still limited to so-called sequential execution of the commands, that is – they have to executed in a fixed order. Most of the spam salad recipe is sequential or linear like that. But what if we wanted to tell the computer how to check on the cooked spam? If it is heated, then it should be removed from the oven – otherwise, it should be cooked for another minute or so. How do we express that?
What we want to do, is to control the flow of the program. It can go in two directions – either take out the spam, or leave it in the oven. We can choose, and the condition is whether or not it is properly heated. This is called conditional execution. We can do it like this:
temperature = input("What is the temperature of the spam?")
if temperature > 50:
print "The salad is properly cooked."
else:
print "Cook the salad some more."
The meaning of this should be obvious: If the temperature is higher than 50 (centigrades), then print out a message telling the user that it is properly cooked, otherwise, tell the user to cook the salad some more.
Note: The indentation is important in Python. Blocks in conditional execution (and loops and function definitions – see below) must be indented (and indented by the same amount of whitespace; acounts as 8 spaces) so that the interpreter can tell where they begin and end. It also makes the program more readable to humans.
Let's return to our area calculations. Can you see what this program does?
# Area calculation program
print "Welcome to the Area calculation program"
print "---------------------------------------"
# Print out the menu:
print "Please select a shape:"
print "1 Rectangle"
print "2 Circle"
# Get the user's choice:
shape = input("> ")
# Calculate the area:
if shape == 1:
height = input("Please enter the height: ")
width = input("Please enter the width: ")
area = height*width
print "The area is", area
else:
radius = input("Please enter the radius: ")
area = 3.14*(radius**2)
print "The area is", area
New things in this example:
print used all by iself prints out an empty line
== checks whether two things are equal, as opposed to =, which assigns the value on the right side to the variable on the left. This is an important distinction!
** is Python's power operator – thus the squared radius is written radius**2.
print can print out more than one thing. Just separate them with commas. (They will be separated by single spaces in the output.)
The program is quite simple: It asks for a number, which tells it whether the user wants to calculate the area of a rectangle or a circle. Then, it uses an if-statement (conditional execution) to decide which block it should use for the area calculation. These two blocks are essentially the same as those used in the previous area examples. Notice how the comments make the code more readable. It has been said that the first commandment of programming is: "Thou shalt comment!" Anyway – it's a nice habit to acquire.
Exercise:
Extend the program above to include area calculations on squares, where the user only has to enter the length of one side. There is one thing you need to know to do this: If you have more than two choices, you can write something like:
if foo == 1:
# Do something...
elif foo == 2:
# Do something else...
elif foo == 3:
# Do something completely different...
else:
# If all else fails...
Here elif is a mysterious code which means "else if" :). So; if foo is one, then do something; otherwise, if foo is two, then do something else, etc. You might want to add other options to the programs too – like triangles or arbitrary polygons. It's up to you.
Loops
Sequential execution and conditionals are only two of the three fundamental building blocks of programming. The third is the loop. In the previous section I proposed a solution for checking if the spam was heated, but it was quite clearly inadequate. What if the spam wasn't finished the next time we checked either? How could we know how many times we needed to check it? The truth is, we couldn't. And we shouldn't have to. We should be able to ask the computer to keep checking until it was done. How do we do that
Free Webpages at Webspawner.com
languages lisps programs and tips
our other site
Send E-Mail to: cole_gex@hotmail.com
This page created using the webpage creation facilities of Webspawner.
Copyright © 2002 brandon. All Rights Reserved