📄 python for newbies.htm
字号:
Finally, an example: <PRE>>>> f.readlines() #Our imaginary file; create it if you want
['This is the first line\012', 'This is the second line\012', "Hmm I'm running out
of creative things to say\012", 'Alright, this is the last line']
>>> f.seek(0) #You need this to go back to the beginning of the file; see below
>>> f.readline()
'This is the first line\012'
</PRE>Just in case you're wondering, the \012 at the end of every line is just a
newline. When reading files, Python replaces simple \ characters like \n with
their hex (ASCII) code. If you didn't get that, just remember that \012's are
really \n's. There are three (maybe four) more important methods of files.
First, read and seek. read just reads the entire file into a string, or a
maximum number of bytes if you specify it. seek needs one argument, which is the
offset in the file to go to, or seek. Huh? Well, Python reads files by putting a
little pointer in one and moving it along. When you read from a file, the little
pointer moves along to the end of the part you read. If you read again, it'll
start from where the pointer left off. seek will tell the pointer to go back (or
forward) to a specified point in the file. Here's another example, using the
same imaginary file as above: <PRE>>>> f.seek(12) #Offsets start at 0, therefore 12 is 'f'
>>> f.read(10)
'first line'
>>> f.seek(0)
>>> f.read() #Whole file. You probably shouldn't do this with big files.
"This is the first line\012This is the second line\012Hmm I'm running out
of creative things to say\012Alright, this is the last line"
</PRE>Then, finally, there is the write function, which (surprise!) writes to
your file. Just put in the parentheses the string you want to write. Be sure you
have a file opened in mode w, r+, or a, though! Also, if you want to create a
new file you must use the mode w or a, not r+. The last method is close, which
closes the file and frees up any memory it's been using. It's always good
programming practice to close any files when you're done with them or before you
leave. One last example for this section, then we move on: <PRE>>>> f = open( "mynewfile.txt", "w" )
>>> f.write( "This is some text" )
>>> f.close()
>>> f.read() #Oops! Can't read a closed file (or a write-only file for that matter)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
>>> f = open( "mynewfile.txt" )
>>> f.read()
'This is some text'
</PRE>
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H2 align=center><A name=mod>Modules</A></H2>
<H3 align=center><A name=mod1>Overview and Importing</A></H3>
<P>Before we talk about Python's wide variety of builtin modules, let's go over
what a module is first and how to get to them. A module is a script (or compiled
library) that can be loaded into the interpreter environment separately from the
core language of Python. Modules are accessed with the import statement, which
can be used in a number of ways: <PRE>>>> import sys #For these examples we're using the builtin sys module
>>> sys.argv #Access names from the modules like you would an object
['']
>>> from sys import argv #Another way to call it
>>> argv
['']
>>> from sys import * #Get everything in the sys module
>>> stdout
<open file '<stdout>', mode 'w' at 0x80d34b0>
</PRE>Confusing? Not really. Let's go through it. The first line imports the
module sys (one of the <A
href="#builtin">builtin
modules</A>). Notice on the next line that we needed to call a member of sys,
argv (the arguments passed to the interpreter), with a . like we did for
objects. This is using the so-called sys namespace, i.e. all sys members are
accessed using, obviously, the name 'sys'. Alternatively, if we put 'from
<module> import <members>', we use the global namespace. Then you
can access the method's members just like any other sort of local variables or
base functions. If you want to use the whole module in the global namespace,
just do a 'from <module> import *'. Not too hard, eh?
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=builtin>Builtin Modules</A></H3>
<P>Python, being the versatile language it is, has a large selection of modules
built into the default distribution. And I do mean large: at my count, there are
196 modules available in Python 2.0 (including obsolete and OS-specific ones).
When I say "builtin," this doesn't mean you don't have to import them, just that
they should be included in Python installation. So, I'll list a choice 5 or so
here, with basic descriptions of what they do and only a few of their members.
</P>
<UL>
<LI><B><FONT size=+1>sys</FONT></B> - Basic system/program functions
<UL>
<LI><B>argv</B> - List of commands passed to the interpreter
<LI><B>stdout, stdin, stderr</B> - Basic standard output, standard input,
and standard error. These can be accessed like normal files.
<LI><B>exit</B> - Exits the program gracefully, accepting a value as the
exit code (basically 0=good exit, non-0=error)
<LI><B>path</B> - The paths Python looks in to find modules to import
</LI></UL>
<LI><B><FONT size=+1>math</FONT></B> - Mathematical functions and constants. I
won't list them all here, but math contains many functions like sin, acos,
tanh, log, etc. Here are the constants:
<UL>
<LI><B>pi</B> - The mathematical constant π. The ratio of a circle's
diameter to its circumference, approximately 3.1415926535897931
<LI><B>e</B> - The base of the natural logarithm (ln). Get it with the sum
of 1/k! for all numbers k 0->infinity. Oddly enough, factorials (and
infinity) are not in the math module. </LI></UL>
<LI><B><FONT size=+1>string</FONT></B> - Functions for more manipulations of
strings
<UL>
<LI><B>printable</B> - A string of all so-called printable characters. Also
available are digits, letters (uppercase and lowercase), whitespace, and
punctuation.
<LI><B>atoi, atof, atol</B> - Convert strings to int, float, and long,
respectively. In Python 2.0 you should use builtins functions int, float,
and long.
<LI><B>find</B> - Find the lowest index where the second string (argument)
appears in the first.
<LI><B>count</B> - Count the number of times the second string appears in
the first.
<LI><B>split</B> - Split the string given in the first argument by
whitespace characters; return a list. If a second argument is given, the
string is split according to that instead of whitespace.
<LI><B>strip</B> - Strip leading and trailing whitespace from the given
string.
<LI><B>replace</B> - Replace all occurrences of the second string in the
first string with the third string. Err, look at it this way: replace( str,
"old", "new" ) replaces all occurrences of "old" in str with "new". </LI></UL>
<LI><B><FONT size=+1>random</FONT></B>
<UL>
<LI><B>seed</B> - Seeds the random number generator with three optional
arguments; defaults to the current time
<LI><B>random</B> - Returns the next random number as a floating-point
number between 0 and 1.
<LI><B>randint</B> - Returns a random number between two given integers.
<LI><B>uniform</B> - Same as randint, only with floating-point numbers.
<LI><B>choice</B> - Randomly chooses an element from the specified list or
tuple. </LI></UL>
<LI><B><FONT size=+1>time</FONT></B> - Functions for getting and manipulating
local and arbitrary times. See the Python library documentation for more
complete information.
<UL>
<LI><B>time</B> - No arguments, returns a long number that's your system's
current time, in seconds since...some time. Not really useful without some
sort of parser, except for seeding randoms.
<LI><B>localtime</B> - A parser. Given a time (like that returned by the
time function), it returns a tuple with the following information: year
(four-digit), month (1-12), day (1-31), hour (0-23), minute (0-59), second
(0-61 - 60 & 61 for leap seconds, never used), weekday (0-6, Monday is
0), day (1-366), daylight savings time (0 - no, 1 - yes, -1 - system
default). Useful :)
<LI><B>gmtime</B> - Same as above, except in Greenwich Mean Time, not your
system's local time.
<LI><B>asctime</B> - Given a tuple from localtime or gmtime, returns a
string in the format 'Thu Mar 22 18:24:35 2001'. </LI></UL>
<LI><B><FONT size=+1>re</FONT></B> - Regular expression (regexp) operators. I
won't cover them here, but I thought all you Perl fans out there might like to
know they exist in Python. There are some definite peculiarities about regexps
in Python, so read the docs...docs are your friends :). </LI></UL>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=yours>User-Defined Modules and Functions</A></H3>
<P>Of course, what use are all these modules if you can't use your own? Well, a
user-defined module is just a .py file in one of Python's module directories. To
import the module, it's run, and any functions, variables, classes, etc. are
imported in. You can specify what to import, just like for any other module.
Well, then, that's all well and good, but a big part of these modules is
functions. How to make your own functions, then? Ok. </P>
<P>Alright. So we want a function. Since I like math, we'll do a simple
logarithm to any base using the log function in the math module. Here we go, try
this: <PRE>>>> def logb( b, n ):
... from math import log
... a = log(n)/log(b)
... if a - int(a) == 0: #a is an int
... return int(a)
... else:
... return a
...
</PRE>How nice. Only a couple things should need explaining, unless you haven't
taken high school algebra (hey no offense...I'm just a freshman :). This 'def'
thing? Well, it's just the name of the function and the arguments it takes. I
should hope you have a good idea of what arguments are now. Then there's return.
It's...uh...what the function returns :). Execution stops after a return
statemnt, just like a break statement. Except it returns something. Ok. Well,
I've kinda run out of things to say...so here's an example module, just for
practice. Hey, this is a tutorial, isn't it? Let's go, put this in moremath.py: <PRE>#!/usr/bin/python
def logb( b, n ): #Definition
from math import log #Need this!
a = log(n)/log(b) #Change of base formula
if a - int(a) == 0: #a is an int
return int(a) #Get rid of that decimal :)
else: #a is a float
return a #Just return it
#Ye Olde Golden Ratio <www.verbose.net>
phi = 1.6180339887498948
</PRE>And now in the interpreter: <PRE>>>> import moremath
>>> moremath.phi #Floating point numbers aren't that accurate, you may notice
1.6180339887499999
>>> from moremath import logb
>>> logb(2,1024)
10
</PRE>Wow! A module! Just like other modules! But you did it myself! Or I did it
yourself...or...wait...you did it yourself. If you look in the directory where
you put moremath.py now, you'll now find a moremath.pyc file. This is a
'compiled' file, which is not really compiled (it's bytecode - kinda like a Java
.class file), but has less memory overhead than a .py file. As far as I know
.pyc files are not portable, though, so if you're just using this module for
yourself you can use the .pyc but if you want to distribute it, I recommend you
keep the .py file. In any case, it's certainly easier to edit your source if you
still have a .py file. Any questions :)?
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H2 align=center><A name=close>In Closing</A></H2>
<H3 align=center><A name=perl>Why Python is Better than Perl</A></H3>
<P>I admit it: maybe Python isn't better than Perl. It's different, to say the
least. For many things it <I>is</I> better. And it's got definite advantages,
and that's what I thought I'd just review, or look at, or list, or whatever.
Here goes. </P>
<UL>
<LI>Intuitiveness. Instead of all that nasty, obfuscated code, Python has
syntax and blocking that resembles, somewhat, normal (English) speech and
indenting.
<LI>High-levelness. List slicing, tuple packing, etc. allow for high-level
manipulation of data without all that mucking about with
pointers...wait...that's C...and efficient though it may be, it sometimes even
confuses the 黚erhacker in me. But it's still easier in Python than Perl.
<LI>More integrated object-oriented (OO) support. OO in Perl involves working
with hashes as classes and weird stuff like that. Bottom line, Python was
designed from the start to be OO...even though I didn't talk about classes too
much. Sorry.
<LI>Better C integration. Well, this is opinionated here, but I think
embedding Python in C is easier than Perl...what can I say?
<LI>Interactive mode. No need to put scripts in separate files. You know what
I'm saying.
<LI>Wider variety of data structures. Perl has arrays, hashes, and scalars.
Python has scalars (int, float, long), lists, dictionaries (which I didn't
talk about; they're like hashes or associative arrays), tuples. And it's
extensible and evolving, according to the docs.
<LI>range function. People complain about the lack of a generic for loop, like
Perl has. range really makes the for loop...without having a whole different
type of loop. Less overhead. And you can use range for other things, too.
<LI>Monty Python. 'Nuff said. </LI></UL>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=ref>References</A></H3>
<UL>
<LI><A href="http://www.python.org/">Python.org</A>. A must-see.
<LI><A href="http://www.python.org/doc/current/">Current Python docs</A>.
Gotta read them.
<LI><A href="http://www.zope.org/">Zope</A>. Great webserver written in
Python.
<LI><A href="http://www.programmershaven.com/zone23/links/link281.htm">Python
section at ProgrammersHaven</A>. More good links.
<LI><A href="http://blacksun.box.sk/">Black Sun Research Facility</A>. Great
site for networking, programming, cracking, OSes, etc. This tutorial should be
published there :)
<LI><A href="http://www.pythonline.com/">Pythonline</A>. Monty Python, may or
may not be the official site, I'm not sure. </LI></UL>
<P>Any comments, questions, glowing praise, rants, hatemail, feel free to <A
href="mailto:skinite@home.com">mail me</A> or leave a message for me at <A
href="http://dvd.box.sk/wb/?did=blacksun">BSRF's message board</A>. I'm a
member, I check it regularly. Hatemail is ok, but death threats are discouraged.
</P>
<P>Well, we've come to the end, at long last. I hope you've learned something,
and you aren't too high on the adrenaline rush of coding. I'm not good at these
ending things, so I think I'll just trail off right...about...now... </P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P></FONT></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -