Python for you and me 0.2

你​我​的​python

写​给​入​门​者​的​python

版 1

标​志​

Kushal Das

Linux User Group of Durgapur

法律通告

Permission is granted to copy, distribute, and/or modify this document under the terms of the Open Publication Licence, Version 1.0, or any later version. The terms of the OPL are set out below.
  1. REQUIREMENTS ON BOTH UNMODIFIED AND MODIFIED VERSIONS

    Open Publication works may be reproduced and distributed in whole or in part, in any medium physical or electronic, provided that the terms of this license are adhered to, and that this license or an incorporation of it by reference (with any options elected by the author(s) and/or publisher) is displayed in the reproduction.
    Proper form for an incorporation by reference is as follows:
    Copyright (c) <year> by <author's name or designee>. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, vX.Y or later (the latest version is presently available at http://www.opencontent.org/openpub/).
    The reference must be immediately followed with any options elected by the author(s) and/or publisher of the document (see section VI). Commercial redistribution of Open Publication-licensed material is permitted. Any publication in standard (paper) book form shall require the citation of the original publisher and author. The publisher and author's names shall appear on all outer surfaces of the book. On all outer surfaces of the book the original publisher's name shall be as large as the title of the work and cited as possessive with respect to the title.
  2. COPYRIGHT

    The copyright to each Open Publication is owned by its author(s) or designee.
  3. SCOPE OF LICENSE

    The following license terms apply to all Open Publication works, unless otherwise explicitly stated in the document.
    Mere aggregation of Open Publication works or a portion of an Open Publication work with other works or programs on the same media shall not cause this license to apply to those other works. The aggregate work shall contain a notice specifying the inclusion of the Open Publication material and appropriate copyright notice.
    SEVERABILITY. If any part of this license is found to be unenforceable in any jurisdiction, the remaining portions of the license remain in force.
    NO WARRANTY. Open Publication works are licensed and provided "as is" without warranty of any kind, express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose or a warranty of non-infringement.
  4. REQUIREMENTS ON MODIFIED WORKS

    All modified versions of documents covered by this license, including translations, anthologies, compilations and partial documents, must meet the following requirements:
    1. The modified version must be labeled as such.
    2. The person making the modifications must be identified and the modifications dated.
    3. Acknowledgement of the original author and publisher if applicable must be retained according to normal academic citation practices.
    4. The location of the original unmodified document must be identified.
    5. The original author's (or authors') name(s) may not be used to assert or imply endorsement of the resulting document without the original author's (or authors') permission.
  5. GOOD-PRACTICE RECOMMENDATIONS

    In addition to the requirements of this license, it is requested from and strongly recommended of redistributors that:
    1. If you are distributing Open Publication works on hardcopy or CD-ROM, you provide email notification to the authors of your intent to redistribute at least thirty days before your manuscript or media freeze, to give the authors time to provide updated documents. This notification should describe modifications, if any, made to the document.
    2. All substantive modifications (including deletions) be either clearly marked up in the document or else described in an attachment to the document.
    3. Finally, while it is not mandatory under this license, it is considered good form to offer a free copy of any hardcopy and CD-ROM expression of an Open Publication-licensed work to its author(s).
  6. LICENSE OPTIONS

    The author(s) and/or publisher of an Open Publication-licensed document may elect certain options by appending language to the reference to or copy of the license. These options are considered part of the license instance and must be included with the license (or its incorporation by reference) in derived works.
    A. To prohibit distribution of substantively modified versions without the explicit permission of the author(s). "Substantive modification" is defined as a change to the semantic content of the document, and excludes mere changes in format or typographical corrections.
    To accomplish this, add the phrase 'Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.' to the license reference or copy.
    B. To prohibit any publication of this work or derivative works in whole or in part in standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder.
    To accomplish this, add the phrase 'Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.' to the license reference or copy.
摘要
这​本​书​主​要​的​读​者​对​象​是​python语​言​的​入​门​者​。​

Preface
1. 文​档​约​定​
1.1. 排​版​约​定​
1.2. 抬​升​式​引​用​约​定​
1.3. 备​注​及​警​告​
2. 我​们​需​要​您​的​反​馈​意​见​!
1. 安​装​
1.1. Windows下​
1.2. GNU/Linux下​
2. 初​光​乍​现​
2.1. helloworld.py
2.2. 空​格​和​缩​进​
2.3. 注​释​
2.4. 模​块​
3. 变​量​和​数​据​类​型​
3.1. 关​键​字​和​标​识​符​
3.2. 从​键​盘​读​取​用​户​输​入​
3.3. 一​些​例​子​
3.3.1. N个​数​字​的​平​均​值​
3.3.2. 温​度​转​换​
3.4. 在​单​行​定​义​多​个​变​量​或​赋​值​
4. 运​算​符​和​表​达​式​
4.1. 运​算​符​
4.2. 整​型​计​算​的​实​例​
4.3. 关​系​操​作​符​
4.4. 逻​辑​运​算​符​
4.5. 简​写​运​算​符​
4.6. 表​达​式​
4.7. 类​型​转​换​
4.8. evaluateequ.py
4.9. quadraticequation.py
4.10. salesmansalary.py
5. if-else,控​制​流​程​的​关​键​字​
5.1. if 声​明​
5.2. Else声​明​
6. 循​环​
6.1. While循​环​
6.2. Fibonacci Series
6.3. Power Series
6.4. Multiplication Table
6.5. Some printing * examples
6.6. Lists
6.7. For loop
6.8. range() function
6.9. Continue statement
6.10. Else loop
7. 数​据​结​构​
7.1. 列​表​
7.2. 将​列​表​用​作​栈​和​队​列​
7.3. List Comprehensions
7.4. Tuples
7.5. Sets
7.6. Dictionaries
7.7. students.py
7.8. matrixmul.py
8. Strings
8.1. Different methods available for Strings
8.2. String the strings
8.3. Finding text
8.4. Palindrome checking
8.5. Number of words
9. Functions
9.1. Defining a function
9.2. Local and global variables
9.3. Default argument value
9.4. Keyword arguments
10. File handling
10.1. File opening
10.2. Reading a file
10.3. Writing in a file
10.4. copyfile.py
10.5. Random seeking in a file
11. 感​谢​
A. Revision History

Preface

1. 文​档​约​定​

本​手​册​使​用​几​个​约​定​来​突​出​某​些​用​词​和​短​语​以​及​信​息​的​某​些​片​段​。​
在 PDF 版​本​以​及​纸​版​中​,本​手​册​使​用​在 Liberation 字​体​套​件​中​选​出​的​字​体​。​如​果​您​在​您​的​系​统​中​安​装​了 Liberation 字​体​套​件​,它​还​可​用​于 HTML 版​本​。​如​果​没​有​安​装​,则​会​显​示​可​替​换​的​类​似​字​体​。​请​注​意​:红​帽​企​业 Linux 5 以​及​其​后​的​版​本​默​认​包​含 Liberation 字​体​套​件​。​

1.1. 排​版​约​定​

我​们​使​用​四​种​排​版​约​定​突​出​特​定​用​词​和​短​语​。​这​些​约​定​及​其​使​用​环​境​如​下​。​
固​定​粗​体​
用​来​突​出​系​统​输​入​,其​中​包​括 shell 命​令​、​文​件​名​以​及​路​径​。​还​可​用​来​突​出​按​键​以​及​组​合​键​。​例​如​:
To see the contents of the file my_next_bestselling_novel in your current working directory, enter the cat my_next_bestselling_novel command at the shell prompt and press Enter to execute the command.
The above includes a file name, a shell command and a key cap, all presented in Mono-spaced Bold and all distinguishable thanks to context.
Key-combinations can be distinguished from key caps by the hyphen connecting each part of a key-combination. For example:
Press Enter to execute the command.
Press Ctrl+Alt+F1 to switch to the first virtual terminal. Press Ctrl+Alt+F7 to return to your X-Windows session.
The first sentence highlights the particular key cap to press. The second highlights two sets of three key caps, each set pressed simultaneously.
If source code is discussed, class names, methods, functions, variable names and returned values mentioned within a paragraph will be presented as above, in Mono-spaced Bold. For example:
File-related classes include filesystem for file systems, file for files, and dir for directories. Each class has its own associated set of permissions.
Proportional Bold
This denotes words or phrases encountered on a system, including application names; dialogue box text; labelled buttons; check-box and radio button labels; menu titles and sub-menu titles. For example:
Choose System > Preferences > Mouse from the main menu bar to launch Mouse Preferences. In the Buttons tab, click the Left-handed mouse check box and click Close to switch the primary mouse button from the left to the right (making the mouse suitable for use in the left hand).
To insert a special character into a gedit file, choose Applications > Accessories > Character Map from the main menu bar. Next, choose Search > Find… from the Character Map menu bar, type the name of the character in the Search field and click Next. The character you sought will be highlighted in the Character Table. Double-click this highlighted character to place it in the Text to copy field and then click the Copy button. Now switch back to your document and choose Edit > Paste from the gedit menu bar.
The above text includes application names; system-wide menu names and items; application-specific menu names; and buttons and text found within a GUI interface, all presented in Proportional Bold and all distinguishable by context.
Note the > shorthand used to indicate traversal through a menu and its sub-menus. This is to avoid the difficult-to-follow 'Select Mouse from the Preferences sub-menu in the System menu of the main menu bar' approach.
Mono-spaced Bold Italic or Proportional Bold Italic
Whether Mono-spaced Bold or Proportional Bold, the addition of Italics indicates replaceable or variable text. Italics denotes text you do not input literally or displayed text that changes depending on circumstance. For example:
To connect to a remote machine using ssh, type ssh username@domain.name at a shell prompt. If the remote machine is example.com and your username on that machine is john, type ssh john@example.com.
The mount -o remount file-system command remounts the named file system. For example, to remount the /home file system, the command is mount -o remount /home.
To see the version of a currently installed package, use the rpm -q package command. It will return a result as follows: package-version-release.
Note the words in bold italics above — username, domain.name, file-system, package, version and release. Each word is a placeholder, either for text you enter when issuing a command or for text displayed by the system.
Aside from standard usage for presenting the title of a work, italics denotes the first use of a new and important term. For example:
When the Apache HTTP Server accepts requests, it dispatches child processes or threads to handle them. This group of child processes or threads is known as a server-pool. Under Apache HTTP Server 2.0, the responsibility for creating and maintaining these server-pools has been abstracted to a group of modules called Multi-Processing Modules (MPMs). Unlike other modules, only one module from the MPM group can be loaded by the Apache HTTP Server.

1.2. 抬​升​式​引​用​约​定​

二​,一​般​是​多​行​,数​据​输​入​要​明​显​与​周​围​文​本​分​开​。​
将​发​送​到​终​端​的​输​入​设​置​为 Mono-spaced Roman 并​显​示​为​:
books        Desktop   documentation  drafts  mss    photos   stuff  svn
books_tests  Desktop1  downloads      images  notes  scripts  svgs
源​码​列​表​也​设​为 Mono-spaced Roman,但​以​下​面​的​形​式​出​现​和​突​出​:
package org.jboss.book.jca.ex1;

import javax.naming.InitialContext;

public class ExClient
{
   public static void main(String args[]) 
       throws Exception
   {
      InitialContext iniCtx = new InitialContext();
      Object         ref    = iniCtx.lookup("EchoBean");
      EchoHome       home   = (EchoHome) ref;
      Echo           echo   = home.create();

      System.out.println("Created Echo");

      System.out.println("Echo.echo('Hello') = " + echo.echo("Hello"));
   }
   
}

1.3. 备​注​及​警​告​

最​后​,我​们​使​用​三​种​视​觉​形​式​来​突​出​那​些​可​能​被​忽​视​的​信​息​。​

备​注​

备​注​是​对​手​头​任​务​的​提​示​、​捷​径​或​者​另​外​的​解​决​方​法​。​忽​略​提​示​不​会​造​成​负​面​后​果​,但​您​可​能​会​错​过​一​个​更​省​事​的​诀​窍​。​

重​要​

重​要​框​中​的​内​容​是​那​些​容​易​错​过​的​事​情​:配​置​更​改​只​可​用​于​当​前​会​话​,或​者​在​应​用​更​新​前​要​重​启​服​务​。​忽​略​重​要​框​中​的​内​容​不​会​造​成​数​据​丢​失​但​可​能​会​让​您​抓​狂​。​

警​告​

警​告​是​不​应​被​忽​略​的​。​忽​略​警​告​信​息​很​可​能​导​致​数​据​丢​失​。​

2. 我​们​需​要​您​的​反​馈​意​见​!

您​应​该​创​建​您​自​己​的​本​地 Feedback.xml 文​件​来​覆​盖​这​个​文​件​。​

第 1 章 安​装​

在​这​一​章​中​你​将​学​到​如​何​安​装​python

1.1. Windows下​

到​python官​方​站​点​http://python.org/ftp/python/,下​载​最​新​的​版​本​带​Windows(TM)安​装​程​序​的​python版​本​。​像​安​装​windows其​它​的​应​用​程​序​一​样​安​装​python。​

1.2. GNU/Linux下​

通​常​的​GNU/Linux发​行​版​都​包​含​了​Python,所​以​不​用​有​什​么​担​心​:)如​果​你​还​没​有​,那​么​你​可​以​直​接​从​python的​官​网​下​载​,也​可​以​从​你​的​发​行​版​仓​库​中​下​载​安​装​。​
Fedora下​
#yum install python
Debian下​
#apt-get install python

第 2 章 初​光​乍​现​

现​在​我​们​来​看​下​我​们​的​第​一​次​编​码​。​众​所​周​知​,python是​一​门​解​释​性​语​言​,你​可​以​在​python解​释​器​中​直​接​写​代​码​,也​可​以​将​之​写​到​文​件​中​,然​后​执​行​这​个​文​件​。​首​先​,我​们​将​用​python的​解​释​器​来​作​示​范​,启​动​python:在​终​端​或​shell下​键​入​“​python":
[kd@kdlappy ~]$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information. 
>>>
作​为​第​一​次​编​码​,我​们​将​打​印​经​典​的​"Hello World!",如​下​所​示​:
>>> print "Hello World!"
Hello World!

2.1. helloworld.py

作​为​正​式​的​程​序​员​,你​可​能​要​将​上​述​代​码​写​到​一​个​文​件​。​那​么​我​们​来​建​立​一​个​文​件​名​为​helloworld.py的​文​件​,用​你​喜​欢​的​任​何​编​辑​器​,我​用​的​是​vi,你​可​以​使​用​基​于​GUI的​工​具​,如​kate,gedit等​。​
#!/usr/bin/env python
print "Hello World!"
欲​运​行​上​述​写​下​的​代​码​,你​首​先​得​使​文​件​属​性​为​可​执​行​,在​GNU/Linux环​境​下​,你​可​以​在​shell中​执​行​如​下​命​令​:
$ chmod +x helloworld.py
这​时​你​可​以​执​行​此​文​件​了​。​
$ ./helloworld.py 
Hello World!
在​代​码​的​第​一​行​我​们​以​#! 开​始​,我​们​称​之​为​sha-bang。​这​样​做​的​目​的​是​告​诉​shell用​python解​释​器​来​执​行​下​面​代​码​。​接​下​来​的​一​行​,仅​仅​是​打​印​一​条​信​息​。​在​python中​我​们​认​为​所​有​的​文​本​行​都​是​strings类​型​(下​面​会​讲​到​python数​据​类​型​--译​者​注​)。​

2.2. 空​格​和​缩​进​

在​python语​言​中​,空​格​很​重​要​。​我​们​使​用​空​格​将​标​志​符​区​分​开​。​空​格​在​行​的​开​始​处​被​称​之​为​缩​排​,但​是​如​果​你​写​了​错​误​的​缩​排​,python解​释​器​将​抛​出​错​误​。​例​如​下​面​情​形​:
>>> a = 12
>>>  a = 12
  File "<stdin>", line 1
      a = 12
          ^
          IndentationError: unexpected indent

警​告​

在​第​二​行​的​开​始​处​出​现​了​多​余​的​空​格​,以​至​于​引​起​错​误​。​所​以​要​经​常​检​查​合​适​的​缩​排​!
如​果​你​混​合​使​用​制​表​符​和​空​格​,这​种​缩​排​错​误​会​常​见​。​所​以​建​议​如​果​使​用​空​格​,就​一​直​用​空​格​作​缩​排​,不​要​使​用​制​表​符​。​对​于​你​来​说​他​们​俩​是​一​样​的​,但​是​你​试​图​去​运​行​的​时​候​,代​码​会​给​你​抛​出​错​误​

2.3. 注​释​

注​释​是​一​些​英​语​文​本​方​式​提​供​解​释​此​处​代​码​是​做​什​么​的​,我​们​写​在​代​码​中​写​注​释​是​便​于​其​他​人​容​易​理​解​。​python的​注​释​是​以​#开​始​的​行​,注​释​在​程​序​中​将​被​忽​略​,也​就​是​说​对​程​序​没​有​任​何​的​作​用​。​
>>> #this is a comment
>>> #the next line will add two numbers
>>> a = 12 + 34
>>> print c #this is a comment too :)

2.4. 模​块​

模​块​是​包​含​可​以​直​接​使​用​(重​用​)的​函​数​定​义​、​变​量​的​python文​件​,它​们​通​常​是​以​.py为​扩​展​名​。​Python本​身​在​安​装​时​就​带​有​大​量​的​模​块​。​我​们​将​会​用​到​一​部​分​。​欲​使​用​模​块​你​首​先​的​将​之​导​入​(import)。​
>>> import math
>>> print math.e
2.71828182846
我​们​将​会​在​Modules那​章​中​学​习​更​多​的​关​于​模​块​的​内​容​。​

第 3 章 变​量​和​数​据​类​型​

每​一​种​编​程​语​言​都​有​其​自​身​的​语​法​规​则​,正​如​我​们​日​常​所​说​的​其​它​国​家​、​民​族​的​语​言​。​

3.1. 关​键​字​和​标​识​符​

Python代​码​使​用​标​识​符​来​分​离​。​标​识​符​(通​常​提​供​名​称​)被​描​述​为​以​下​定​义​:
identifier ::= (letter|"_") (letter | digit | "_")* 
letter ::= lowercase | uppercase 
lowercase ::= "a"..."z" 
uppercase ::= "A"..."Z" 
digit ::= "0"..."9"
这​意​味​着​_abcd是​合​法​的​而​1sd不​是​。​以​下​列​出​的​是​用​于​预​留​字​,或​者​说​是​语​言​的​关​键​字​,它​们​是​不​可​用​于​通​常​的​标​识​符​的​。​他​们​是​必​须​按​如​下​拼​写​:
and       del      from      not   while 
as        elif     global    or    with 
assert    else     if        pass  yield 
break     except   import    print 
class     exec     in        raise 
continue  finally  is        return 
def       for      lambda    try
在​python中​我​们​不​需​要​特​别​的​为​变​量​指​定​数​据​类​型​。​所​以​你​可​以​直​接​写​abc = 1,这​样​变​量​abc就​是​整​型​,如​果​你​写​出 abc =1.0,那​么​abc就​是​一​浮​点​型​。​以​下​是​一​个​增​加​上​述​给​定​的​数​字​的​简​单​程​序​
>>> a = 13 
>>> b = 23
>>> a + b 
36
通​过​上​面​的​例​子​你​可​能​已​经​理​解​了​在​python中​如​何​定​义​变​量​,也​就​是​只​需​要​敲​入​名​称​和​值​就​可​以​了​。​Python可​以​很​精​妙​的​操​纵​字​符​串​,它​们​只​需​要​如​下​用​单​引​号​和​双​引​号​括​起​来​即​可​
>>> 'India'
'India' 
>>> 'India\'s best' 
"India's best" 
>>> "Hello World!" 
'Hello World!'

3.2. 从​键​盘​读​取​用​户​输​入​

通​常​情​况​下​,在​python的​代​码​中​是​不​需​要​从​键​盘​读​取​输​入​的​。​当​然​python还​是​提​供​了​这​个​输​入​函​数​,那​就​是​raw_input。​raw_input("String to show") ,这​将​返​回​一​字​符​串​用​于​输​出​。​让​我​们​写​一​个​程​序​:实​现​从​键​盘​读​入​一​数​字​,然​后​判​断​其​是​否​小​于​100.程​序​的​名​称​是 testhundred.py
#!/usr/bin/env python   
number = int(raw_input("Enter an integer: "))
if number < 100:   
    print "Your number is smaller than 100"   
else:   
    print "Your number is greater than 100"
输​出​
[kd@kdlappy book]$ ./testhundred.py 
Enter an integer: 13 
Your number is smaller than 100 
[kd@kdlappy book]$ ./testhundred.py 
Enter an integer: 123 
Your number is greater than 100
在​接​下​来​的​程​序​我​们​将​计​算​投​资​。​
#!/usr/bin/env python 
amount = float(raw_input("Enter amount: ")) 
inrate = float(raw_input("Enter Interest rate: ")) 
period = int(raw_input("Enter period: ")) 
value = 0 
year = 1 
while year <= period:
    value = amount + (inrate * amount)
    print "Year %d Rs. %.2f" %(year, value)
    amount = value
    year = year + 1
输​出​
[kd@kdlappy book]$ ./investment.py
Enter amount: 10000
Enter Interest rate: 0.14
Enter period: 5
Year 1 Rs. 11400.00
Year 2 Rs. 12996.00
Year 3 Rs. 14815.44
Year 4 Rs. 16889.60
Year 5 Rs. 19254.15

3.3. 一​些​例​子​

一​些​关​于​变​量​和​数​据​类​型​的​例​子​:

3.3.1. N个​数​字​的​平​均​值​

接​下​来​的​程​序​我​们​将​实​现​计​算​N个​数​字​的​平​均​值​。​
#!/usr/bin/env python
N = 10
sum = 0
count = 0
while count < N:
    number = float(raw_input(""))
    sum = sum + number
    count = count + 1
average = float(sum)/N
print "N = %d , Sum = %f" % (N, sum)
print "Average = %f" % average
输​出​
[kd@kdlappy book]$ ./averagen.py
1
2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
N = 10 , Sum = 38.800000
Average = 3.880000

3.3.2. 温​度​转​换​

在​此​程​序​中​我​们​用​公​式 C=(F-32)/1.8将​华​氏​温​度​转​换​为​摄​氏​温​度​
#!/usr/bin/env python
fahrenhite = 0.0
print "Fahrenheit Celsius"
while fahrenheit <= 250:
    celsius = ( fahrenheit - 32.0 ) / 1.8 #Here we calculate the fahrenhite value
    print "%5.1f %7.2f" % (fahrenheit , celsius)
    fahrenheit = fahrenheit + 25
输​出​
[kd@kdlappy book]$ ./temperature.py
Fahrenheit Celsius
  0.0  -17.78
 25.0   -3.89
 50.0   10.00
 75.0   23.89
100.0   37.78
125.0   51.67
150.0   65.56
175.0   79.44
200.0   93.33
225.0  107.22
250.0  121.11

3.4. 在​单​行​定​义​多​个​变​量​或​赋​值​

你​可​以​在​单​行​中​实​现​多​个​变​量​并​赋​值​,例​如​
>>> a , b = 45, 54
>>> a
45
>>> b
54
此​用​于​交​换​两​个​数​字​变​的​非​常​容​易​
>>> a, b = b , a
>>> a
54
>>> b
45

第 4 章 运​算​符​和​表​达​式​

在​Python代​码​中​你​将​用​到​大​量​的​表​达​式​。​表​达​式​由​操​作​符​和​操​作​数​组​成​。​像​2 + 3就​是​一​个​表​达​式​。​

4.1. 运​算​符​

运​算​符​只​是​一​种​告​诉​python解​释​器​去​做​一​些​数​学​或​逻​辑​操​作​的​符​号​。​一​些​基​本​的​数​学​操​作​符​如​下​所​示​:
>>> 2 + 3
5
>>> 23 - 3
20
>>> 22.0 / 12
1.8333333333333333
想​要​得​到​浮​点​数​的​结​果​,你​必​须​用​浮​点​数​作​操​作​数​来​实​现​除​法​运​算​。​求​余​的​符​号​是 %
>>> 14 % 3
2

4.2. 整​型​计​算​的​实​例​

代​码​
#!/usr/bin/env python
days = int(raw_input("Enter days: "))
months = days / 30
days = days % 30
print "Months = %d Days = %d" % (months, days)
输​出​
[kd@kdlappy book]$ ./integer.py
Enter days: 265
Months = 8 Days = 25
在​头​一​行​中​我​获​得​用​户​输​入​的​天​数​,然​后​得​到​月​份​数​和​具​体​的​天​数​并​打​印​出​来​。​你​可​以​使​用​更​容​易​的​方​法​
#!/usr/bin/env python
days = int(raw_input("Enter days: "))
print "Months = %d Days = %d" % (divmod(days, 30))
divmod(num1, num2)函​数​返​回​两​个​值​,第​一​个​是​num1和​num2相​除​得​到​的​值​,第​二​个​是​num1和​num2求​余​得​到​的​值​。​

4.3. 关​系​操​作​符​

你​可​以​使​用​下​面​的​操​作​符​来​实​现​关​系​运​算​
关​系​操​作​符​
数​学​运​算​符​含​义​
<小​于​
<=小​于​等​于​
>大​于​
>=大​于​等​于​
==等​于​
!=不​等​于​
一​些​实​例​
>>> 1 < 2
True
>>> 3 > 34
False
>>> 23 == 45
False
>>> 34 != 323
True
// 操​作​符​会​给​出​平​除​运​算​结​果​
>>> 4.0 // 3
1.0
>>> 4.0 / 3
1.3333333333333333

4.4. 逻​辑​运​算​符​

作​逻​辑​运​算​的​“​与​”​,“​或​”​,我​们​用 and , or关​键​字​。 如​果​x 是​False x and y 返​回​False否​则​返​回​y的​值​。​如​果​x 是​Ture,它​返​回​真​。​
>>> 1 and 4
4
>>> 1 or 4
1
>>> -1 or 4
-1
>>> 0 or 4
4

4.5. 简​写​运​算​符​

x op = expression 为​简​写​运​算​的​语​法​形​式​。​它​将​计​算​形​如​x = x op expression ,例​如​
>>> a = 12
>>> a += 13
>>> a
25
>>> a /= 3
>>> a
8
>>> a += (26* 32)
>>> a
840
shorthand.py 实​例​
#!/usr/bin/env python
N = 100
a = 2
while a < N:
    print "%d" % a
    a *= a
输​出​
[kd@kdlappy book]$ ./shorthand.py
2
4
16

4.6. 表​达​式​

我​们​一​般​写​表​达​式​的​时​候​,在​远​算​符​的​前​后​都​加​一​个​空​格​,这​样​使​代​码​更​可​读​。​如​
a = 234 * (45 - 56.0 / 34)
一​个​用​于​演​示​表​达​式​的​例​子​
#!/usr/bin/env python
a = 9
b = 12
c = 3
x = a -b / 3 + c * 2 -1
y = a -b / (3 + c) * (2 -1)
z = a - (b / (3 +c) * 2) -1
print "X = ", x
print "Y = ", y
print "Z = ", z
输​出​
[kd@kdlappy book]$ ./evaluationexp.py
X =  10
Y =  7
Z =  4
x作​为​第​一​个​被​计​算​。​步​骤​如​下​所​示​
9 - 12 / 3 + 3 * 2 -1
9 - 4 + 3 * 2 - 1
9 - 4 + 6 - 1
5 + 6 -1
11 - 1
10
现​在​yz均​有​括​号​,所​以​表​达​式​计​算​会​有​不​同​的​方​式​。​请​读​者​自​行​检​验​。​

4.7. 类​型​转​换​

我​们​可​以​手​动​的​去​作​类​型​转​换​,如​
float(string) -> float value
int(string) -> integer value
str(integer) or str(float) -> string representation 
>>> a = 8.126768
>>> str(a)
'8.126768'

4.8. evaluateequ.py

这​个​程​序​计​算​1/x+1/(x+1)+1/(x+2)+ ... +1/n 直​到​n.在​此​例​中​x = 1 , n =10
#!/usr/bin/env python
sum = 0.0
for i in range(1, 11):
    sum += 1.0 / i
    print "%2d %6.4f" % (i , sum)
输​出​
[kd@kdlappy book]$ ./evaluateequ.py
 1 1.0000
 2 1.5000
 3 1.8333
 4 2.0833
 5 2.2833
 6 2.4500
 7 2.5929
 8 2.7179
 9 2.8290
10 2.9290
sum += 1.0 / i 是​和​sum = sum + 1.0 / i表​达​的​相​同​的​意​思​。​

4.9. quadraticequation.py

这​是​一​个​模​拟​二​次​方​运​算​的​程​序​
#!/usr/bin/env python
import math
a = int(raw_input("Enter value of a: "))
b = int(raw_input("Enter value of b: "))
c = int(raw_input("Enter value of c: "))
d = b * b - 4 * a * c
if d < 0:
    print "ROOTS are imaginary"
else:
    root1 = (-b + math.sqrt(d)) / (2.0 * a)
    root2 = (-b - math.sqrt(d)) / (2.0 * a)
print "Root 1 = ", root1
print "Root 2 = ", root2

4.10. salesmansalary.py

在​这​个​例​子​中​我​们​将​计​算​一​位​数​码​相​机​的​销​售​人​员​的​工​资​。​他​的​基​本​工​资​是​1500,每​售​出​一​台​数​码​相​机​他​可​以​得​到​200而​且​他​的​月​任​务​是​%2.输​入​表​示​的​分​别​是​售​出​的​数​码​相​机​的​台​数​和​总​的​数​码​相​机​的​价​格​。​
#!/usr/bin/env python
basic_salary = 1500
bonus_rate = 200
commision_rate = 0.02
numberofcamera = int(raw_input("Enter the number of inputs sold: "))
price = float(raw_input("Enter the total prices: "))
bonus = (bonus_rate * numberofcamera)
commision = (commision_rate * numberofcamera * price)

print "Bonus        = %6.2f" % bonus
print "Commision    = %6.2f" % commision
print "Gross salary = %6.2f" % ( basic_salary + bonus + commision)
输​出​
[kd@kdlappy book]$ ./salesmansalary.py
Enter the number of inputs sold: 5
Enter the total prices: 20450
Bonus        = 1000.00
Commision    = 2045.00
Gross salary = 4545.00

第 5 章 if-else,控​制​流​程​的​关​键​字​

我​们​处​理​现​实​生​活​中​的​问​题​时​会​作​出​决​定​。​决​定​买​那​种​照​相​机​或​者​怎​么​击​打​棒​球​较​好​。​同​样​写​计​算​机​程​序​我​们​作​一​样​的​决​定​。​我​们​用​if-else声​明​来​决​定​事​情​,我​们​用​它​们​可​以​改​变​程​序​运​行​的​流​程​。​

5.1. if 声​明​

语​法​如​下​
if expression:
    do this
如​果​expression的​值​为​真​(不​是​零​的​任​何​数​),程​序​将​执​行​缩​排​后​的​内​容​。​记​住​缩​排​,在​表​达​式​为​真​的​情​况​下​所​有​行​都​要​被​执​行​。​一​个​简​单​的​例​子​,接​受​用​户​输​入​一​个​并​且​检​查​它​小​于​100还​是​不​小​于​100。​
#!/usr/bin/env python
number = int(raw_input("Enter a number: "))
if number < 100:
    print "The number is less than 100"
然​后​我​们​运​行​它​
[kd@kdlappy book]$ ./number100.py
Enter a number: 12
The number is less than 100

5.2. Else声​明​

现​在​我​们​需​要​在​上​面​的​例​子​中​打​印​"Greater than"如​果​数​字​大​于​100的​话​。​为​此​我​们​用​到​了 else声​明​。​它​将​奏​效​于​当​if语​句​不​能​完​全​的​控​制​的​时​候​。​
#!/usr/bin/env python
number = int(raw_input("Enter a number: "))
if number < 100:
    print "The number is less than 100"
else:
    print "The number is greater than 100"
输​出​
   
[kd@kdlappy book]$ ./number100.py
Enter a number: 345
The number is greater than 100
另​外​一​个​基​本​的​实​例​
>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'

第 6 章 循​环​

In the examples we used before , sometimes it was required to do the same work couple of times. We use a counter to check how many times the code needs to be executed. This technique is known as looping. First we are going to look into while statement for looping.

6.1. While循​环​

The syntax for while statement is like
while condition:
    statement1
    statement2
The code we want to reuse must be indented properly under the while statement. They will be executed if the condition is true. Again like in if-else statement any non zero value is true. Let us write a simple code to print numbers 0 to 10
>>> n = 0
>>> while n < 11:
...     print n
...     n += 1
...
0
1
2
3
4
5
6
7
8
9
10
In the first line we are setting n = 0, then in the while statement the condition is n < 11 , that means what ever line indented below that will execute until n becomes same or greater than 11. Inside the loop we are just printing the value of n and then increasing it by one.

6.2. Fibonacci Series

Let us try to solve Fibonacci series. In this series we get the next number by adding the previous two numbers. So the series looks like 1,1,2,3,5,8,13 .......
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
    print b
    a, b = b, a + b
The output
[kd@kdlappy book]$ ./fibonacci1.py
1
1
2
3
5
8
13
21
34
55
89
In the first line of the code we are initializing a and b, then looping while b's value is less than 100. Inside the loop first we are printing the value of b and then in the next line putting the value of b to a and a + b to b in the same line.
If you put a trailing comma in the print statement , then it will print in the same line
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
    print b,
    a, b = b, a + b
The output
[kd@kdlappy book]$ ./fibonacci2.py
1 1 2 3 5 8 13 21 34 55 89

6.3. Power Series

Let us write a program to evaluate the power series. The series looks like e**x =1+x+x**2/2! +x**3/3! +....+ x**n/n! where 0 <x <1
#!/usr/bin/env python
x = float(raw_input("Enter the value of x: "))
n = term = num = 1
sum = 1.0
while n <= 100:
    term *= x / n
    sum += terrm
    n += 1
    if term < 0.0001:
        break
print "No of Times= %d and Sum= %f" % (n, sum)
The output
kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0
No of Times= 2 and Sum= 1.000000
[kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0.1
No of Times= 5 and Sum= 1.105171
[kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0.5
No of Times= 7 and Sum= 1.648720
In this program we introduced a new keyword called break. What break does is stop the innermost loop. In this example we are using break under the if statement
if term < 0.0001:
        break
This means if the value of term is less than 0.0001 then get out of the loop.

6.4. Multiplication Table

In this example we are going to print the multiplication table up to 10.
#!/usr/bin/env python
i = 1
print "-" * 50
while i < 11:
    n = 1
    while n <= 10:
        print "%4d" % (i * n),
        n += 1
    print ""
    i += 1
print "-" * 50
The output
[kd@kdlappy book]$ ./multiplication.py
--------------------------------------------------
   1    2    3    4    5    6    7    8    9   10
   2    4    6    8   10   12   14   16   18   20
   3    6    9   12   15   18   21   24   27   30
   4    8   12   16   20   24   28   32   36   40
   5   10   15   20   25   30   35   40   45   50
   6   12   18   24   30   36   42   48   54   60
   7   14   21   28   35   42   49   56   63   70
   8   16   24   32   40   48   56   64   72   80
   9   18   27   36   45   54   63   72   81   90
  10   20   30   40   50   60   70   80   90  100
--------------------------------------------------
Here we used one while loop inside another loop, this is known as nested looping. You can also see one interesting statement here
print "-" * 50
In a print statement if we multiply the string with an integer n , the string will be printed nmany times. Some examples
>>> print "*" * 10
**********
>>> print "#" * 20
####################
>>> print "--" * 20
----------------------------------------
>>> print "-" * 40
----------------------------------------

6.5. Some printing * examples

Here are some examples which you can find very often in college lab reports
Design 1
#!/usr/bin/env python
row = int(raw_input("Enter the number of rows: "))
n = row
while n >= 0:
    x =  "*" * n
    print x
    n -= 1
The output
[kd@kdlappy book]$ ./design1.py
Enter the number of rows: 5
*****
****
***
**
*
Design 2
#!/usr/bin/env python
n = int(raw_input("Enter the number of rows: "))
i = 1
while i <= n:
    print "*" * i
    i += 1
The output
[kd@kdlappy book]$ ./design2.py
Enter the number of rows: 5
*
**
***
****
*****
Design 3
#!/usr/bin/env python
row = int(raw_input("Enter the number of rows: "))
n = row
while n >= 0:
    x =  "*" * n
    y = " " * (row - n)
    print y + x
    n -= 1
The output
[kd@kdlappy book]$ ./design3.py
Enter the number of rows: 5
*****
 ****
  ***
   **
    *

6.6. Lists

We are going to learn a data structure called list before we go ahead to learn more on looping. Lists an be written as a list of comma-separated values (items) between square brackets.
>>> a = [ 1 , 342, 2233423, 'India', 'Fedora']
>>> a
[1, 342, 2233423, 'India', 'Fedora']
Lists can keep any other data inside it. It works as a sequence too, that means
>>> a[0]
1
>>> a[4]
'Fedora'
You can even slice it into different pieces, examples are given below
>>> a[4]
'Fedora'
>>> a[-1]
'Fedora'
>>> a[-2]
'India'
>>> a[0:-1]
[1, 342, 2233423, 'India']
>>> a[2:-2]
[2233423]
>>> a[:-2]
[1, 342, 2233423]
>>> a[0::2]
[1, 2233423, 'Fedora']
In the last example we used two :(s) , the last value inside the third brackets indicates step. s[i:j:k] means slice of s from i to j with step k.
To check if any value exists within the list or not you can do
>>> a = ['Fedora', 'is', 'cool']
>>> 'cool' in a
True
>>> 'Linux' in a
False
That means we can use the above statement as if clause expression. The built-in function len() can tell the length of a list.
>>> len(a)
3

6.7. For loop

There is another to loop by using for statement. In python the for statement is different from the way it works in C. Here for statement iterates over the items of any sequence (a list or a string). Example given below
>>> a = ['Fedora', 'is', 'powerfull']
>>> for x in a:
...     print x,
...
Fedora is powerfull
We can also do things like
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> for x in a[::2]:
...     print x
...
1
3
5
7
9

6.8. range() function

range() is a buitin function. From the help document
range(...)
    range([start,] stop[, step]) -> list of integers
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.
Now if you want to see this help message on your system type help(range) in the python interpreter. help(s) will return help message on the object s. Examples of range function
>>> range(1,5)
[1, 2, 3, 4]
>>> range(1,15,3)
[1, 4, 7, 10, 13]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

6.9. Continue statement

Just like break we have another statement, continue, which skips the execution of the code after itself and goes back to the start of the loop. That means it will help you to skip a part of the loop. In the below example we will ask the user to input an integer, if the input is negative then we will ask again, if positive then we will square the number. To get out of the infinite loop user must input 0.
#!/usr/bin/env python
while True:
    n = int(raw_input("Please enter an Integer: "))
    if n < 0:
        continue #this will take the execution back to the starting of the loop
    elif n == 0:
        break
    print "Square is ", n ** 2
print "Goodbye"
The output
[kd@kdlappy book]$ ./continue.py
Please enter an Integer: 34
Square is 1156
Please enter an Integer: 4
Square is 16
Please enter an Integer: -9
Please enter an Integer: 0
Goodbye

6.10. Else loop

We can have an optional else statement after any loop. It will be executed after the loop unless a break statement stopped the loop.
>>> for i in range(0,5):
...     print i
... else:
...     print "Bye bye"
...
0
1
2
3
4
Bye bye
We will see more example of break and continue later in the book.

第 7 章 数​据​结​构​

Python有​许​多​内​建​的​数​据​结​构​。​如​果​你​还​想​知​道​什​么​是​数​据​结​构​,其​实​她​除​了​存​储​数​据​和​一​些​特​殊​的​操​作​技​巧​之​外​什​么​也​不​是​。​我​们​在​以​前​已​经​见​过​列​表​了​,现​在​我​们​来​深​入​的​了​解​一​下​。​

7.1. 列​表​

>>> a = [23, 45, 1, -3434, 43624356, 234]
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45]
首​先​我​们​建​立​了​一​个​列​表 a. 然​后​添​加​元​素 45 到​列​表​的​末​尾​,我​们​调​用​函​数 a.append(45)。 你​可​以​看​到​元​素 45 已​经​添​加​到​列​表​的​末​端​了​。 有​时​候​我​们​需​要​将​数​据​插​入​到​列​表​的​任​何​位​置​,这​时​我​们​使​用​函​数​insert()。​
>>> a.insert(0, 1) # 1 added at the 0th position of the list
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45]
>>> a.insert(0, 111)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 234, 45]
count(s)将​返​回​出​现​在​列​表​中 s 的​次​数​。​这​里​我​们​将​检​验​在​此​列​表​中​出​现​45 的​次​数​。​
>>> a.count(45)
2
如​果​你​想​从​列​表​中​去​掉​一​些​元​素​,那​么​请​使​用​函​数​remove()。​
>>> a.remove(234)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45]
将​整​个​列​表​反​转​后​输​出​
>>> a.reverse()
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111]
我​们​可​以​在​列​表​里​存​储​任​何​数​据​,现​在​我​们​来​将​一​个​列​表​b 添​加​到​列​表​a 中​,呵​呵​,你​看​到​了​吧​!我​们​接​着​学​习​如​何​将​b 中​的​值​添​加​到​a 中​。​
>>> b = [45, 56, 90]
>>> a.append(b)
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90]]
>>> a[-1]
[45, 56, 90]
>>> a.extend(b) #To add the values of b not the b itself
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90], 45, 56, 90]
>>> a[-1]
90
如​上​,你​可​以​看​到​我​们​用​a.extend()方​法​来​扩​展​列​表​的​了​。​要​是​为​列​表​排​序​,我​们​使​用​sort()方​法​。​
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356, [45, 56, 90]]
你​也​可​以​用​关​键​字​del来​删​除​列​表​中​的​任​何​元​素​。​
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356]

7.2. 将​列​表​用​作​栈​和​队​列​

栈​是​我​们​通​常​所​说​的​一​种​LIFO(Last In First Out)数​据​结​构​。​它​的​意​思​是​数​据​在​最​后​的​位​置​上​进​入​,并​且​最​后​进​入​的​数​据​第​一​个​出​来​。​最​简​单​的​例​子​洗​一​打​盘​子​,如​果​你​想​让​最​下​边​的​那​个​盘​子​,你​必​须​将​上​面​的​一​一​拿​走​,最​先​拿​走​的​就​是​最​上​面​的​那​个​盘​子​。​代​码​同​样​可​以​达​到​目​标​
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop()
6
>>> a.pop()
5
>>> a.pop()
4
>>> a.pop()
3
>>> a
[1, 2]
>>> a.append(34)
>>> a
[1, 2, 34)
我​们​刚​学​到​一​新​的​方​法​,如​上​pop().pop(i)方​法​,可​以​从​列​表​中​将​第​i个​元​素​踢​出​来​。​
在​我​们​每​天​的​生​活​中​都​可​以​遇​到​队​列​多​次​,比​如​售​票​窗​口​、​图​书​馆​、​超​市​的​结​帐​出​口​。​队​列​是​一​种​你​可​以​在​后​面​追​加​数​据​但​只​能​从​开​始​拿​出​数​据​的​数​据​结​构​,这​就​是​为​什​么​它​是​FIFO(First In First Out).
>>> a = [1, 2, 3, 4, 5]
>>> a.append(1)
>>> a
[1, 2, 3, 4, 5, 1]
>>> a.pop(0)
1
>>> a.pop(0)
2
>>> a
[3, 4, 5, 1]
欲​从​列​表​中​踢​出​第​一​个​元​素​,我​们​用​方​法​a.pop(0)

7.3. List Comprehensions

List comprehensions provide a concise way to create lists. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it.
For example if we want to make a list out of the square values of another list, then
>>> a = [1, 2, 3]
>>> [x ** 2 for x in a]
[1, 4, 9]
>>> z = [x + 1 for x in [x ** 2 for x in a]]
>>> z
[2, 5, 10]
Above in the second case we used two list comprehensions in a same line.

7.4. Tuples

Tuples are data separated by comma.
>>> a = 'Fedora', 'Debian', 'Kubuntu', 'Pardus'
>>> a
('Fedora', 'Debian', 'Kubuntu', 'Pardus')
>>> a[1]
'Debian'
>>> for x in a:
...     print x,
...
Fedora Debian Kubuntu Pardus
You can also unpack values of any tuple in to variables, like
>>> divmod(15,2)
(7, 1)
>>> x, y = divmod(15,2)
>>> x
7
>>> y
1
Tuples are immutable, that means you can not del/add/edit any value inside the tuple. Here is another example
>>> a = (1, 2, 3, 4)
>>> del a[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
Above you can see python is giving error when we are trying to delete a value in the tuple.
To create a tuple which contains only one value you have to type a trailing comma.
>>> a = (123)
>>> a
123
>>> type(a)
<type 'int'>
>>> a = (123, ) #Look at the trailing comma
>>> a
(123,)
>>> type(a)
<type 'tuple'>
Using the buitin function type() you can know the data type of any variable. Remember the len() function we used to find the length of any sequence ?
>>> type(len)
<type 'bulletin_function_or_method'>

7.5. Sets

Sets are another type of data structure with no duplicate items. We can also mathematical set operations on sets.
>>> a = set('abcthabcjwethddda')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 't', 'w'])
And some examples of the set operations
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                              # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                              # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                              # letters in both a and b
set(['a', 'c'])
>>> a ^ b                              # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
To add or pop values from a set
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 't', 'w'])
>>> a.add('p')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 'p', 't', 'w'])

7.6. Dictionaries

Dictionaries are unordered set of key: value pairs where keys are unique. We declare dictionaries using {} braces. We use dictionaries to store data for any particular key and then retrieve them.
>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_']
'Debian'
We can add more data to it by simply
>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
To delete any particular key:value pair
>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'
To check if any key is there in the dictionary or not you can use has_key() or in keyword.
>>> data.has_key('Soumya')
False
>>> 'Soumya' in data
False
You must remember that no mutable object can be a key, that means you can not use a list as a key.
dict() can create dictionaries from tuples of key,value pair.
>>> dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
{'Indian': 'Delhi', 'Bangladesh': 'Dhaka'}
If you want to loop through a dict use iteritems() method.
>>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.iteritems():
...     print "%s uses %s" % (x, y)
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu
If you want to loop through a list (or any sequence) and get iteration number at the same time you have to use enumerate().
>>> for i, j in enumerate(['a', 'b', 'c']):
...     print i, j
...
0 a
1 b
2 c
You may also need to iterate through two sequences same time, for that use zip() function.
>>> a = ['Pradeepto', 'Kushal']
>>> b = ['OpenSUSE', 'Fedora']
>>> for x, y in zip(a, b):
...     print "%s uses %s" % (x, y)
...
Pradeepto uses OpenSUSE
Kushal uses Fedora

7.7. students.py

In this example , you have to take number of students as input , then ask marks for three subjects as 'Physics', 'Maths', 'History', if the total number for any student is less 120 then print he failed, or else say passed.
#!/usr/bin/env python
n = int(raw_input("Enter the number of students:"))
data = {} # here we will store the data
languages = ('Physics', 'Maths', 'History') #all languages
for i in range(0, n): #for the n number of students
    name = raw_input('Enter the name of the student %d: ' % (i + 1)) #Get the name of the student
    marks = []
    for x in languages:
        marks.append(int(raw_input('Enter marks of %s: ' % x))) #Get the marks for  languages
    data[name] = marks
for x, y in data.iteritems():
    total =  sum(y)
    print "%s 's  total marks %d" % (x, total)
    if total < 120:
        print "%s failed :(" % x
    else:
        print "%s passed :)" % y
The output
[kd@kdlappy book]$ ./students.py
Enter the number of students:2
Enter the name of the student 1: Babai
Enter marks of Physics: 12
Enter marks of Maths: 45
Enter marks of History: 40
Enter the name of the student 2: Ria
Enter marks of Physics: 89
Enter marks of Maths: 98
Enter marks of History: 40
Babai 's  total marks 97
Babai failed :(
Ria 's  total marks 227
Ria passed :)

7.8. matrixmul.py

In this example we will multiply two matrix's. First we will take input the number of rows/columns in the matrix (here we assume we are using n x n matrix). Then values of the matrix's.
#!/usr/bin/env python
n = int(raw_input("Enter the value of n: "))
print "Enter values for the Matrix A"
a = []
for i in range(0, n):
    a.append([int(x) for x in raw_input("").split(" ")])
print "Enter values for the Matrix B"
b = []
for i in range(0, n):
    b.append([int(x) for x in raw_input("").split(" ")])
c = []
for i in range(0, n):
    c.append([a[i][j] * b[j][i] for j in range(0,n)])
print "After matrix multiplication"
print "-" * 10 * n
for x in c:
    for y in x:
        print "%5d" % y,
    print ""
print "-" * 10 * n
The output
[kd@kdlappy book]$ ./matrixmul.py
Enter the value of n: 3
Enter values for the Matrix A
1 2 3
4 5 6
7 8 9
Enter values for the Matrix B
9 8 7
6 5 4
3 2 1
After matrix multiplication
------------------------------
    9    12     9
   32    25    12
   49    32     9
------------------------------
Here we have used list comprehensions couple of times. [int(x) for x in raw_input("").split(" ")] here first it takes the input as string by raw_input(), then split the result by " ", then for each value create one int. We are also using [a[i][j] * b[j][i] for j in range(0,n)] to get the resultant row in a single line.

第 8 章 Strings

Strings are nothing but simple text. In python we declare strings in between "" or '' or ''' ''' or """ """. The examples below will help you to understand sting in a better way.

>
>
> s = "I am Indian"

>
>
> s
'I am Indian'

>
>
> s = 'I am Indian'

>
>
> s = "Here is a line \
... splitted in two lines"

>
>
> s
'Here is a line splitted in two lines'

>
>
> s = "Here is a line \n splitted in two lines"

>
>
> s
'Here is a line \n splitted in two lines'

>
>
> print s
Here is a line
 splitted in two lines
Now if you want to multiline strings you have to use triple single/double quotes.

>
>
> s = """ This is a
... multiline string, so you can
... write many lines"""

>
>
> print s
 This is a
multiline string, so you can
write many lines

8.1. Different methods available for Strings

Every string object is having couple of buildin methods available, we already saw some of them like s.split(" ").

>
>
> s = "kushal das"

>
>
> s.title()
'Kushal Das'
title() method returns a titlecased version of the string, words start with uppercase characters, all remaining cased characters are lowercase.

>
>
> z = s.upper()

>
>
> z
'KUSHAL DAS'

>
>
> z.lower()
'kushal das'
upper() returns a total uppercase version whereas lower() returns a lower case version of the string.

>
>
> s = "I am A pRoGraMMer"

>
> s.swapcase()
'i AM a PrOgRAmmER'
swapcase() returns the string with case swapped :)

>
>
> s = "jdwb 2323bjb"

>
>
> s.isalnum()
False

>
>
> s = "jdwb2323bjb"

>
>
> s.isalnum()
True
Because of the space in the first line isalnum() returned False , it checks for all charecters are alpha numeric or not.

>
>
> s = "SankarshanSir"

>
>
> s.isalpha()
True

>
>
> s = "Sankarshan Sir"

>
>
> s.isalpha()
False
isalpha() checkes for only alphabets.

>
>
> s = "1234"

>
>
> s.isdigit() #To check if all the characters are digits or not
True

>
>
> s = "Fedora9 is coming"

>
>
> s.islower() # To check if all chracters are lower case or not
False

>
>
> s = "Fedora9 Is Coming" 

>
>
> s.istitle() # To check if it is a title or not
True

>
>
> s = "INDIA"

>
>
> s.isupper() # To check if characters are in upper case or not
True
To split any string we have split(). It takes a string as an argument , depending on that it will split the main string and returns a list containing splitted strings.

>
>
> s = "We all love Python"

>
>
> s.split(" ")
['We', 'all', 'love', 'Python']

>
>
> x = "Nishant:is:waiting"

>
>
> x.split(':')
['Nishant', 'is', 'waiting']
The opposite method for split() is join(). It takes a list contains strings as input and join them.

>
>
> "-".join("GNU/Linux is great".split(" "))
'GNU/Linux-is-great'
In the above example first we are splitting the string "GNU/Linux is great" based on the white space, then joining them with "-".

8.2. String the strings

Strings do have few methods to do striping. The simplest one is strip(chars). If you provide the chars argument then it will strip any combination of them. By default it strips only whitespace or newline characters.

>
>
> s = "  abc\n "

>
>
> s.strip()
'abc'
You can particularly strip from the left hand or right hand side also using lstrip(chars) or rstrip(chars).

>
>
> s = "www.foss.in"

>
>
> s.lstrip("cwsd.")
'foss.in'

>
>
> s.rstrip("cnwdi.")
'www.foss'

8.3. Finding text

Stings have some methods which will help you in finding text/substring in a string. Examples are given below:

>
>
> s.find("for")
7

>
>
> s.find("fora")
-1

>
>
> s.startswith("fa") #To check if the string startswith fa or not
True

>
>
> s.endswith("reason") #
True
find() helps to find the first occurrence of the substring given, if not found it returns -1.

8.4. Palindrome checking

Palindrome are the kind of strings which are same from left or right whichever way you read them. Example "madam". In this example we will take the word as input from the user and say if it is palindrome or not.
#!/usr/bin/env python
s = raw_input("Please enter a string: ")
z = [x for x in s]
z.reverse()
if s == "".join(z):
    print "The string is a palindrome"
else:
    print "The string is not a palindrome"
The output
[kd@kdlappy book]$ ./palindrome.py
Please enter a string: madam1
The string is not a palindrome
[kd@kdlappy book]$ ./palindrome.py
Please enter a string: madam
The string is a palindrome

8.5. Number of words

In this example we will count the number of words in a given line
#!/usr/bin/env python
s = raw_input("Enter a line: ")
print "The number of words in the line are %d" % (len(s.split(" ")))
The output
[kd@kdlappy book]$ ./countwords.py
Enter a line: Sayamindu is a great programmer
The number of words in the line are 5

第 9 章 Functions

Reusing the same code is required many times within a same program. Functions help us to do so. We write the things we have to do repeatedly in a function then call it where ever required. We already saw build in functions like len(), divmod().

9.1. Defining a function

We use def keyword to define a function. general syntax is like
def functionname(params):
    statement1
    statement2
Let us write a function which will take two integers as input and then return the sum.

>
>
> def sum(a, b):
...     return a + b
In the second line with the return keyword, we are sending back the value of a + b to the caller. You must call it like

>
>
> res = sum(234234, 34453546464)

>
>
> res
34453780698L
Remember the palindrome program we wrote in the last chapter. Let us write a function which will check if a given string is palindrome or not, then return True or False.
#!/usr/bin/env python
def palindrome(s):
    z = s
    z = [x for x in z]
    z.reverse()
    if s == "".join(z):
        return True
    else:
        return False
s = raw_input("Enter a string: ")
if palindrome(s):
    print "Yay a palindrome"
else:
    print "Oh no, not a palindrome"
Now run the code :)

9.2. Local and global variables

To understand local and global variables we will go through two examples.
#!/usr/bin/env python
def change(b):
    a = 90
    print a
a = 9
print "Before the function call ", a
print "inside change function",
change(a)
print "After the function call ", a
The output
[kd@kdlappy book]$ ./local.py
Before the function call  9
inside change function 90
After the function call  9
First we are assigning 9 to a, then calling change function, inside of that we are assigning 90 to a and printing a. After the function call we are again printing the value of a. When we are writing a = 90 inside the function, it is actually creating a new variable called a, which is only available inside the function and will be destroyed after the function finished. So though the name is same for the variable a but they are different in and out side of the function.
#!/usr/bin/env python
def chvariable ange(b):
    global a
    a = 90
    print a
a = 9
print "Before the function call ", a
print "inside change function",
change(a)
print "After the function call ", a
Here by using global keyword we are telling that a is globally defined, so when we are changing a's value inside the function it is actually changing for the a outside of the function also.

9.3. Default argument value

In a function variables may have default argument values, that means if we don't give any value for that particular variable it will assigned automatically.

>
>
> def test(a , b = -99):
...     if a 
> b:
...         return True
...     else:
...         return False
In the above example we have written b = -99 in the function parameter list. That means of no value for b is given then b's value is -99. This is a very simple example of default arguments. You can test the code by

>
>
> test(12, 23)
False

>
>
> test(12)
True

Important

Remember that you can not have an argument without default argument if you already have one argument with default values before it. Like f(a, b=90, c) is illegal as b is having a default value but after that c is not having any default value.
Also remember that default value is evaluated only once, so if you have any mutable object like list it will make a difference. See the next example

>
>
> def f(a, data=[]):
...     data.append(a)
...     return data
...

>
>
> print f(1)
[1]

>
>
> print f(2)
[1, 2]

>
>
> print f(3)
[1, 2, 3]

9.4. Keyword arguments


>
>
> def func(a, b=5, c=10):
...     print 'a is', a, 'and b is', b, 'and c is', c
...

>
>
> func(12, 24)
a is 12 and b is 24 and c is 10

>
>
> func(12, c = 24)
a is 12 and b is 5 and c is 24

>
>
> func(b=12, c = 24, a = -1)
a is -1 and b is 12 and c is 24
In the above example you can see we are calling the function with variable names, like func(12, c = 24), by that we are assigning 24 to c and b is getting its default value. Also remember that you can not have without keyword based argument after a keyword based argument. like

>
>
> def func(a, b=13, v):
...     print a, b, v
...
  File "<stdin
>", line 1
SyntaxError: non-default argument follows default argument

第 10 章 File handling

A file is some information or data which stays in the computer storage devices. You already know about different kinds of file , like your music files, video files, text files. Python gives you easy ways to manipulate these files. Generally we divide files in two categories, text file and binary file. Text files are simple text where as the binary files contain binary data which is only readable by computer.

10.1. File opening

To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open. Modes are like
"r" -> open read only, you can read the file but can not edit / delete anything inside
"w" -> open with write power, means if the file exists then delete all content and open it to write
"a" -> open in append mode
The default mode is read only, ie if you do not provide any mode it will open the file as read only. Let us open a file

>
>
> f = open("love.txt")

>
>
> f
<open file 'love.txt', mode 'r' at 0xb7f2d968>

10.2. Reading a file

To read the whole file at once use the read() method.

>
>
> f = open("sample.txt")

>
>
> f.read()
'I love Python\nPradeepto loves KDE\nSankarshan loves Openoffice\n'
If you call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file.

>
>
> f = open("sample.txt")

>
>
> f.readline()
'I love Python\n'

>
>
> f.readline()
'Pradeepto loves KDE\n'
To read all the all the lines in a list we use readlines() method.

>
>
> f = open("sample.txt")

>
>
> f.readlines()
['I love Python\n', 'Pradeepto loves KDE\n', 'Sankarshan loves Openoffice\n']
You can even loop through the lines in a file object.

>
>
> f = open("sample.txt")

>
>
> for x in f:
...     print x,
...
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice
Let us write a program which will take the file name as the input from the user and show the content of the file in the console.
#!/usr/bin/env python
name = raw_input("Enter the file name: ")
f = open(name)
print f.read()
f.close()
In the last line you can see that we closed the file object with the help of close() method.
The output
[kd@kdlappy book]$ ./showfile.py
Enter the filename: sample.txt
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice

10.3. Writing in a file

Let us open a file then we will write some random text into it by using the write() method.

>
>
> f = open("ircnicks.txt", 'w')

>
>
> f.write('powerpork\n')

>
>
> f.write('indrag\n')

>
>
> f.write('mishti\n')

>
>
> f.write('sm|CPU')

>
>
> f.close()
Now read the file we just created

>
>
> f = open('ircnicks.txt')

>
>
> s = f.read()

>
>
> print s
powerpork
indrag
mishti
sm|CPU

10.4. copyfile.py

In this example we will copy a given file to another file.
#!/usr/bin/env python
import sys
if len(sys.argv) < 3:
    print "Wrong parameter"
    print "./copyfile.py file1 file2"
    sys.exit(1)
f1 = open(sys.argv[1])
s = f1.read()
f1.close()
f2 = open(sys.argv[2], 'w')
f2.write(s)
f2.close()
You can see we used a new module here sys. sys.argv contains all command line parameters. Remember cp command in shell, after cp we type first the file to be copied and then the new file name.
The first value in sys.argv is the name of the command itself.
#!/usr/bin/env python
import sys
print "First value", sys.argv[0]
print "All values"
for i, x  in enumerate(sys.argv):
    print i, x
The output
[kd@kdlappy book]$ ./argvtest.py Hi there
First value ./argvtest.py
All values
0 ./argvtest.py
1 Hi
2 there
Here we used a new function enumerate(iterableobject), which returns the index number and the value from the iterable object.

10.5. Random seeking in a file

You can also randomly move around inside a file using seek() method. It takes two arguments , offset and whence. To know more about it let us read what python help tells us
seek(...) seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are speakable.
Let us see one example

>
>
> f = open('tempfile', 'w')

>
>
> f.write('0123456789abcdef')

>
>
> f.close()

>
>
> f = open('tempfile')

>
>
> f.tell()    #tell us the offset position
0L

>
>
> f.seek(5) # Goto 5th byte

>
>
> f.tell()
5L

>
>
> f.read(1) #Read 1 byte
'5'

>
>
> f.seek(-3, 2) # goto 3rd byte from the end

>
>
> f.read() #Read till the end of the file
'def'

第 11 章 感​谢​

我​感​谢​下​面​的​人​们​,他​们​对​这​本​书​的​帮​助​很​大​,尤​其​是​IRC站​点​irc.freenode.net上​的​频​道​#fedora-docs 和​#fedora-art,名​字​按​照​字​母​顺​序​排​列​:
  • Jared Smith
  • Marco Mornati
  • Nicu Buculei
  • Paul W. Frields
  • Pradeepto K Bhattacharya
  • Sankarshan Mukhopadhyay
  • Sayamindu Dasgupta
  • Stephanie Whiting
在​以​上​列​表​中​落​下​了​一​些​人​,我​将​在​不​久​的​将​来​会​补​上​
我​从​以​下​站​点​获​得​许​多​帮​助​
  • http://docs.python.org
  • http://en.wikipedia.org
一​些​我​推​荐​的​书​和​站​点

Revision History

修订历史
修订 0.1Kushal
Das
First release
Publican