Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 25th, 2004, 11:37 PM   #1
Beegie_B
Programmer
 
Join Date: Nov 2004
Location: Windsor, Ontario, Canada
Posts: 32
Rep Power: 0 Beegie_B is on a distinguished road
Send a message via ICQ to Beegie_B Send a message via MSN to Beegie_B
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

You can download Python at the link below:
http://www.python.org
This tutorial is written for people using any Windows OS since it is easier to use with its GUI.
NOTE: 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 save your document with Ctrl+S and run it by pressing F5.

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"
print "Blah line2"
print "and so on and so on"
print "and so on"
Simple isn't it?

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 program
print "PROGRAMMING FORUMS OWNZ" #Prints out PROGRAMMING FORUMS OWNZ
print "#This is not a comment"
#meh print "print me"
That is really simple and I'm guessing Easy to understand.
Comments 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 = 20
bleep = 30
print bloop + bleep #Adds bloop and bleep
print bloop * bleep #Multiplys bloop and bleep
print bleep / bloop #Divides bloop and bleep
print bleep % bloop #Finds the remainder of bleep and bloop
print bleep - bloop #Subtracts bloop and bleep
What's new with this?
You 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, 10
bloop = bleep = 20

print meh
print deh
print bloop
print bleep
So what happend when your ran the program? Well meh was equal to 5, deh was equal to 10 and both bloop and bleep were equal to 20. Now let me explane how the meh and deh line worked. Each variable name goes along with a variable value in the same order, so if you had a,b,c = 1,2,3 a would be 1, b would be 2, and c would be 3; understand? Now let me explane the bloop = bleep = 20 line. In this line you set bleep to be the value of 20, and bloop to be the value of 20.
NOTE: You can also set a string of text to a variable by having the value between quotations. Example:
meh = "Hello Everyone"
Now life is just plain with you calling the shots now isn't it? Lets get the user who would run the program the ability to input his own information.
#This program will calculate the area of a rectange and the area of a square

length = input("The length of the rectange is: ")
width = input("The width of the rectange is: ")
square = input("The width of the square is: ")
areaRectangle = length * width
areaSquare = square ** 2 #The ** means to the power of

print
print "The area of the rectange is:", areaRectangle
print "The area of the square is:", areaSquare
What are some new things? We now have the input command, and as you can see the input command allows a user to input info. You can use input commands by setting a varable name followed by an equals sign than input("text"). Example:
disndat = input("blah blah blah")
Simple eh?
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
Insted of making a variable for the equation I could of done:
print blah * dah
But I just did it with the variable because well, I wanted to.
Another 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:", areaRectangle
print "The area of the square is:", areaSquare
This is very easy to explane, I printed out a line of text in quotations and than followed by a comma I put the variable name, I think you should know what happens so I wont explane this in deatail.

There 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 out

name = raw_input("What is your name? ")
print "Hello", name
Well the raw_input command is exactly like the input command except this one takes strings of text instead of numbers.

2b. 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 Way
print "This is line one"
print "This is line two"
print "and so on"
It's a hassle having to put "print" infront of every line.
Here is the second way:
#The second and better way
print """This is line one
This is line two
and so on"""
as you can see I put 3 quotation marks after print, what this did was indicate that to continue reading lines until it reache's the other 3 quotations... SIMPLE!

3. 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 Loop

for name in "Beegie_B", "H@GG!S", "Stone", "$watto":
  print name,", is Sweet"
This loop above is called a for loop because it starts with for, hehe. Well what a for loop does is it takes a variable and gives it the value for each time it runs.
If 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 Loop

s = 0
while s <= 10:
  print s
  s = s + 1
What just happend with this program. Well we set s to equal 0(simple eh?) than we put:

while 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: ")
while number < 400:
  number = number + 1

print number
Simple isnt it?

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: ")
while name != "bob":
  print "Sorry wrong name"
  name = raw_input("Name: ")
print "Welcome", name
Now the name program is preatty crappy now isn't it. What if you wanted to have 3 different working names istead of one? Well for that we would use an IF statement.

if statements are easy to use let me make you a basic program to show how it works.
n = input("Number: ")
if n < 50:
  print "The number is less than 50"
else:
  print "The number is more than or equal to 50"
Now lets look at the above program, looks simple doesn't it? Well that is because it is

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: ")
if n < 0:
  print "The number is less than 0"
elif n == 0:
  print "The number is 0"
else:
  print "The number is more than 0"
If you ran the program you would see that if you input a number less than 0 it prints the string "The number is less than 0", and so on.
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: ")
if name == "bob":
  print "Welcome", name
elif name == "steve":
  print "Welcome", name
elif name == "joe":
  print "Welcome", name
else:
  print "Wrong name!"
If you want you can try to put that program into a loop so it will ask to input the name untill it is the right name, but me, I'm moving on.

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):
  x = x + 1
  return x
Now lets have a look at that code.
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):
  while b != 0:
    c = a
    a = b
    b = c % a
  return a
The code above is euclid's equation on how to find the greatest common denominator. I want you to look at the code and try to figure out how it works.

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

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]
Now a list works like a variable except it stores more than one value as you see above. The example I showed you has the list called "boop" with the asigned values of 10, 20, "Beeg", and 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]
print boop[0] #Prints the first value
print boop[2] #Prints the third value
Now I hope you understand how that works. When you want to call a certain value you just have to follow the list name by "[value number]"

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]
print l
l.append(10)
print l
l.remove(2)
print l
l.pop(1)
print l
l[1] = "hey"
print l
l.append(10)
l.append(25)
l.append("beeg")
l.append(l)
print l
print l[2]
print l[1:3]
If you ran the code you should see what happens. Let me explain each of the commands in detail

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

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 = {
"a":10,
"b":12,
"c":14
}
It's is used by first giving the database name (Like a variable or list) followed by the "=" sign and than the "{" bracket. Than the first value put in is the name (Can be string or number) followed by a colon ":", after the colon the value is put in. If more than one value for the database is going to be put in, follow it by a comma.

Now if you wanted to print out the first value you would just put:
print = dbase["a"]
Simple eh?

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.

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

Last edited by big_k105; Apr 27th, 2007 at 11:46 AM.
Beegie_B is offline   Reply With Quote
Old Nov 26th, 2004, 12:59 AM   #2
thechristelegacy
Expert Programmer
 
thechristelegacy's Avatar
 
Join Date: Jul 2004
Location: Somerset, Pa
Posts: 708
Rep Power: 5 thechristelegacy is on a distinguished road
Send a message via AIM to thechristelegacy Send a message via MSN to thechristelegacy
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

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 it
x = len(list) # assigns the function len to x
print x # prints out how many objects are in list, which is 4

I'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!"
c = len(x)
print c
would result in the interger 13 being printed.

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 reading
x = file.read() #assign files contents to x
file.close() #close the file
len(x) #count characters in file
and that will automaticly print out the contents, where as if I used IDLE, I would have to go in, save it first and then run it.

There 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
thechristelegacy is offline   Reply With Quote
Old Nov 26th, 2004, 10:07 AM   #3
Ooble
I eat cake for breakfast.
 
Ooble's Avatar
 
Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9 Ooble is on a distinguished road
Haven't read all of it, but from what I've seen, it's a bloody good tut.
__________________
Me :: You :: Them
Ooble is offline   Reply With Quote
Old Nov 26th, 2004, 12:14 PM   #4
Beegie_B
Programmer
 
Join Date: Nov 2004
Location: Windsor, Ontario, Canada
Posts: 32
Rep Power: 0 Beegie_B is on a distinguished road
Send a message via ICQ to Beegie_B Send a message via MSN to Beegie_B
yah, thanks for the good revies

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
Beegie_B is offline   Reply With Quote
Old Nov 26th, 2004, 3:31 PM   #5
thechristelegacy
Expert Programmer
 
thechristelegacy's Avatar
 
Join Date: Jul 2004
Location: Somerset, Pa
Posts: 708
Rep Power: 5 thechristelegacy is on a distinguished road
Send a message via AIM to thechristelegacy Send a message via MSN to thechristelegacy
yeah, I'll write the one on file IO, prob won't have much time until christmas break though
thechristelegacy is offline   Reply With Quote
Old Nov 26th, 2004, 9:10 PM   #6
Beegie_B
Programmer
 
Join Date: Nov 2004
Location: Windsor, Ontario, Canada
Posts: 32
Rep Power: 0 Beegie_B is on a distinguished road
Send a message via ICQ to Beegie_B Send a message via MSN to Beegie_B
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
Beegie_B is offline   Reply With Quote
Old Nov 26th, 2004, 9:57 PM   #7
thechristelegacy
Expert Programmer
 
thechristelegacy's Avatar
 
Join Date: Jul 2004
Location: Somerset, Pa
Posts: 708
Rep Power: 5 thechristelegacy is on a distinguished road
Send a message via AIM to thechristelegacy Send a message via MSN to thechristelegacy
We could make a nice little PDF or something
thechristelegacy is offline   Reply With Quote
Old Nov 28th, 2004, 11:55 AM   #8
Infinite Recursion
Programming Guru
 
Infinite Recursion's Avatar
 
Join Date: Jul 2004
Location: United States
Posts: 3,467
Rep Power: 8 Infinite Recursion is on a distinguished road
Send a message via MSN to Infinite Recursion Send a message via Yahoo to Infinite Recursion
good information guys... i need to brush up on my python a good bit, eventually.
__________________
http://jasonpowers.net

"There are a thousand hacking at the branches of evil to one who is striking at the root."
Infinite Recursion is offline   Reply With Quote
Old Nov 28th, 2004, 12:15 PM   #9
Overmind
Professional Programmer
 
Overmind's Avatar
 
Join Date: Jun 2004
Location: South Africa, Johannesburg
Posts: 301
Rep Power: 5 Overmind is on a distinguished road
I have finaly decided to start python
__________________
[SIGPIC][/SIGPIC]
Overmind is offline   Reply With Quote
Old Nov 28th, 2004, 1:13 PM   #10
Ooble
I eat cake for breakfast.
 
Ooble's Avatar
 
Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9 Ooble is on a distinguished road
Good man.
__________________
Me :: You :: Them
Ooble is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 3:11 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC