📄 python for newbies.htm
字号:
like it. The next line has a cryptic-looking statement elif. First notice it's
not indented; it's not in the same code block. elif is not life backwards, it's
short for else if. If the first condition isn't true, it checks the next one.
Next block, there we go. Finally comes else: the fallback statement, in case
none of the above conditions (there can be as many as you want, which serves as
a replacement for C-style switch statements) are met.
<P></P>
<P>There it is, if in a nutshell. </P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=for>For Ever...</A></H3>
<P>Wow, don't I come up with the worst section titles? Anyway, on to the next
standard loop: the for loop. Python's for loop is probably a bit different from
those you've seen, unless you've seen perl's or PHP's foreach loop. for loops in
Python run through each item in a string or list and assign it to a particular,
specified variable. The syntax is intuitive and might even resemble human
speech. Watch and learn: <PRE>>>> for letter in "Brian": #Blocks are treated the same way as above
... print letter
... #This just prints each letter in "Brian" on its own line
...
B
r
i
a
n
</PRE>Very simple. But you might say this odd for loop is lacking because it
doesn't go through, for example, the numbers from 1 to 10 and put them in i,
like in *other* languages. That is easily overcome with the ubiquitously useful
range() function. range() will return a list, perfect for running through with
for, of numbers in a specified range (now where do those Python creators come up
with those names?). You can specify one of a number of arguments, as follows: <PRE>>>> #This returns a list of 6 numbers, starting at 0
... range(6) #which means the argument you put there is not actually in the list.
[0, 1, 2, 3, 4, 5]
>>> #A list from 6 to 10-1, or 6-9.
... range(6,10) Remember 10 doesn't actually appear, just like above.
[6, 7, 8, 9]
>>> range(6,10,2) #Same as above, only increments by 2.
[6, 8]
>>> range(10,6,-1) #Negative increments work too. The last number, 6, still doesn't appear.
[10, 9, 8, 7]
</PRE>Those should have been pretty much self-explanatory. Another little trick,
if you want to iterate through the elements in a list by index number, is to use
the len() function (which returns the length of the list) together with the
range() function: <PRE>>>> l = ["I'm", "not", "dead"]
>>> for i in range(len(l)):
... print "Item", i, "of l is "+l[i]
...
Item 0 of l is I'm
Item 1 of l is not
Item 2 of l is dead
</PRE>Well, that about wraps it up for for loops. Remember: if you can't come to
grips with for really being a foreach, range() is your friend.
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=while>While We...and Others</A></H3>
<P>I'm not even going to <I>say</I> anything about this title. Moving on, then,
to the last of the ever-so-common loops: while. while performs its little block
of code forever and ever, or at least until some predefined condition is met. <PRE>>>> while name != "Dave"
... name = raw_input( "What's my name? " )
...
What's my name? David
What's my name? Monty
What's my name? Dave
>>>
</PRE>Notice how it obstinately refuses to let me go on until I give it what
it's looking for. Of course, while loops need not be dependent on user input.
This loop here will calculate every cube that's under 1000: <PRE>>>> c = 0
>>> while c**3 <= 1000:
... print `c`+"^3="+`c**3`
... c = c + 1
...
0^3=0
1^3=1
2^3=8
3^3=27
4^3=64
5^3=125
6^3=216
7^3=343
8^3=512
9^3=729
10^3=1000
</PRE>A few other features of loops bear mentioning: break, continue, and else.
break will completely break out of a loop, bypassing any statements (and else
clauses, as we shall see). continue will stop where it is in the loop and go on
with the next iteration. else clauses, which can be used on any loop (not just
if), specify code to execute after the loop is finished, e.g. in a for loop
there are no more items to iterate through. Look at this
slightly-modified-but-still-cheesy example: <PRE>>>> for i in range(3):
... name = raw_input( "What's my name? " )
... if name != "Dave":
... print "Wrong!"
... continue
... else:
... print "Damn straight!"
... break
... else:
... print "Too many guesses! You're wrong!"
...
What's my name? David
Wrong!
What's my name? David
Wrong!
What's my name? David
Wrong!
Too many guesses! You're wrong!
>>> #Try it again, but I won't type the code here again
What's my name? Dave
Damn straight!
</PRE>Well, so much for control structures...
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H2 align=center><A name=inter>Intermediate Python</A></H2>
<H3 align=center><A name=tuples>Tuples!</A></H3>
<P>Well, here we are, at the much-hyped tuple section. Tuples are another type
of variable that resemble lists but are more general and have a wider range of
features. They are usually put in parentheses (), but sometimes parentheses
aren't even necessary to assign them: <PRE>>>> t = (1, 2, 3) #Wow, our first tuple :)
>>> t
(1, 2, 3)
>>> t + 1, 2, 3 #Who needs parentheses? Well most of the time you do...
>>> t
(1, 2, 3)
>>> t[0] #Still use brackets to get indexes
1
>>> t = 1, #You need the trailing comma, or else t is just an int
(1)
</PRE>Great, you say, but what makes these "tuples" more special than any old
lists? Well, for one thing, tuples can be nested in one another: <PRE>>>> tu = tuple(range(1,4)) #Note use of tuple function
>>> ple = tuple(range(4,7))
>>> tuples = tu, ple
>>> tuples
((1, 2, 3), (4, 5, 6))
>>> print tuples[1][1] #Access it like this
5
</PRE>Nesting tuples together like this can provide a substitute for things like
two-dimensional arrays (arrays of arrays) in C without all that pesky pointing.
Also notice, just for convenience, the tuple() function. This just converts any
old list into any old tuple. Its opposite, the list() function, also exists.
There's another little nifty feature of tuples that bears talking about: packing
and unpacking. Packing a tuple is basically what we've seen above, putting two
or more variables in a tuple just with commas. Unpacking can also be useful. Try
to see how this works: <PRE>>>> n = tuple(range(1,6))
>>> a1, a2, a3, a4, a5 = n
>>> print a1, a2, a3, a4, a5
1 2 3 4 5
</PRE>In case you didn't quite understand that, what the second line did was
take each member of the tuple n and assign it to a different variable, a1
through a5. This unpacking, just so you know, also works with lists. Just put
the list of variables in list brackets []. Note how these two examples do the
same thing: <PRE>>>> l = range(1,4)
>>> [l1, l2, l3] = l
>>> t1, t2, t3 = tuple(l)
>>> print l1, l2, l3, "\n", t1, t2, t3
1 2 3
1 2 3
</PRE>When you're unpacking a bunch of tuples, just remember that the number of
variables in your list has to equal the length of the tuple. There is one more
interesting opportunity afforded by tuple packing and unpacking, namely multiple
assignment. It may seem like this has nothing whatsoever to do with tuples, but
look now, I'll explain later: <PRE>>>> a, b = 0, 1
>>> a
0
>>> b
1
</PRE>Look at that, a and b assigned different values in the same line! Very
useful, very simple. Now, since this is the <I>Intermediate</I> section, an
explanation (rather simple though) is in order. First look on the right: the
values 0 and 1 are packed into a "temporary" tuple. which I'll call t but I'm
not sure really has a name. Now on the left. a and b, since they are a
comma-separated sequence, are about to receive an unpacked tuple. This tuple is
t. Just like normal unpacking, the first element of t goes in a and the second
in b. Voila! There's your multiple assignment.
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=string>Strings and Slice Indexing</A></H3>
<P>Remember waaayyy back up <A
href="#slice">somewhere</A>
where I had a string indexed like a[1:]? Well, that's a simple example of slice
indexing. With slice indexing you can take more than just one element of a
string (or list or tuple, but it's usually more useful with strings), in fact
you can take a whole slice out of it (hence the name). Just put two numbers, the
starting and ending indices, inside your brackets. Observe: <PRE>>>> s = 'supercalifragalisticexpialidotious'
>>> s[0:5]
'super'
</PRE>Wait, that's not right! Element 5 of s is 'c', not 'r'! Well, I lied
before. The second number is one more than the highest index you want. (Remember
range()? It's just like that.) Another one of those things you'll just have to
deal with, I guess.
<P></P>
<P>Now, what about that example I gave earlier? There was no second index,
right? Precisely. There are of course default indexes for before and after the
:. Before the colon defaults to 0, after defaults to len(s), or the length of
the string: <PRE>>>> s = 'supercalifragalisticexpialidotious'
>>> s[:5]
'super'
>>> s[27:]
'dotious'
</PRE>You may think it inconvenient to have to count all the way to the 27th
letter of s in order to get dotious. Say you just wanted the last 7 letters.
Remember I said negative index numbers work too? Well they do here, too, with
slicing. Just make sure the beginning index comes before the ending (you'll see
what I mean): <PRE>>>> s = 'supercalifragalisticexpialidotious'
>>> s[-7:]
'dotious'
>>> s[int(-.5*len(s)):len(s)-5] #Indices can be any int expressions
'ticexpialido'
>>> s[:] #A plain colon is the same as no colon
'supercalifragalisticexpialidotious'
>>> s[:10]+s[10:] #As a rule of thumb, s[:n]+s[n:]=s
'supercalifragalisticexpialidotious'
>>> s[-5:5]
''
</PRE>See what happens when the indices don't match up? No string. Hey, it's
better than an error, but still not what you want. Moving on, then, why would I
devote an entire section to slice indexing? Well, I think it's pretty damn neat.
It also lets you splice (not slice, splice) together strings in weird and
sometimes cool (not to mention useful) ways. Look at this non-useful way: <PRE>>>> #Mixes two names together. You could make this more sophisticated, like making sure
... #a vowel in the first name is followed by a consonant in the second.
... name1 = raw_input( "Type a name: " )
Type a name: Dave
>>> name2 = raw_input( "Type another name: " )
Type another name: Guido
>>> print name1[:3]+name2[-3:]
Davido
</PRE>Of course, I'm sure you'll find much more practical uses for splicing and
slicing, but hey, I gotta show you how it works first, don't I?
<P></P>
<P><FONT size=-2><A
href="#top">Back
to top</A></FONT></P>
<HR>
<H3 align=center><A name=fileio>File I/O</A></H3>
<P>How can you have a programming language without a way to access other files
on the system? I really don't know, but that's alright since Python can do it.
Well, then you're probably wondering how. Basically, first you need to open the
file and assign it to an object. Object? We haven't talked about those, have we?
Objects are like structures (more properly classes) in C, record in some other
languages. Basically they are a data type that is made up of other data types
combined, including (and in some cases especially) functions. File handles
(variables that refer to a file to be opened) are, predictably, of the file
object type. You assign a file handle using the open function, like this: <PRE>>>> f = open( "myfile.txt", "r" )
>>> f #This will vary
<open file 'myfile.txt', mode 'r' at 0x8122338>
</PRE>I hope you know what myfile.txt is (hint: the file to be opened). The "r"
part is a mode for opening the file. The mode you open the file in tells Python
whether you're going to read data from the file, write data to the file, etc.
Here's a list of the modes you can use:
<UL>
<LI>r - Reading
<LI>w - Writing
<LI>a - Appending (same as writing, only any new data is written at the end of
the file)
<LI>r+ - Reading and writing
<LI>No argument - Reading </LI></UL>Note that Python won't give you an error if
you specify some mode other than these. Be warned that it might make some
unexpected things happen later on, though. In Windows and MacOS there is also a
binary mode, "b", which is important but a bit confusing. Binary mode treats all
characters as normal characters, including newlines. The other modes, as we
shall soon see, can rely on newlines to separate or find data. The first of
these newline-using methods is readline. To access the readline method for a
file object, put 'readline()' after the object's name and a period. This returns
a string containing the next line in a file. Also available is readlines, which
reads all the lines of a file into a list. readlines can take an optional
argument that specifies the most bytes it should read from the file, plus
whatever it needs to reach the end of a line. One more thing: readline (or
readlines) returns an empty string '' if the end of the file has been reached.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -