This is a brief expanation of how to get started writing programs in Python. It is based on three messages posted on the Dev Shed Beginner's Forum. The current version is essentially the unmodified original text, though it intended that it will be edited and expanded in the near future.
OK, since you originally posted to the Python forum, I assume that that is where you want to start - all good with that. I'll start from the pretty much the basics, though I'm assuming you know enough about computers in generally to, say, start the computer, open the web browser, get on a web page and enter a message on a message board :)
If you are on the same computer as he is, and he's already got Python set up on the system, then you are probably all set for tools - all you really need is the Python interpreter and a simple text editor like Notepad, TextEdit or pico, though there are editors specifically for Python which might make it easier to start out. If you're on a different computer, you can go to the main Python download page to download an installable version. You'll find installers for most types of computer systems there.
Once you have the program installed, you can get started immediately. Assuming you're on a Windows box, you can go to the Start menu, go to [All] Programs , and look for a folder marked Python 2.4 or something similar to that (the square brackets mean that the word 'All' may or may not be there, depending on the version of Windows). In that folder, you will find a program marked Python (command line). This is the main Python interpreter, which is the program that actually runs a Python program after you've run it. You can also use it 'interactively', which means you that if you run the interpreter without a particular program, it will let you type in little snippets of programs and run them right the and there. Running this now will bring up a console window, with white text on a black background (usually, though it could be configured differently).
There will probably be a few other programs and files there as well: usually, it will have Python Manuals and Module Docs, which are information files about the interpreter and the language; an uninstaller, if you need to get rid of Python for some reason; and a program called Idle (Python GUI). This last one is a 'front end' for the interpreter, a program which makes it a little easier to work in the interactive interpreter.
Let's start by trying a few simple things with the listener. If you start up Idle, you will get a plain white window with a copyright notice and some other information, followed by a line that looks something like:
This is what is called the 'listener' or 'interpreter prompt'. If you've ever used MS-DOS, or a console window, it might look familiar, but if it doesn't, don't worry too much right now. When you start up, the cursor should be right there at the listener, so if you start typing it should start appearing right after the prompt. Type the following
2 + 2
then hit enter. The result should look something like this:
>>> 2 + 2 4 >>>
What just happened is that the interpreter read what you just typed, interpreted it as a line of Python source code, and gave the result of that little program. It then puts a new prompt up where you can add more lines of source code.
OK, so adding 2 and 2 isn't so exciting, I know. This is just the start, trust me. We still need to lay a good deal more foundation before we can do anything really spectacular, but just with that, you've starting writing at least a very simple program.
Python let's you use several other mathematical operators like that, which look at least a little like the ones used in regular math, and let's you use decimal fractions for numbers. For example, to multiply two and five, you would type
2 * 5
The asterisk * stands for 'multiply', the hyphen - is subtraction, the slash / is division, the double asterisk ** is exponentiation ('to the power of'), and the percentage sign % is the remainder (actually, it's something sort of like remainder, call 'modulo', but you can think of it as getting the remainder of a division). For example:
>>> 2 - 3 -1 >>> 6 / 2 3 >>> 2 / 6 0 >>> 2 % 6 2 >>> 2 ** 4 16
Note that if you use only integers (a whole number, rather than a fraction), it gives only an integral result, even if it means that dividing a smaller number by a larger one gives zero. If you use a decimal fraction for one or more of the numbers, it treats division differently:
>>> 2.0 / 6 0.33333333333333331
You can combine these as well:
>>> 10.0 / 2.0 + 6.0 11.0
Which divides 10 by 2 and then adds 6. The order of operations is like that in normal math; that is to say, exponentiation comes first, then multiplication, division and modulo, then addition and subtraction. You can group numbers using parentheses:
>>> 10.0 / (2.0 + 6.0) 1.25
Which adds 2 and 6 first to get 8, then divides 10 by that.
Try a few different expressions to get a feel for how it works before going on. Now, if you make a mistake along the way, you may get a 'syntax error', which means you typed in something that the interpreter couldn't parse (make sense of). In Idle, they look like this:
>>> 188.8.131.52 /4 SyntaxError: invalid syntax
Also, if you type something impossible to calculate, you may get something like this:
>>> 2/ 0 Traceback (most recent call last): File "<pyshell#21>", line 1, in -toplevel- 2/ 0 ZeroDivisionError: integer division or modulo by zero
This is the interpreter's response to something it can't handle.
Now, obviously the Python interpreter can do more than just math; otherwise, it would be pretty useless for writing programs. Python can also use letters and symbols (called 'characters'), though they have written in a particular way, for reasons I'll explain in a moment. To have Python show a letter as the letter itself, you need to put quote marks around it:
>>> 'a' 'a'
You can use double quotes " instead, but you have to make sure that whichever one you use, you use the same one both before and after the letter:
>>> 'a' 'a' >>> "b" 'b' >>> "c' SyntaxError: EOL while scanning single-quoted string
(You'll notice that it always prints the result with single quotes.)
You can use the quotes to hold a 'sentence' of several characters (called a string) as well:
>>> "Hello, World!" 'Hello, World!'
Now, you usually don't want the string to show the quotes, because it looks rather strange like that. To print a string as by itself, you would use the print command:
>>> print 'Hello, World!' Hello, World!
The print command is a part of the language which prints out whatever the results of the expression come after it:
>>> print 2 + 5 7
Now, this may seem useless right now, but as you'll see, when you are writing actual full programs, the results of an expression won't get printed the way it does when you run it at the interpreter prompt. Also, you can now see why the strings need to be in quotes: otherwise, the interpreter would try to run the string as a function or as variables.
Now, if this was all you could do in Python, it would be pretty useless for writing programs; there's still a lot more in the language. You'll notice that I just mentioned variables, for example. Now, you can think of a variable as a name for something. You can put a value into a variable using the assignment operator =, like this:
x = 2
Notice that this doesn't give any result, However, if after this you type the variable name into the listener, you'll get back the value you gave it:
>>> x = 2 >>> x 2
As the name 'variable' implies, you can change the value later:
>>> x 2 >>> x = 4 + 10 >>> x 14
OK, to pick up where I left off: in addition to variables, Python also allows you to define functions. One way of looking at a function is that it is a name given to a sequence of expressions, which can be then used to run those expressions whenever the function is called. For example, try typing in
>>> def Hello(): print 'Hello, World!'
After this, if you the name of the function followed by a pair of matching parentheses, you will get:
>>> Hello() Hello, World!
Now, you'll see that when you type this in to the listener, something interesting happens: when you hit the enter key at the end of the first line, the Idle mini-editor automatically indents the second line and those following it by a certain amount (in Idle, it actually uses a tab character, which is an invisible character that says, 'move over by so many blank spaces'; other editors will use actual spaces, but it doesn't actually matter which it does, so long as the line gets indented). You'll also find that you need to hit enter twice after the last line, before it goes back to the listener prompt. In Python, groups of expressions - called blocks - are marked by indenting the expressions in the block; every function has at least one block, as do some other kinds of compound expressions (as I will explain shortly), and there can be blocks inside of other blocks, where the indentation goes one level further for each block that is inside of another one. If this doesn't make much sense yet, don't worry; I will show how this works shortly.
Now, I should explain a bit more about how the function definition works. The def keyword is short for 'define', and it tells the interpreter that you are creating a function. the next word following def is used as the name of the function. The function name is then followed by a list of parameters, which are put together in a pair of parentheses; even if the function doesn't have any arguments, you still need the parentheses, as they show that the defined object is a function rather than a variable. Finally, the line is ended with a colon :, which marked the beginning of the block which makes up the function's body (the group of instructions in the function).
In this case, the next line is the whole of the function body; when the function is called by writing Hello(), it causes the interpreter to look up the function definition, and run the expressions that are in the function body. Once again, you need the parentheses, even though the function doesn't have any parameters, if you type just the name of the function, it will return a reference to the function itself, rather than running the function:
>>> Hello <function Hello at 0x00DC84F0>
You should also note that Python expressions are case-sensitive; that means, it treats capital letters as being different characters from lowercase letters. So, if you were to now type in 'hello()' with the lowercase 'h', it would return "NameError: name 'hello' is not defined". This can be a tricky source of problems.
As mentioned earlier, a function can take a list of parameters, which are variables whose values are set when you call the function. For example, if you define the following function:
def show(x): print "The value of x is" print x
you could then call it like this:
>>> show(1) The value of x is 1 >>> show('w') The value of x is w
In this case, the value 1 (the function's argument) is put into the variable x at the start of the function, and is the value of the variable from there on out. (Note that I gave more than one value to print. Also, from here on, most of the times when I write out a function, I will only type out the function itself, not the prompt, so you can see what the actual function itself looks like.)
In addition to taking a value as an argument, a function can also return a value as it's result. for example:
def plus_one(x): return 1 + x
When you call this with a number, it returns that number plus one:
>>> plus_one(2) 3
Note, however, that passing it a string argument will cause problems, because you cannot add a string and a number:
plus_one('a') TypeError: unsupported operand type(s) for +: 'int' and 'str'
This is the same result you would get if you tried to run
1 + 'a'
Functions can even call other functions:
def print_plus_one(x): print "The result of adding one to", x, "is", plus_one(x) >>> print_plus_one(5) The result of adding one to 5 is 6
Now, in all of the things we've done so far, the code we've written has always done the same things, regardless of what the values we used. However, to be able to do more complex things, a program has to be able to take different directions depending on the circumstances. To let you do this, Python has several conditional statements, which take different actions depending on if something is true or false. The first of these is call the if: statement:
def more_than_ten(x): if x > 10: print x, "is greater than 10" return True else: print x, "is less than 10" return False
(Notice that we use the keywords True and False here; they are special constants representing those concepts uniquely. Also, the > sign is used to compare two values to see if the one on the left side is more than the one on the right.)
When we run these with different arguments, we get different results depending on whether the argument is more than ten or not:
>>> more_than_ten(5) 5 is less than 10 False >>> more_than_ten(12) 12 is greater than 10 True >>> more_than_ten(10) 10 is less than 10 False
By combining this with a function that calls itself recursively, we can repeat something a specific number of times:
def stars(n): "prints out a n asterisks in a row" if n > 0: # determine if we are at the last star to print out # print a star and have the next print call on the same line print '*', stars(n - 1) # call stars() with one less star to print >>> stars(5) * * * * *
This may seem strange, since it looks as if you are using that parameter n with different values each time it calls itself; and in fact that is exactly what is happening. Every time you call a function, it creates it's own version of its parameters, separately from the other calls. Because of this, the different calls don't conflict with each other.
You'll notice that there are some strange extra lines in the code. These comments are used to describe what the function is doing, so that if someone reads it later, they can understand better what the function is supposed to do. The string just under the function name is a special case called a documentation string, which is used to automatically create a description of the function which certain automatic tools can use to create documentation files for several functions at once.
The last thing I mentioned in the last posting was how you could write comments for people reading your programs after they are written. But how can someone ever read a function like that? So far, everything we've done has been at the interpreter prompt; when you exit Idle, it will all vanish. So how can you create a permanent program? The answer is that you need to create a source file which you write the program into, which you then can save, run, and edit later on.
For Python, you can write a your program files in any editor that can save a file as plain text, that is, a file of ordinary characters without things like special fonts, embedded images, tables, etc. In Windows, the default text editor is Notepad, but there are many other editors for various special purposes, including ones specifically for a given programming language - such as Python. There are several such editors for Python, including one which is built into Idle itself. Others which you might want to try using include Dr Python and Boa Constructor, which have additional tools to make writing Python programs easier; a list of them can be found in the Python Resources Thread.
To use the editor in Idle, you go to the File menu and choose New Window, which then opens an editor window. If you then enter a program like this one:
print "Hello!" name = raw_input("What is your name? ") print "Nice to meet you,", name, "!"
and then go to File: Save As... and save the file as 'greet.py', you will have created your first permanent Python program. Now you can run this by going to Run: Run Module, which will start the program in the original interpreter window:
Hello! What is your name? Jay Osako Nice to meet you, Jay Osako !
Now, you might ask why anyone would use the listener at all, if you have to save them in a separate editor to write actual programs. The reason I had you start out in the listener was so that you could see how the individual expressions work, and how they then fit together into statements, functions, and so on. Also, there are times when you want to test out something quickly, without wanting to write out a full program for it; the listener is a convenient way to do this.
At this point, you should have at least a sense for how the interpreter and the language work. There are a lot more things to Python; I've only given you the smallest taste of it that I thought would get you started. To actually learn to program in Python, go through some of the longer tutorials mentioned in the resource thread, read the Python language documentation, try reading and modifying other people's programs, and most of all, write as many of your own programs as you can. Good luck, and feel free to ask any questions you have about it.