Basic Python Tutorial for Newbies
Page 1 of 2 12 LastLast
Results 1 to 10 of 12

Thread: Basic Python Tutorial for Newbies

  1. #1
    Banned
    Join Date
    Jun 2002
    Posts
    40

    Basic Python Tutorial for Newbies

    This tutorial is original work by [pHA]XeNoCiDe(Daedalus)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    The Basic Newbie Python Tutorial
    Python is an easy programming language for people who want to learn how to make scripts/programs and have fun with them. In this tutorial, I will show you the basic commands of Python and how to make your own programs.
    ---------------------------------------------------------------------------------------------
    Python is availible at www.python.org
    Python can run on *nix, Windows, and Macintosh systems.
    ------------------------
    Printing
    Printing is a command used greatley in Python. It does what it says, it prints the desired text:
    >>>Print "Hello World"
    Hello World
    >>>
    Yes, I know it is dull, but you gotta know all of the commands
    -------------------------
    If you are wondering what >>> is, it is Python's way of showing you that it is ready to take your commands. There are ways it will prompt you >>> is one and ... is another.
    -------------------------
    Expressions
    Expressions, Python can be used like a calculator by using certain expressions.
    Python has six basic expressions:
    ** = Exponentiation
    * = Multiplication
    / = Division
    % = Remainder
    + = Addition
    - = Subtraction
    Try this program:
    Print "3 + 3 is", 3+3
    It should print:
    3 + 3 is 6
    Well, if you got the hang of that, experiment with the different expressions.
    Oh, and Python follows the Standard Order of Operations (just like in 7th grade!)
    ------------------------
    Comments
    Comments are notes to you and people using your program that Python and the computer ignore.
    So if you type something that you wouldn't recognize off the bat, then add a comment by typing # and then your text so:
    >>># The Pythagorean Theroem
    ...Print "A2 + B2 = C2"
    And thus you have created a comment about The Pythagorean Theroem (sorry about the 2, I couldn't figure out how to make the squared symbol)(Bad Example, lol)
    ------------------------
    Variables and Input
    Variables store data. Here is an example of the usage of variables:
    >>>a = 1
    ...print a
    >>>a = 2
    ...print a
    >>>a = 3
    ...print a
    and so on and so forth.
    Try this for input (I found this one on the internet):
    (from internet START)
    ^v^v^v^v^v^v^
    num = input("Type in a Number: ")
    str = raw_input("Type in a String: ")
    print "num =", num
    print "num is a ",type(num)
    print "num * 2 =",num*2
    print "str =", str
    print "str is a ",type(str)
    print "str * 2 =",str*2

    Notice that num was gotten with input while str was gotten with raw_input. raw_input returns a string while input returns a number. When you want the user to type in a number use input but if you want the user to type in a string use raw_input.

    The second half of the program uses type which tells what a variable is. Numbers are of type int or float (which are short for 'integer' and 'floating point' respectively). Strings are of type string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiples a number by a integer the expected thing happens. However when a string is multiplied by a integer the string has that many copies of it added i.e. str * 2 = HelloHello.
    (from internet END)
    ^v^v^v^v^v^v^v^
    That was an example I found of the internet.
    -------------------------
    Loops
    Loops are well.... Loops. They loop information.
    Here is an example:
    a = 1
    while a < 20:
    a = a + 1
    Print a
    It should show:
    2
    3
    4
    5
    ..... And so on.
    ------------------------
    Decision Statements
    Decision Statements basically explain themselves, the following are decision statements:
    If
    Else
    Elif (else and if)
    < (Less than)
    > (Greater than)
    <= (Less than or equal to)
    => (Greater than or equal to)
    == (Equal)
    != (Not equal)
    <> (Either way to say not equal)
    Try this program I looked at:
    a = 0
    while a < 10:
    a = a + 1
    if a > 5:
    print a," > ",5
    elif a <= 7:
    print a," <= ",7
    else:
    print "Neither test was true"
    ------------------------
    Defining Functions
    a = 23
    b = -23

    if a < 0:
    a = -a

    if b < 0:
    b = -b

    if a == b:
    print "The absolute values of", a,"and",b,"are equal"
    else:
    print "The absolute values of a and b are different"

    with the output being:
    The absolute values of 23 and 23 are equal

    The program seems a little repetitive. (Programmers hate to repeat things (That's what computers are for aren't they?)) Fortunately Python allows you to create functions to remove duplication. Here's the rewritten example:
    a = 23
    b = -23

    def my_abs(num):
    if num < 0:
    num = -num
    return num

    if my_abs(a) == my_abs(b):
    print "The absolute values of", a,"and",b,"are equal"
    else:
    print "The absolute values of a and b are different"

    with the output being:
    The absolute values of 23 and -23 are equal

    The key feature of this program is the def statement. def (short for define) starts a function definition. def is followed by the name of the function my_abs. Next comes a ( followed by the parameter num (num is passed from the program from wherever it is called to the function). The statements after the : are executed when the function is used. The statements continue until either the indented statements end or a return is encountered. The return statement returns a value back to the place where the function was called.
    Notice how the values of a and b are not changed. Functions of course can be used to repeat tasks that don't return values. Here's some examples:

    def hello():
    print "Hello"

    def area(width,height):
    return width*height

    def print_welcome(name):
    print "Welcome",name

    hello()
    hello()

    print_welcome("Fred")
    w = 4
    h = 5
    print "width =",w,"height =",h,"area =",area(w,h)

    with output being:
    Hello
    Hello
    Welcome Fred
    width = 4 height = 5 area = 20

    That example just shows some more stuff that you can do with functions. Notice that you can use no arguments or two or more. Notice also how a return is optional.
    Functions can be used to eliminate repeat code.


    Variables in functions
    Of course, when eliminiating repeated code, you often have variables in the repeated code. These are dealt with in a special way in Python. Up till now, all variables we have see are global variables. Functions have a special type of variable called local variables. These variables only exist while the function is running. When a local variable has the same name as another variable such as a global variable, the local variable hides the other variable. Sound confusing? Well, hopefully this next example (which is a bit contrived) will clear things up.


    a_var = 10
    b_var = 15
    e_var = 25

    def a_func(a_var):
    print "in a_func a_var = ",a_var
    b_var = 100 + a_var
    d_var = 2*a_var
    print "in a_func b_var = ",b_var
    print "in a_func d_var = ",d_var
    print "in a_func e_var = ",e_var
    return b_var + 10

    c_var = a_func(b_var)

    print "a_var = ",a_var
    print "b_var = ",b_var
    print "c_var = ",c_var
    print "d_var = ",d_var

    The output is:

    in a_func a_var = 15
    in a_func b_var = 115
    in a_func d_var = 30
    in a_func e_var = 25
    a_var = 10
    b_var = 15
    c_var = 125
    d_var =
    Traceback (innermost last):
    File "separate.py", line 20, in ?
    print "d_var = ",d_var
    NameError: d_var

    In this example the variables a_var, b_var, and d_var are all local variables when they are inside the function a_func. After the statement return b_var + 10 is run, they all cease to exist. The variable a_var is automatically a local variable since it is a parameter name. The variables b_var and d_var are local variables since they appear on the left of an equals sign in the function in the statements b_var = 100 + a_var and d_var = 2*a_var .

    As you can see, once the function finishes running, the local variables a_var and b_var that had hid the global variables of the same name are gone. Then the statement print "a_var = ",a_var prints the value 10 rather than the value 15 since the local variable that hid the global variable is gone.

    Another thing to notice is the NameError that happens at the end. This appears since the variable d_var no longer exists since a_func finished.

    One last thing to notice is that the value of e_var is kept inside a_func since it is not a parameter and it never appears on the left of an equals sign inside of the function a_func.

    Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.


    Function walkthrough
    Now we will do a walk through for the following program:

    def mult(a,b):
    if b == 0:
    return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value

    print "3*2 = ",mult(3,2)

    Basically this program creates a positive integer multiplication function (that is far slower than the built in multiplication function) and then demonstrates this function with a use of the function.

    Question: What is the first thing the program does?

    Answer: The first thing done is the function mult is defined with the lines:

    def mult(a,b):
    if b == 0:
    return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value

    This creates a function that takes two parameters and returns a value when it is done. Later this function can be run.
    Question: What happens next?

    Answer: The next line after the function, print "3*2 = ",mult(3,2) is run.

    Question: And what does this do?

    Answer: It prints 3*2 = and the return value of mult(3,2)

    Question: And what does mult(3,2) return?

    Answer: We need to do a walkthrough of the mult function to find out.

    Question: What happens next?

    Answer: The variable a gets the value 3 assigned to it and the variable b gets the value 2 assigned to it.

    Question: And then?

    Answer: The line if b == 0: is run. Since b has the value 2 this is false so the line return 0 is skipped.

    Question: And what then?

    Answer: The line rest = mult(a,b - 1) is run. This line sets the local variable rest to the value of mult(a,b - 1). The value of a is 3 and the value of b is 2 so the function call is mult(3,1)

    Question: So what is the value of mult(3,1) ?

    Answer: We will need to run the function mult with the parameters 3 and 1.

    Question: So what happens next?

    Answer: The local variables in the new run of the function are set so that a has the value 3 and b has the value 1. Since these are local values these do not affect the previous values of a and b.

    Question: And then?

    Answer: Since b has the value 1 the if statement is false, so the next line becomes rest = mult(a,b - 1).

    Question: What does this line do?

    Answer: This line will assign the value of mult(3,0) to rest.

    Question: So what is that value?

    Answer: We will have to run the function one more time to find that out. This time a has the value 3 and b has the value 0.

    Question: So what happens next?

    Answer: The first line in the function to run is if b == 0: . b has the value 0 so the next line to run is return 0 .

    Question: And what does the line return 0 do?

    Answer: This line returns the value 0 out of the function.

    Question: So?

    Answer: So now we know that mult(3,0) has the value 0. Now that we know that we know what the line rest = mult(a,b - 1) did now that we have run the function mult with the parameters 3 and 0. We have finished running mult(3,0) and are now back to running mult(3,1). The variable rest get assigned the value 0.

    Question: What line is run next?

    Answer: The line value = a + rest is run next. In this run of the function, a=3 and rest=0 so now value=3.

    Question: What happens next?

    Answer: The line return value is run. This returns 3 from the function. This also exits from the run of the function mult(3,1). After return is called, we go back to running mult(3,2).

    Question: Where where we in mult(3,2)?

    Question: We had the variables a=3 and b=2 and were examining the line rest = mult(a,b - 1) .

    Question: So what happens now?

    Answer: The variable rest get 3 assigned to it. The next line value = a + rest sets value to or 6.

    Question: So now what happens?

    Answer: The next line runs, this returns 6 from the function. We are now back to running the line print "3*2 = ",mult(3,2) which can now printout the 6.

    These last two sections were recently written. If you have any comments, found any errors or think I need more/clearer explanations please email. Thanks.

    Some Programs to screw around with:
    factorial.py

    #defines a function that calculates the factorial

    def factorial(n):
    if n <= 1:
    return 1
    return n*factorial(n-1)

    print "2! = ",factorial(2)
    print "3! = ",factorial(3)
    print "4! = ",factorial(4)
    print "5! = ",factorial(5)

    Output:

    2! = 2
    3! = 6
    4! = 24
    5! = 120

    temperature2.py

    #converts temperature to fahrenheit or celsius

    def print_options():
    print "Options:"
    print " 'p' print options"
    print " 'c' convert from celsius"
    print " 'f' convert from fahrenheit"
    print " 'q' quit the program"

    def celsius_to_fahrenheit(c_temp):
    return 9.0/5.0*c_temp+32

    def fahrenheit_to_celsius(f_temp):
    return (f_temp - 32.0)*5.0/9.0

    choice = "p"
    while choice != "q":
    if choice == "c":
    temp = input("Celsius temperature:")
    print "Fahrenheit:",celsius_to_fahrenheit(temp)
    elif choice == "f":
    temp = input("Fahrenheit temperature:")
    print "Celsius:",fahrenheit_to_celsius(temp)
    elif choice != "q":
    print_options()
    choice = raw_input("option:")

    Sample Run:

    > python temperature2.py
    Options:
    'p' print options
    'c' convert from celsius
    'f' convert from fahrenheit
    'q' quit the program
    option:c
    Celsius temperature:30
    Fahrenheit: 86.0
    option:f
    Fahrenheit temperature:60
    Celsius: 15.5555555556
    option:q

    area2.py

    #By Amos Satterlee
    print
    def hello():
    print 'Hello!'

    def area(width,height):
    return width*height

    def print_welcome(name):
    print 'Welcome,',name

    name = raw_input('Your Name: ')
    hello(),
    print_welcome(name)
    print
    print 'To find the area of a rectangle,'
    print 'Enter the width and height below.'
    print
    w = input('Width: ')
    while w <= 0:
    print 'Must be a positive number'
    w = input('Width: ')
    h = input('Height: ')
    while h <= 0:
    print 'Must be a positive number'
    h = input('Height: ')
    print 'Width =',w,' Height =',h,' so Area =',area(w,h)

    Sample Run:

    Your Name: Daedalus
    Hello!
    Welcome, Daedalus

    To find the area of a rectangle,
    Enter the width and height below.

    Width: -4
    Must be a positive number
    Width: 4
    Height: 3
    Width = 4 Height = 3 so Area = 12
    (The above Defining Functions is pasted from a website)
    ----------------------------
    Lists
    Lists are lists, they show information how you define it.
    Here is an example I found:
    which_one = input("What month (1-12)? ")
    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\
    'August', 'September', 'October', 'November', 'December']
    if 1 <= which_one <= 12:
    print "The month is",months[which_one - 1]

    The statement if 1 <= which_one <= 12: will only be true if which_one is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra, heh 8th grade).
    ------------------------
    Range
    If you have ever used a Texas Instuments Graphing calcualtor then some of this may make sense when you made programs, Range does what it means, it shows a range of numbers.
    Try:
    Range (10,20)
    And you should see:
    [10,11,12,13,14,15,16,17,18,19,]
    Try to incorporate the List command into one of your Range programs.
    -------------------------
    Well, these are some commands and programs that will make your programming experience with Python more fun and easier.
    If you want more help check out:The Python Tutorial by Guido van Rossum.
    Thank you very much for reading this, and have fun programming with Python.
    P.S.: It took me one hour and thirty minutes to type this.
    Share on Google+

  2. #2
    er0k
    Guest
    great tut daedalus w00t w00t!
    Share on Google+

  3. #3
    Banned
    Join Date
    Jun 2002
    Posts
    458
    Xenocide how is that possible? An hour ago I saw you post that basic firewall linux script, then probably because you saw me and streamer had posted something similar you deleted it. So then how did you type this in an hour and thirty minutes?
    Share on Google+

  4. #4
    Banned
    Join Date
    Jun 2002
    Posts
    40
    because i looked at my clock...it said 12:30 when i started and it is now 2:00 sir, i felt stupid for not searching before i made the firewall tutorial, please except my apologies for that.
    Share on Google+

  5. #5
    Senior Member
    Join Date
    Feb 2002
    Posts
    253
    Great work !!!!

    Great work !!!!
    Share on Google+

  6. #6
    Senior Member
    Join Date
    Apr 2002
    Posts
    1,049
    nice tutorial i was writing a tutorial on python 2 but u r was better good work man
    By the sacred **** of the sacred psychedelic tibetan yeti ....We\'ll smoke the chinese out
    The 20th century pharoes have the slaves demanding work
    http://muaythaiscotland.com/
    Share on Google+

  7. #7
    GreekGoddess
    Guest
    Great job...this is my first real glance at Python...haven't worked with it yet...Gonna play with it a little and see what I can do with it. Thanks!
    Share on Google+

  8. #8
    Senior Member
    Join Date
    Jun 2002
    Posts
    104
    I've just started learning Python, and this is really really helpful! I was using a progressive step-by-step tutorial and I never get on particularly well with them if they don't explain WHY you're making the steps, and don't tell you exactly what you've got at your disposal. This is great especially because of the list of definitions, that's just what I was after, gives you a lot more control and freedom to muck about - always the best way to learn! Thanks a lot!

    XXX
    [gloworange]The Owls Are Not What They Seem[/gloworange]

    Share on Google+

  9. #9
    Banned
    Join Date
    Oct 2001
    Posts
    55
    hey, [pHA]XeNoCiDe
    khakisrule did't take offence for that, and any way y should he?
    Share on Google+

  10. #10
    AntiOnline Senior Member souleman's Avatar
    Join Date
    Oct 2001
    Location
    Flint, MI
    Posts
    2,884
    Function walkthrough
    Now we will do a walk through for the following program:

    def mult(a,b):
    if b == 0:
    return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value

    print "3*2 = ",mult(3,2)

    Basically this program creates a positive integer multiplication function (that is far slower than the built in multiplication function) and then demonstrates this function with a use of the function.

    Question: What is the first thing the program does?
    Taken from http://honors.montana.edu/~jjc/easyt...tut/node9.html

    You almost had me for a minute. You changed just enough from the first few pages of the jjc tutorial to make it look like you might have written it yourself. But then you just got to lazy on the last pages. You remembered to change the name to Daedalus instead of Josh in the area2.py program, but leaving the #By Amos Satterlee made me wonder.... Its good to give creadit to programs you didn't write, but its bad to take credit for tutorials you didn't write.
    \"Ignorance is bliss....
    but only for your enemy\"
    -- souleman
    Share on Google+

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

 Security News

     Patches

       Security Trends

         How-To

           Buying Guides