![]() |
Beginners Python Tutorial
This is a tutorial I originaly wrote for the hackers.com forum... but since that forum was taken down for the better part of the year I'll bring the tutorial here...
1. Intro Now what is Python? Well Python is a very powerful programming language that can be used for many things like Basic Adding to somewhat Complex Shell Programming and CGI’s it is also very simple to learn, this is a good language to learn if you are new to programming. This tutorial is written for people who have never programmed before so don’t expect to learn how to do any complex programs, Just Yet :D You can download Python at the link below: :
http://www.python.orgNOTE: For Linux users just find out where python is located... I think "/usr/bin/python" but not to sure, and than write the programs in a text editor... and to run just use the command: /user/bin/python filename.py There are two main ways to type the code in Python: 1. Use the Python Editor and save as a .py or 2. Use any text editing software and save as a .py NOTE: When saving your code if you are using text editing software make sure it saves in Plain Text Format. For this tutorial I will suggest using the Python editor since it is very simple to use. 2. Lets get started To start of your journy we will begin with a simple code. First open up IDLE (Python GUI) and go to File>New Window(Ctrl+N) to open the editor. Now I suggest saving once the new window is open because as you will see it makes your code nice and neat by giving differnt commands different colors. Go to File>Save (Ctrl+S) to save the file NOTE: Python has one annoying flaw in it. Every time you save a new file you have to give it the extention .py because it does not do it automatically :( Lest start with the simplest code ever: :
print "Hello, World"Now what just happend? A line of text appeared that said: Hello, World The command to print any information "print" followed by the content. You have to put your text in quotations because Python does not understand the command Hello, World the print command only lasts untill the end of the line so if you wish to print multiple lines you would have to put the code :
print "Blah Blah Blah line1"Here is one thing that is a must in Python programming, it is the Comment Line. A comment line is anything that gets skipped when it is read by Python just line the <!-- TEXT --> ignors the text in the middle in HTML. To use a comment in Python you just use the #, here is a simple program to show how comments work. :
#This is a comment line not read by the programComments extend to the end of the line so as shown in the last line of the code #meh print "print me" the text "print me" will not be seen when the program is run. 2a. Getting beyond the print Now I don't think you're reading this because you want to print out a whole bunch of text. You want to increase your bounderies and that is what we shall do. put in the following code and run: :
bloop = 20You were now just introduced to variables. Now what is a variable? A variable is anything that holds the information given How do I use variables? You can call a variable by: Putting a variable name (in this case bloop and bleep) followed by an equals sign and than the value of the variable. Example : stuff = 125 In the example above stuff is equal to the number 125 ... easy! Cool things you can do with variables is you can call 2 different varables in one line, you can assigne the data to more that one variable in one line and so on. Run the following code below: :
meh, deh = 5, 10NOTE: You can also set a string of text to a variable by having the value between quotations. Example: :
meh = "Hello Everyone":
#This program will calculate the area of a rectange and the area of a square:
disndat = input("blah blah blah")What about when I put "square ** 2" well what the ** means is TO THE POWER OF, so in this example it's to the power of 2(Multiplys square by itself one time). Did you also notice how I had a variable equal an equation, yes you can do that, hehe :mrgreen: Insted of making a variable for the equation I could of done: :
print blah * dahAnother thing you just learned was that the command print all by itself prints a blank line of text. Now what about when I put: :
print "The area of the rectange is:", areaRectangleThere is one more simple variable techniques I want you to learn. This is called raw_input. You may have tryed to type in text into one of the input variables and got an error if so here is the solution to the problem. :
#ask for user name and than print it out2b. Extra Print Features With print you can aslo do some other things. Lets say you wanted to print out a block of text instead of just 1 line, you can do it in 2 different ways. :
#The First WayHere is the second way: :
#The second and better way3. If, and, or, for, and while This chapter will teach you how to make loops and if statements. (WOOT!) Lets start off with the loop because well their short and simple to learn. Look at the code below: :
#A For LoopIf you are confused let me explane the code. for is the name of the loop and it means for VARIABLE give each value name is a variable, you do not need to call it before the program it is automatically called in is well self explanitory "Beegie_B", "H@GG!S", "Stone", "$watto" is each value that will be given to the variable, you can have as many as you want after the line you must put a comma ( : ) next the code gets indented, this means that whatever is indented belongs to the loop to exit the loop you just have to get rid of the indent NOTE: The white space in Python is necessary when working with loops and anything else followed by a comma. Now lets move on to the second kind of loop, a "while loop" here is an example: :
#A While Loopwhile s <= 10: now what does that command do. Well lets break it down. We started off with while(duh!) and than we put our variable(this variable has to be called before the loop) than we put the less than or equal to sign ( <= ) followed by the number. So what it means is, while the variable s is less than or equal to 10 then do the following. The commands inside the loop will be executed untill s is greater than 10. NOTE: The other commands besides <= are: == Equal to <= Less than or equal to < Less than > Greater than >= Greater than or equal to != Not equal to <> Not equal to Quick Program Test! Now I want you to try to make a program that will take a number a user inputs, and than add that number by 1 untill it reaches 400 and than print out the value of 400. ============================================== ANSWER: :
number = input("Number: ")I have another program I want you to try to make. Let the user input his name, and every time the name they input isn't "bob" make the program write the string "Sorry wrong name", and when the correct name is put in make the string "Welcome (persons name)" print. NOTE: when you want something to equal text you have to put it in brackets. Example: while name != "bob": ============================================== Answer: :
name = raw_input("Name: ")if statements are easy to use let me make you a basic program to show how it works. :
n = input("Number: ")If statements work simerlarly to while loops, they just don't loop, insted they will do the command given only if the information given is the same as what you told the statement to do. hehe I know thats a bad explanation but I think you should understand how it works. Here is another if statement program: :
n = input("Number: ")So whats new in that program? The command elif. elif works exactly like an if statement except elif is put inside the if statement if there are more than 2 ways of seperating data. Now I want you to try to improve that name program so that whenever the person inputs one of the 3 names: "steve", "bob", "joe" than it will print the string "Welcome (persons name)" ============================================== Answer: :
name = raw_input("Name: ")4. Functions Functions and Classes are the main part of Python programming, its the building block of moduals, and all that good stuff, hehe What is a function? Well a function is a part of a program that wont run untill the user wants to use it. Let me show you a basic funtion: :
def test(x):FIRST- you define functions using the command def SECOND- you follow the def command by the funtion name THIRD- you follow the funtion name with parenthasys () FOURTH- you can leave the parenthatsys blank and that will allow the funtion to be used wihtout any input FIFTH- You input all your code inside the funtion Now if you tryed running that program and nothing happend, don't think that there is somehting wrong, all you have to do when the program is run is put: test(any number) when I ran the program I had: test(10) and what returned was 11. I don't think you would want to use a function for a basic command like that, lets do something that use's all of our skills that we have learned. :
def euclid(a,b):Remember "%" gets the remander of the 2 numebrs. How the code works: What this program does is it takes the 2 numbers you input: eg euclid(99,15) a = 99, and b = 15. The variable "c" is assigned to be the value of "a" and "a" is assigned to be the value of "b". Than "b" is assigned the remander of "c" and "a". This is run through untill "b" is equal to zero. After "b" is equal to zero the program returns the value of "a". You may look at that and say "WTF!?!" and well I don't blame you, I know I said that when I first saw the code. I'll spend more time on functions, just be calm :D 4b. Sidetracked Before we go deeper into some functions let me teach you 2 more types of variable, well their not really variables but the begin with: "NAME =" The first one I'm going to teach you is a list. Here is a small example of how a list looks: :
boop = [10, 20, "Beeg", 40]So whats so good about lists? Well they can really help you out in complex programs. Now lets say you just wanted the list to show one of the 4 values, you would do something like this: :
boop = [10, 20, "Beeg", 40]NOTE: The first value of the list is always 0, so if you want the first value you would put "listname[0]" There are some special comands that go along with lists also, they are below: :
l = [1,2,3]l.append(value) allows you to add the value to the end of the list l.remove(value) removes that value l.pop(place) removes that place number in the list, and if used by itself it also prints the value before removing it. eg: l.pop(0) removes the first value of the list l[place] = "blah" gives that spot in the list to the value after the "=" sign. print[place] prints out that value print[place1:place2] prints out the value of the place and everything between untill it reaches the second place value. NOTE: print l[2:] will print out all the values from the third value to the last Now those arn't all the list command avalable, but they are the ones that are used most often. You will learn the rest if you go deeper into python programming, or untill I write a new tut :D What comes after list? Well the answer is, Databases! A database is almost like a list except it allows you to give the value a name, so instead of having to call something by it's position in the list, you can just call it by name. A simple database would look like this: :
dbase = {Now if you wanted to print out the first value you would just put: :
print = dbase["a"]Well, there is one thing you should know before I get off databases, they do not have the commands like in lists. 4c. End of functions Now that you know how lists and databases work, you can start making some cool functions. I can't really tell you much more about functions because I'm to lazy right now to write some more so it looks like I'm done. :D 5. Conclusion Okay, so the tutorial is done, FINALLY! hehe, and well I hope it gets you on your way to some better knowledge in programming. If you have any questions with how to use some commands and stuff just ask them in this forum so everyone can see the question's and answers so we all learn. I Hope you like my tutorial. Beeg |
Very nice tut Beeg, couldn't have explained it better myself. Perhaps if I get some free time I'll write up some more advanced ones once they read this one. Write some more on functions and get into classes, but over all very nice job :D
The one function that I think needs pointing out is the len() function which I often find very usefull. If you need to find out how many items are in a list or dictionary just use len(). For example: :
list = ["cat","dog",5,"bird"] # Creats a list with those objects in itI've used that little function many of a time for many differnt task. len() also coutns how many characters in a string For Example: :
x = "Python rocks!"The last thing I would like to point out is all those example above we're made using IDLE. Python can be just as powerful and you can code often times quicker with just using the command based version, regular old Python.exe. for exmaple if I wanted to know how many charcters were in plan text document quickly, I'd just go to run and fire up python.exe. Once in I could quickly type :
file = open("C:/file.txt",r) #open a file for readingThere isn't that big of a differnce in time, if you need to do something small, and you need it done fast, I'd use the command line, if you're going to be writing a script with a bunch of functions and classes and possibly writing differnt modules, then by all means it's best to use IDLE. Anyway, very good tutorial beeg :) |
Haven't read all of it, but from what I've seen, it's a bloody good tut.
|
yah, thanks for the good revies :D
I was thinking of doing a tut on Classes and so on... and Yes, the len function is amazing, there is alot of programs that need it, especially when it comes to reading files. Also, a small tutorial on opening, reading, and writing files wouldn't be bad ether. Beeg |
yeah, I'll write the one on file IO, prob won't have much time until christmas break though :)
|
sounds good to me, why don't we all just merge all the tuts we write into one big one... or we can seperate it in chapters... it's up to you
Beeg |
We could make a nice little PDF or something
|
good information guys... i need to brush up on my python a good bit, eventually. ;)
|
I have finaly decided to start python :)
|
Good man.
|
| All times are GMT -5. The time now is 6:10 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC