|
||||
|
« Naming Conventions | A dedicated server for GIDNetwork sites » |
Beginning Python Tutorial (Part 8)
by: crystalattice - Nov 03, 2005
Basic StatementsNow that we know how Python uses it's fundamental data types, let's talk about how to use them. Python is nominally a procedure-based language but as we'll see later, it also functions as an object-oriented language. As a matter of fact, it's similar to C++ in this aspect; you can use it as either a procedural or OO language or combine them as necessary. The following is a listing of Python statements, borrowed from O'Reilly's Learning Python. Generic Code Example: Statement Role Examples Assignment Creating references curly, moe, larry = 'good', 'bad', 'ugly' Calls Running functions stdout.write("spam, ham, toast\n") Print Printing objects print 'The Killer', joke If/elif/else Selecting actions if "python" in text: print text For/else Sequence iteration for X in mylist: print X While/else General loops while 1: print 'hello' Pass Empty placeholder while 1: pass Break, Continue Loop jumps while 1: if not line: break Try/except/finally Catching exceptions try: action() except: print 'action error' Raise Triggering exception raise endSearch, location Import, From Module access import sys; from sys import stdin Def, Return Building functions def f(a, b, c=1, *d): return a+b+c+d[0] Class Building objects class subclass: staticData = [] Global Namespaces def function(): global X, Y; X = 'new' Del Deleting things del data[k]; del data [i:j]; del obj.attr Exec Running code strings yexec "import" + modName in gdict, ldict Assert Debugging checks assert X > Y AssignmentAssignment is similar to other languages, so I won't cover it in depth. Suffice it to say, assignment is basically putting the target name on the left of an equals sign and the object you're assigning it from, on the right. There's only a few things you need to remember: Assignment creates object references. Names are created when first assigned Assignment can be created either the standard way spam = "SPAM", via multiple target spam = ham = "Yummy", with a tuple spam, ham = "lunch", "dinner", or with a list [spam, ham] = ["yum", "YUM"]. The final thing to mention about assignment is that a name can be reassigned to different objects. Since a name is just a reference to an object and doesn't have to be declared, you can change it's "value" to anything. For example: Generic Code Example: >>>x = 0 #x is linked to an integer >>>x = "spam" #now it's a string >>>x = [1, 2, 3] #now it's a list ExpressionsPython expressions can be used as statements but since the result won't be saved, expressions are usually used to call functions/methods and for printing values at the interactive prompt. Here's the typical format:
PrintingPrinting in Python is extremely simple. Using print writes the output to the C stdout stream and normally goes to the console unless you redirect it to another file. Printing, by default, adds a space between items separated by commas and adds a linefeed at the end of the output stream. To suppress the linefeed, just add a comma at the end of the print statement: Generic Code Example: print lumberjack, spam, eggs, To suppress the space between elements, just concatenate them when printing: Generic Code Example: print "a" + "b" if TestsThe if statement works the same as other languages. The only difference is the else/if as shown below: Generic Code Example: if <test1>: # if test <statements1> # associated block elif <test2>: # optional elif's <statements2> else: # optional else <statements3> Unlike C, Pascal, and other languages, there isn't a switch or case statement in Python. You can get the same functionality by using if/elif tests, searching lists, or indexing dictionaries. Since lists and dictionaries are built at runtime, they can be more flexible. Here's an equivalent switch statement using a dictionary: Generic Code Example: >>> choice = 'ham' >>> print {'spam': 1.25, # a dictionary-based 'switch' ... 'ham': 1.99, #use has_key() test for default case ... 'eggs': 0.99, ... 'bacon': 1.10}[choice] 1.99 while LoopsThe Python while statement is, again, similar to other languages. Here's the main format: Generic Code Example: while <test>: # loop test <statements1> # loop body else: # optional else <statements2> # run if didn't exit loop with break break and continue work the exact same as in C. The equivalent of C's empty statement (a semicolon) is the pass statement, and Python includes an else statement for use with breaks. Here's a full-blown while example loop: Generic Code Example: while <test>: <statements> if <test>: break # exit loop now, skip else if <test>: continue # go to top of loop now else: <statements> # if we didn't hit a 'break' for LoopsThe for loop is a sequence iterator for Python. It will work on nearly anything: strings, lists, tuples, etc. I've talked about for loops before so I won't get into much more detail about them. The main format is below: Generic Code Example: for <target> in <object>: # assign object items to target <statements> if <test>: break # exit loop now, skip else if <test>: continue # go to top of loop now else: <statements> # if we didn't hit a 'break' From Learning Python:
Related to for loops are range and counter loops. The range function auto-builds a list of integers for you. Typically it's used to create indexes for a for statement but you can use it anywhere. Generic Code Example: >>> range(5), range(2, 5), range(0, 10, 2) ([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8]) As you can see, a single argument gives you a list of integers, starting from 0 and ending at one less than the argument. Two arguments gives a starting number and the max value while three arguments adds a stepping value, i.e. how many numbers to skip between each value. Well, that's it for this installment. As you can see, Python is a pretty simple language that "automates" many of the features you'd have to code by hand in other languages. Next time I'll discuss using procedural-style functions in Python followed by a more in-depth look at modules.
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Naming Conventions | A dedicated server for GIDNetwork sites » |