├── 2code ├── __init__.py ├── 23501.txt ├── 23502.txt ├── stdout.md ├── 22901.dat ├── pm.pyc ├── pp.pyc ├── 22901.db ├── 23301.db ├── 22903.dat ├── 23401.xlsx ├── newtemp.py ├── 23301.sqlite ├── 22102.py ├── fractal-tree.png ├── 20801p3.py ├── 24201.py ├── 20703p3.py ├── 20703.py ├── 22101.py ├── 22102p3.py ├── 24202.py ├── pm.py ├── 20403.py ├── 21501.py ├── 23504.py ├── 20402.py ├── 21302.py ├── 20401.py ├── 21703.py ├── 21703p3.py ├── 20202.py ├── 20702.py ├── 20704.py ├── 22501.py ├── pp.py ├── 20503.py ├── 23501.py ├── 21602.py ├── 23901p3.py ├── 23901.py ├── 22103.py ├── 20901.py ├── 20904.py ├── 24001p3.py ├── 20902.py ├── 21601p3.py ├── 22601.xml ├── 21101.py ├── 21801.py ├── 20902_1.py ├── 21402.py ├── 20701p3.py ├── 21601.py ├── 21001.py ├── 21102.py ├── 20701.py ├── 20903.py ├── 20905p3.py ├── 21401p3.py ├── 20501p3.py ├── 20905.py ├── 23503.py ├── 20501.py ├── 23502.py ├── 23502p3.py ├── 21702.py ├── 21701.py ├── 21401.py ├── 21301.py ├── 22701.py ├── 20502.py └── 20502p3.py ├── 3code ├── web │ ├── handlers │ │ ├── __init__.py │ │ ├── base.pyc │ │ ├── user.pyc │ │ ├── index.pyc │ │ ├── sleep.pyc │ │ ├── __init__.pyc │ │ ├── base.py │ │ ├── sleep.py │ │ ├── user.py │ │ └── index.py │ ├── methods │ │ ├── __init__.py │ │ ├── db.pyc │ │ ├── readdb.pyc │ │ ├── __init__.pyc │ │ ├── db.py │ │ └── readdb.py │ ├── statics │ │ ├── css │ │ │ └── style.css │ │ └── js │ │ │ └── script.js │ ├── url.pyc │ ├── application.pyc │ ├── templates │ │ ├── see.html │ │ ├── sleep.html │ │ ├── error.html │ │ ├── user.html │ │ ├── index.html │ │ ├── register.html │ │ └── base.html │ ├── application.py │ ├── url.py │ └── server.py ├── marks.xlsx ├── marks.csv ├── hello.py └── 31301.py ├── python3code ├── chapter06 │ ├── mypackage │ │ ├── __init__.py │ │ ├── A │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── abasic.cpython-36.pyc │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ └── apython.cpython-36.pyc │ │ │ ├── apython.py │ │ │ └── abasic.py │ │ ├── B │ │ │ ├── __init__.py │ │ │ ├── brust.py │ │ │ └── __pycache__ │ │ │ │ ├── brust.cpython-36.pyc │ │ │ │ └── __init__.cpython-36.pyc │ │ └── __pycache__ │ │ │ └── __init__.cpython-36.pyc │ ├── __pycache__ │ │ └── moduleexample.cpython-36.pyc │ ├── exampleimport.py │ ├── exit_file.py │ ├── sys_file.py │ ├── pp.py │ └── moduleexample.py ├── chapter01 │ ├── helloworld.py │ ├── simplemath.py │ └── nameage.py ├── chapter02 │ ├── my.txt │ ├── txtfile.txt │ ├── py.txt │ ├── aliquot.py │ ├── whileelse.py │ ├── evenbreak.py │ ├── forelse.py │ ├── evencontinue.py │ ├── judgenumber.py │ └── guessnumber.py ├── chapter03 │ ├── foo1.py │ ├── foo2.py │ ├── parabola.py │ ├── firstfunc.py │ ├── fibs.py │ ├── fibsbetter.py │ ├── fibs_rec.py │ ├── weight.py │ └── decorate.py ├── chapter04 │ ├── convert2g.py │ ├── fibsyield.py │ ├── gcdlcm.py │ ├── simlist.py │ ├── definefraction.py │ ├── private.py │ ├── singleton.py │ ├── roundfloat.py │ ├── multi_inhance.py │ ├── mro.py │ ├── myrange.py │ ├── about_self.py │ ├── fibsiterator.py │ ├── rectangle1.py │ ├── simdict.py │ ├── rectangle2.py │ ├── addfractions.py │ ├── schoolwork.py │ └── temperature.py └── chapter05 │ ├── tryelse.py │ ├── calculator.py │ ├── tryexceptccb.py │ ├── customexception.py │ ├── account.py │ └── try_except.py ├── newfiles ├── txtfile.txt ├── p.dat ├── sp.db ├── lite.db ├── p2.dat ├── p3.dat ├── mdfile.md └── you.md ├── 1code ├── helloworld.py ├── 130.txt ├── 110_2.py ├── 127.txt ├── 110_3.py ├── simplemath.py ├── 105-1.py ├── 12904.py ├── 12901.py ├── aliquot.py ├── 12701.py ├── 12503p3.py ├── 12502p3.py ├── 12905.py ├── 12905_2.py ├── simplewhileloop.py ├── 12501.py ├── simplewhileloop2.py ├── 12903.py ├── 107.py ├── nameage.py ├── chartoint.py ├── you.md ├── judgenumber.py ├── 122p3.py ├── 12902.py ├── guessnumber.py └── guessnumber2.py ├── 0images ├── 01.jpg ├── n00201.png └── n00401.png ├── 1images ├── 10101.png ├── 10102.png ├── 10103.png ├── 10201.jpg ├── 10501.png ├── 10502.png ├── 10503.png ├── 10504.png ├── 10505.png ├── 10506.png ├── 10507.png ├── 10508.jpg ├── 10901.png ├── 11001.png ├── 11002.png ├── 11901.png ├── 11902.png ├── 11903.png ├── 11904.png ├── 12201.png ├── 12301.png ├── 12501.png ├── 12601.png ├── 12602.png └── 12603.png ├── 2images ├── 20101.png ├── 20102.png ├── 20401.png ├── 20801.png ├── 20802.png ├── 20803.png ├── 21001.png ├── 21002.png ├── 22301.jpg ├── 22302.jpg ├── 22303.jpg ├── 22304.jpg ├── 22305.jpg ├── 22306.jpg ├── 22307.jpg ├── 22308.jpg ├── 22309.jpg ├── 22310.jpg ├── 22311.jpg ├── 22501.jpg ├── 22601.jpg ├── 23201.jpg ├── 23401.jpg └── 23402.jpg ├── 3images ├── 30201.png ├── 30202.png ├── 30301.png ├── 30401.png ├── 30402.png ├── 30403.png ├── 30404.png ├── 30405.png ├── 30501.png ├── 30502.png ├── 30503.png ├── 30504.png ├── 30601.png ├── 30602.png ├── 30603.png ├── 30604.png ├── 30701.png ├── 30702.png ├── 30703.png ├── 30704.png ├── 30901.png ├── 31001.png ├── 31002.png ├── 31003.png ├── 31004.png ├── 31005.png ├── 31006.png ├── 31007.png ├── 31101.png ├── 31102.png ├── 31103.png ├── 31104.png ├── 31105.png ├── 31106.png ├── 31107.png ├── 31108.png ├── 31109.png ├── 31110.png ├── 31111.png ├── 31112.png ├── 31113.png ├── 31114.png ├── 31115.png ├── 31116.png ├── 31117.png ├── 31118.png ├── 31301.png └── 31302.png ├── fib ├── .fib02.py.swp ├── fib02.py ├── fib04.py ├── fib03.py └── fib01.py ├── python-book1.png ├── nimages └── n005-01.png ├── .vscode └── settings.json ├── newcodes ├── __pycache__ │ └── pm.cpython-34.pyc ├── pm.py ├── exit_file.py ├── answers │ ├── q12.py │ ├── q58-2.py │ ├── q8.py │ ├── q46.py │ ├── q15.py │ ├── q17.py │ ├── q37.py │ ├── q47.py │ ├── q16.py │ ├── q13.py │ ├── q56.py │ ├── q26.py │ ├── q31.py │ ├── q60.py │ ├── q40-2.py │ ├── q39.py │ ├── q67.py │ ├── q59.py │ ├── q22-2.py │ ├── youraisemeup.txt │ ├── q62.py │ ├── q29.py │ ├── q49.py │ ├── q42.py │ ├── q40.py │ ├── q22.py │ ├── q41.py │ ├── q57.py │ ├── q66.py │ ├── q38.py │ ├── q71.py │ ├── q58.py │ ├── q70.py │ ├── q68.py │ ├── q48.py │ ├── q43.py │ ├── q64.py │ ├── q35.py │ ├── q21.py │ ├── q34.py │ ├── q53.py │ ├── q61.py │ ├── q63.py │ ├── q74.py │ ├── q65.py │ ├── q44.py │ ├── q69.py │ ├── q45.py │ ├── q76.py │ ├── q73.py │ ├── q72.py │ ├── q50.py │ └── q75.py ├── nest_func1.py ├── sys_file.py ├── add_function.py ├── nest_func2.py ├── fibs_rec.py ├── weight.py ├── wrap1.py ├── cal_power.py ├── fibs.py ├── try_else.py ├── fibs_yield.py ├── round_float.py ├── calculator.py ├── myrange.py ├── docktest.py ├── private.py ├── mro.py ├── multi_inhance.py ├── class_method.py ├── fibs_iter.py ├── static_method.py ├── about_self.py ├── normal_rectangle.py ├── try_except.py ├── account.py ├── single_inhance.py ├── special_rectangle.py └── fraction.py ├── README.md ├── videolesson ├── country.py ├── odd_even.py ├── judge_input.py ├── newton.py └── arithmetic.py ├── n001.md ├── n004.md ├── n002.md ├── n003.md └── index.md /2code/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /3code/web/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /3code/web/methods/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /newfiles/txtfile.txt: -------------------------------------------------------------------------------- 1 | do you know canglaoshi? 2 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/B/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /2code/23501.txt: -------------------------------------------------------------------------------- 1 | hello laoqi 2 | www.itdiffer.com 3 | -------------------------------------------------------------------------------- /2code/23502.txt: -------------------------------------------------------------------------------- 1 | hello laoqi 2 | www.itdiffer.com 3 | -------------------------------------------------------------------------------- /2code/stdout.md: -------------------------------------------------------------------------------- 1 | Learn Python: From Beginner to Master 2 | -------------------------------------------------------------------------------- /2code/22901.dat: -------------------------------------------------------------------------------- 1 | (lp0 2 | I1 3 | aI2 4 | aI3 5 | aI4 6 | aI5 7 | a. -------------------------------------------------------------------------------- /1code/helloworld.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | 3 | print("Hello, World") 4 | -------------------------------------------------------------------------------- /3code/web/statics/css/style.css: -------------------------------------------------------------------------------- 1 | 2 | body { 3 | color:red; 4 | } 5 | -------------------------------------------------------------------------------- /1code/130.txt: -------------------------------------------------------------------------------- 1 | learn python 2 | http://qiwsir.github.io 3 | qiwsir@gmail.com 4 | -------------------------------------------------------------------------------- /python3code/chapter01/helloworld.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | 3 | print("Hello, World") -------------------------------------------------------------------------------- /2code/pm.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/pm.pyc -------------------------------------------------------------------------------- /2code/pp.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/pp.pyc -------------------------------------------------------------------------------- /0images/01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/0images/01.jpg -------------------------------------------------------------------------------- /1code/110_2.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1code/110_2.py -------------------------------------------------------------------------------- /1code/127.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1code/127.txt -------------------------------------------------------------------------------- /2code/22901.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/22901.db -------------------------------------------------------------------------------- /2code/23301.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/23301.db -------------------------------------------------------------------------------- /newfiles/p.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newfiles/p.dat -------------------------------------------------------------------------------- /newfiles/sp.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newfiles/sp.db -------------------------------------------------------------------------------- /python3code/chapter02/my.txt: -------------------------------------------------------------------------------- 1 | learn python 2 | http://itdiffer.com 3 | qq group: 26913719 4 | -------------------------------------------------------------------------------- /python3code/chapter02/txtfile.txt: -------------------------------------------------------------------------------- 1 | Life is short, you need python. 2 | Aha, I like program. -------------------------------------------------------------------------------- /1images/10101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10101.png -------------------------------------------------------------------------------- /1images/10102.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10102.png -------------------------------------------------------------------------------- /1images/10103.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10103.png -------------------------------------------------------------------------------- /1images/10201.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10201.jpg -------------------------------------------------------------------------------- /1images/10501.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10501.png -------------------------------------------------------------------------------- /1images/10502.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10502.png -------------------------------------------------------------------------------- /1images/10503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10503.png -------------------------------------------------------------------------------- /1images/10504.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10504.png -------------------------------------------------------------------------------- /1images/10505.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10505.png -------------------------------------------------------------------------------- /1images/10506.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10506.png -------------------------------------------------------------------------------- /1images/10507.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10507.png -------------------------------------------------------------------------------- /1images/10508.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10508.jpg -------------------------------------------------------------------------------- /1images/10901.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/10901.png -------------------------------------------------------------------------------- /1images/11001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11001.png -------------------------------------------------------------------------------- /1images/11002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11002.png -------------------------------------------------------------------------------- /1images/11901.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11901.png -------------------------------------------------------------------------------- /1images/11902.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11902.png -------------------------------------------------------------------------------- /1images/11903.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11903.png -------------------------------------------------------------------------------- /1images/11904.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/11904.png -------------------------------------------------------------------------------- /1images/12201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12201.png -------------------------------------------------------------------------------- /1images/12301.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12301.png -------------------------------------------------------------------------------- /1images/12501.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12501.png -------------------------------------------------------------------------------- /1images/12601.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12601.png -------------------------------------------------------------------------------- /1images/12602.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12602.png -------------------------------------------------------------------------------- /1images/12603.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/1images/12603.png -------------------------------------------------------------------------------- /2code/22903.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/22903.dat -------------------------------------------------------------------------------- /2code/23401.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/23401.xlsx -------------------------------------------------------------------------------- /2code/newtemp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | print "This is a tmp file." 5 | -------------------------------------------------------------------------------- /2images/20101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20101.png -------------------------------------------------------------------------------- /2images/20102.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20102.png -------------------------------------------------------------------------------- /2images/20401.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20401.png -------------------------------------------------------------------------------- /2images/20801.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20801.png -------------------------------------------------------------------------------- /2images/20802.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20802.png -------------------------------------------------------------------------------- /2images/20803.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/20803.png -------------------------------------------------------------------------------- /2images/21001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/21001.png -------------------------------------------------------------------------------- /2images/21002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/21002.png -------------------------------------------------------------------------------- /2images/22301.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22301.jpg -------------------------------------------------------------------------------- /2images/22302.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22302.jpg -------------------------------------------------------------------------------- /2images/22303.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22303.jpg -------------------------------------------------------------------------------- /2images/22304.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22304.jpg -------------------------------------------------------------------------------- /2images/22305.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22305.jpg -------------------------------------------------------------------------------- /2images/22306.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22306.jpg -------------------------------------------------------------------------------- /2images/22307.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22307.jpg -------------------------------------------------------------------------------- /2images/22308.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22308.jpg -------------------------------------------------------------------------------- /2images/22309.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22309.jpg -------------------------------------------------------------------------------- /2images/22310.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22310.jpg -------------------------------------------------------------------------------- /2images/22311.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22311.jpg -------------------------------------------------------------------------------- /2images/22501.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22501.jpg -------------------------------------------------------------------------------- /2images/22601.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/22601.jpg -------------------------------------------------------------------------------- /2images/23201.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/23201.jpg -------------------------------------------------------------------------------- /2images/23401.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/23401.jpg -------------------------------------------------------------------------------- /2images/23402.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2images/23402.jpg -------------------------------------------------------------------------------- /3code/marks.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/marks.xlsx -------------------------------------------------------------------------------- /3code/web/url.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/url.pyc -------------------------------------------------------------------------------- /3images/30201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30201.png -------------------------------------------------------------------------------- /3images/30202.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30202.png -------------------------------------------------------------------------------- /3images/30301.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30301.png -------------------------------------------------------------------------------- /3images/30401.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30401.png -------------------------------------------------------------------------------- /3images/30402.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30402.png -------------------------------------------------------------------------------- /3images/30403.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30403.png -------------------------------------------------------------------------------- /3images/30404.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30404.png -------------------------------------------------------------------------------- /3images/30405.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30405.png -------------------------------------------------------------------------------- /3images/30501.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30501.png -------------------------------------------------------------------------------- /3images/30502.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30502.png -------------------------------------------------------------------------------- /3images/30503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30503.png -------------------------------------------------------------------------------- /3images/30504.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30504.png -------------------------------------------------------------------------------- /3images/30601.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30601.png -------------------------------------------------------------------------------- /3images/30602.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30602.png -------------------------------------------------------------------------------- /3images/30603.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30603.png -------------------------------------------------------------------------------- /3images/30604.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30604.png -------------------------------------------------------------------------------- /3images/30701.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30701.png -------------------------------------------------------------------------------- /3images/30702.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30702.png -------------------------------------------------------------------------------- /3images/30703.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30703.png -------------------------------------------------------------------------------- /3images/30704.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30704.png -------------------------------------------------------------------------------- /3images/30901.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/30901.png -------------------------------------------------------------------------------- /3images/31001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31001.png -------------------------------------------------------------------------------- /3images/31002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31002.png -------------------------------------------------------------------------------- /3images/31003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31003.png -------------------------------------------------------------------------------- /3images/31004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31004.png -------------------------------------------------------------------------------- /3images/31005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31005.png -------------------------------------------------------------------------------- /3images/31006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31006.png -------------------------------------------------------------------------------- /3images/31007.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31007.png -------------------------------------------------------------------------------- /3images/31101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31101.png -------------------------------------------------------------------------------- /3images/31102.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31102.png -------------------------------------------------------------------------------- /3images/31103.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31103.png -------------------------------------------------------------------------------- /3images/31104.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31104.png -------------------------------------------------------------------------------- /3images/31105.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31105.png -------------------------------------------------------------------------------- /3images/31106.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31106.png -------------------------------------------------------------------------------- /3images/31107.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31107.png -------------------------------------------------------------------------------- /3images/31108.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31108.png -------------------------------------------------------------------------------- /3images/31109.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31109.png -------------------------------------------------------------------------------- /3images/31110.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31110.png -------------------------------------------------------------------------------- /3images/31111.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31111.png -------------------------------------------------------------------------------- /3images/31112.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31112.png -------------------------------------------------------------------------------- /3images/31113.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31113.png -------------------------------------------------------------------------------- /3images/31114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31114.png -------------------------------------------------------------------------------- /3images/31115.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31115.png -------------------------------------------------------------------------------- /3images/31116.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31116.png -------------------------------------------------------------------------------- /3images/31117.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31117.png -------------------------------------------------------------------------------- /3images/31118.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31118.png -------------------------------------------------------------------------------- /3images/31301.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31301.png -------------------------------------------------------------------------------- /3images/31302.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3images/31302.png -------------------------------------------------------------------------------- /fib/.fib02.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/fib/.fib02.py.swp -------------------------------------------------------------------------------- /newfiles/lite.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newfiles/lite.db -------------------------------------------------------------------------------- /newfiles/p2.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newfiles/p2.dat -------------------------------------------------------------------------------- /newfiles/p3.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newfiles/p3.dat -------------------------------------------------------------------------------- /python-book1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python-book1.png -------------------------------------------------------------------------------- /0images/n00201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/0images/n00201.png -------------------------------------------------------------------------------- /0images/n00401.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/0images/n00401.png -------------------------------------------------------------------------------- /2code/23301.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/23301.sqlite -------------------------------------------------------------------------------- /nimages/n005-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/nimages/n005-01.png -------------------------------------------------------------------------------- /2code/22102.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import sys 5 | 6 | sys.exit("hello") 7 | -------------------------------------------------------------------------------- /2code/fractal-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/2code/fractal-tree.png -------------------------------------------------------------------------------- /newfiles/mdfile.md: -------------------------------------------------------------------------------- 1 | Python can help you to be a great programmer. 2 | Are you a PHPer? 3 | I am a Pythoner. -------------------------------------------------------------------------------- /3code/web/methods/db.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/methods/db.pyc -------------------------------------------------------------------------------- /3code/web/application.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/application.pyc -------------------------------------------------------------------------------- /3code/web/handlers/base.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/handlers/base.pyc -------------------------------------------------------------------------------- /3code/web/handlers/user.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/handlers/user.pyc -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3" 3 | } -------------------------------------------------------------------------------- /1code/110_3.py: -------------------------------------------------------------------------------- 1 | #python 3 2 | 3 | import sys 4 | 5 | print(sys.getdefaultencoding()) 6 | 7 | print("《跟老齐学python》值得读") 8 | -------------------------------------------------------------------------------- /3code/web/handlers/index.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/handlers/index.pyc -------------------------------------------------------------------------------- /3code/web/handlers/sleep.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/handlers/sleep.pyc -------------------------------------------------------------------------------- /3code/web/methods/readdb.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/methods/readdb.pyc -------------------------------------------------------------------------------- /3code/web/handlers/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/handlers/__init__.pyc -------------------------------------------------------------------------------- /3code/web/methods/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/3code/web/methods/__init__.pyc -------------------------------------------------------------------------------- /python3code/chapter01/simplemath.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | 3 | """ 4 | 请计算:19+2*4-8/2 5 | """ 6 | 7 | a = 19 + 2 * 4 - 8 / 2 8 | print(a) -------------------------------------------------------------------------------- /1code/simplemath.py: -------------------------------------------------------------------------------- 1 | #coding: utf-8 2 | 3 | """ 4 | 请计算:19+2*4-8/2 5 | """ 6 | 7 | a = 19 + 2 * 4 - 8 / 2 8 | print(a) 9 | 10 | -------------------------------------------------------------------------------- /newcodes/__pycache__/pm.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/newcodes/__pycache__/pm.cpython-34.pyc -------------------------------------------------------------------------------- /newcodes/pm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | lang = "python" 5 | 6 | if __name__ == "__main__": 7 | print(lang()) 8 | -------------------------------------------------------------------------------- /2code/20801p3.py: -------------------------------------------------------------------------------- 1 | 2 | class Foo: 3 | def __init__(self): 4 | print("I am in init()") 5 | return None 6 | 7 | bar = Foo() 8 | -------------------------------------------------------------------------------- /1code/105-1.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #coding:utf-8 3 | 4 | """ 5 | 请计算: 6 | 19+2*4-8/2 7 | """ 8 | 9 | a = 19+2*4-8/2 10 | print a 11 | -------------------------------------------------------------------------------- /2code/24201.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | a = 3 4 | def bar(): 5 | return a 6 | return bar 7 | 8 | f = foo() 9 | print f() 10 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/B/brust.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | path: ./mypackage/B/brust.py 4 | filename: brust.py 5 | ''' 6 | rust = 'RUST' -------------------------------------------------------------------------------- /1code/12904.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | a, b = 0, 1 5 | 6 | for i in range(4): 7 | a, b = b, a+b 8 | 9 | print a 10 | -------------------------------------------------------------------------------- /3code/marks.csv: -------------------------------------------------------------------------------- 1 | name,physics,python,math,english 2 | Google,100,100,25,12 3 | Facebook,45,54,44,88 4 | Twitter,54,76,13,91 5 | Yahoo,54,452,26,100 6 | -------------------------------------------------------------------------------- /python3code/chapter02/py.txt: -------------------------------------------------------------------------------- 1 | Learn python with qiwsir. 2 | There is free python course. 3 | The website is: 4 | http://qiwsir.github.io 5 | Its language is Chinese. -------------------------------------------------------------------------------- /1code/12901.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | raw = [1,2,3,4,5,6,7,8,9,0] 5 | print raw 6 | b = raw.pop(0) 7 | raw.append(b) 8 | 9 | print raw 10 | -------------------------------------------------------------------------------- /3code/web/templates/see.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

I hope see you just now.

5 | {% end %} 6 | 7 | {% block body %} 8 | {% end %} 9 | -------------------------------------------------------------------------------- /python3code/chapter06/__pycache__/moduleexample.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/__pycache__/moduleexample.cpython-36.pyc -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/__pycache__/abasic.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/A/__pycache__/abasic.cpython-36.pyc -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/apython.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | path: ./mypackage/A/apython.py 4 | firlename: apython.py 5 | ''' 6 | 7 | def python(): 8 | return "PYTHON" 9 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/B/__pycache__/brust.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/B/__pycache__/brust.cpython-36.pyc -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /newcodes/exit_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import sys 5 | 6 | for i in range(10): 7 | if i == 5: 8 | sys.exit() 9 | else: 10 | print(i) 11 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/A/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/__pycache__/apython.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/A/__pycache__/apython.cpython-36.pyc -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/B/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qiwsir/StarterLearningPython/HEAD/python3code/chapter06/mypackage/B/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /1code/aliquot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | aliquot = [] 5 | 6 | for n in range(1, 100): 7 | if n % 3 == 0: 8 | aliquot.append(n) 9 | 10 | print(aliquot) 11 | -------------------------------------------------------------------------------- /2code/20703p3.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | a = 1 3 | def bar(): 4 | nonlocal a 5 | a = a + 1 6 | print("bar()a=",a) 7 | bar() 8 | print("foo()a=",a) 9 | 10 | foo() 11 | -------------------------------------------------------------------------------- /newcodes/answers/q12.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | word = input("please input a word:") 5 | length_word = len(word) 6 | print("the length of {0} is {1}".format(word, length_word)) 7 | -------------------------------------------------------------------------------- /newcodes/nest_func1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def foo(): 5 | def bar(): 6 | print("bar() is running") 7 | bar() 8 | print("foo() is running") 9 | 10 | foo() 11 | -------------------------------------------------------------------------------- /2code/20703.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | def foo(): 5 | def bar(): 6 | print "bar() is running" 7 | bar() 8 | print "foo() is running" 9 | 10 | #foo() 11 | bar() 12 | -------------------------------------------------------------------------------- /2code/22101.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import sys 5 | 6 | print "The file name: ", sys.argv[0] 7 | print "The number of argument", len(sys.argv) 8 | print "The argument is: ", str(sys.argv) 9 | -------------------------------------------------------------------------------- /2code/22102p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import sys 5 | 6 | #sys.exit("hello") 7 | for i in range(10): 8 | if i == 5: 9 | sys.exit() 10 | else: 11 | print(i) 12 | -------------------------------------------------------------------------------- /3code/web/templates/sleep.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

I am sleeping in 7s.

5 | {% end %} 6 | 7 | {% block body %} 8 |

Please waiting

9 | {% end %} 10 | -------------------------------------------------------------------------------- /1code/12701.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | f = open("you.md") 5 | 6 | while True: 7 | line = f.readline() 8 | if not line: 9 | break 10 | print line , 11 | 12 | f.close() 13 | -------------------------------------------------------------------------------- /2code/24202.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | 4 | def parabola(a, b, c): 5 | def para(x): 6 | return a*x**2 + b*x + c 7 | return para 8 | 9 | p = parabola(2, 3, 4) 10 | print p(5) 11 | -------------------------------------------------------------------------------- /1code/12503p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | a = 9 5 | while a: 6 | if a%2 == 0: 7 | a -=1 8 | continue 9 | else: 10 | print("%d is odd number"%a) 11 | a -=1 12 | -------------------------------------------------------------------------------- /newcodes/sys_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import sys 5 | 6 | print("The file name: ", sys.argv[0]) 7 | print("The number of argument", len(sys.argv)) 8 | print("The argument is: ", str(sys.argv)) 9 | -------------------------------------------------------------------------------- /python3code/chapter02/aliquot.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: aliquot.py 4 | ''' 5 | 6 | aliquot = [] 7 | 8 | for n in range(1,100): 9 | if n % 3 == 0: 10 | aliquot.append(n) 11 | 12 | print(aliquot) -------------------------------------------------------------------------------- /python3code/chapter03/foo1.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: foo1.py 4 | ''' 5 | def foo(): 6 | def bar(): 7 | print("bar() is running") 8 | print("foo() is running") 9 | 10 | foo() #调用函数 11 | -------------------------------------------------------------------------------- /python3code/chapter06/exampleimport.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: exampleimport.py 4 | ''' 5 | 6 | from mypackage.A import abasic 7 | 8 | if __name__ == "__main__": 9 | r = abasic.basic 10 | print(r) 11 | -------------------------------------------------------------------------------- /2code/pm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | This is a document of the python module. 6 | """ 7 | 8 | def lang(): 9 | return "python" 10 | 11 | if __name__ == "__main__": 12 | print lang() 13 | -------------------------------------------------------------------------------- /newcodes/add_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | def add_function(a, b): 4 | c = a + b 5 | return c 6 | 7 | if __name__ == "__main__": 8 | result = add_function(2, 3) 9 | print(result) 10 | -------------------------------------------------------------------------------- /python3code/chapter06/exit_file.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename:exit_file.py 4 | ''' 5 | 6 | import sys 7 | 8 | for i in range(10): 9 | if i == 5: 10 | sys.exit() 11 | else: 12 | print(i) 13 | -------------------------------------------------------------------------------- /3code/web/methods/db.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import MySQLdb 5 | 6 | conn = MySQLdb.connect(host="localhost", user="root", passwd="123123", db="qiwsirtest", port=3306, charset="utf8") 7 | 8 | cur = conn.cursor() 9 | -------------------------------------------------------------------------------- /fib/fib02.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # utf-8 3 | 4 | from math import sqrt 5 | 6 | def fib(n): 7 | return ((1+sqrt(5))**n - (1-sqrt(5))**n)/(2**n*sqrt(5)) 8 | 9 | if __name__=="__main__": 10 | f = fib(4) 11 | print(f) 12 | -------------------------------------------------------------------------------- /fib/fib04.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #utf-8 3 | 4 | def fib(n): 5 | a, b = 0, 1 6 | while n > 0: 7 | a, b = b, a + b 8 | n -= 1 9 | return a 10 | 11 | if __name__ == "__main__": 12 | print(fib(4)) 13 | -------------------------------------------------------------------------------- /newcodes/answers/q58-2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def parabola(a, b, c): 5 | def para(x): 6 | return a*x**2 + b*x + c 7 | return para 8 | 9 | p = parabola(2, 3, 4) 10 | x = 3 11 | print(p(3)) 12 | -------------------------------------------------------------------------------- /1code/12502p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | a = 8 5 | while a: 6 | if a%2 == 0: 7 | break 8 | else: 9 | print("%d is odd number"%a) 10 | a = 0 11 | 12 | print("%d is even number"%a) 13 | -------------------------------------------------------------------------------- /newcodes/answers/q8.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | name = input("what is your name?") 5 | age = input("how old are you?") 6 | new_age = int(age) + 10 7 | 8 | print("{0} will be {1} yeas old in ten yeas.".format(name, new_age)) 9 | -------------------------------------------------------------------------------- /1code/12905.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | n = int(raw_input("Enter an interger >=0: ")) 5 | 6 | fact = 1 7 | 8 | for i in range(2, n + 1): 9 | fact = fact * i 10 | 11 | print str(n) + " factorial is " + str(fact) 12 | -------------------------------------------------------------------------------- /2code/20403.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # coding:utf-8 3 | 4 | def convert(func, seq): 5 | return [func(i) for i in seq] 6 | 7 | if __name__ == "__main__": 8 | myseq = (111, 3.14, -9.21) 9 | r = convert(str, myseq) 10 | print r 11 | -------------------------------------------------------------------------------- /3code/web/handlers/base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import tornado.web 5 | 6 | class BaseHandler(tornado.web.RequestHandler): 7 | def get_current_user(self): 8 | return self.get_secure_cookie("user") 9 | 10 | 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 注意:本书已经停止印刷,请学习者转到:《Python完全自学教程》中学习,这是一本开源免费的在线读物,地址:https://github.com/qiwsir/PythonBook 2 | 3 | # 《跟老齐学Python:轻松入门》 4 | 5 | 本项目为《跟老齐学Python:轻松入门》一书的相关代码。此书是为初学Python的朋友而作,在各大网店有售。 6 | 7 | ![](./python-book1.png) 8 | 9 | # 相关资源 10 | -------------------------------------------------------------------------------- /fib/fib03.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # utf-8 3 | 4 | def fib(n): 5 | f = [0, 1] 6 | for i in range(n-2): 7 | f.append(f[-2] + f[-1]) 8 | return f 9 | 10 | if __name__ == "__main__": 11 | lst = fib(4) 12 | print(lst) 13 | -------------------------------------------------------------------------------- /newcodes/answers/q46.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | def ahead_one(): 5 | a = [i for i in range(1,11)] 6 | b = a.pop(0) 7 | a.append(b) 8 | return a 9 | 10 | if __name__ =="__main__": 11 | print(ahead_one()) 12 | -------------------------------------------------------------------------------- /python3code/chapter03/foo2.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: foo2.py 4 | ''' 5 | def foo(): 6 | def bar(): 7 | print("bar() is running") 8 | bar() #显示调用内嵌函数 9 | print("foo() is running") 10 | 11 | foo() 12 | -------------------------------------------------------------------------------- /python3code/chapter03/parabola.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: parabola.py 4 | ''' 5 | 6 | def parabola(a, b, c): 7 | def para(x): 8 | return a*x**2 + b*x + c 9 | return para 10 | 11 | p = parabola(2, 3, 4) 12 | print(p(5)) 13 | -------------------------------------------------------------------------------- /1code/12905_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | n = int(raw_input('Enter an integer >= 0: ')) 5 | 6 | fact = 1 7 | i = 2 8 | while i<=n: 9 | fact = fact * i 10 | i += 1 11 | 12 | print str(n) + " factorial is " + str(fact) 13 | -------------------------------------------------------------------------------- /newcodes/nest_func2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def foo(): 5 | a = 1 6 | def bar(): 7 | nonlocal a 8 | a = a + 1 9 | print("bar()a=", a) 10 | bar() 11 | print("foo()a=", a) 12 | 13 | foo() 14 | -------------------------------------------------------------------------------- /python3code/chapter02/whileelse.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: whileelse.py 4 | ''' 5 | 6 | count = 0 7 | while count < 5: 8 | print(count, " is less than 5") 9 | count = count + 1 10 | else: 11 | print(count, " is not less than 5") 12 | -------------------------------------------------------------------------------- /3code/web/templates/error.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

错误页面

5 | {% end %} 6 | {% block body %} 7 |

你看到这个页面的时候,就说明遇到了某种错误。

8 |

根本的解决知道是认真阅读《零基础学python》的教程,请进入下面的链接地址。

9 | {% end %} 10 | -------------------------------------------------------------------------------- /python3code/chapter06/sys_file.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: sys_file.py 4 | ''' 5 | 6 | import sys 7 | 8 | print("The file name: ", sys.argv[0]) 9 | print("The number of argument", len(sys.argv)) 10 | print("The argument is: ", str(sys.argv)) 11 | -------------------------------------------------------------------------------- /1code/simplewhileloop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | a = 1 5 | while a: 6 | if a%2 == 0: 7 | break 8 | else: 9 | print("{} is odd number".format(a)) 10 | a -= 1 11 | print("{} is even number".format(a)) 12 | 13 | -------------------------------------------------------------------------------- /newcodes/answers/q15.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | lst = ["canglaoshi", "sola", 23, 12, 3.14, [1,2,3]] 5 | print(lst) 6 | new_lst = [] 7 | for i in lst: 8 | if isinstance(i, str): 9 | new_lst.append(i) 10 | 11 | print(new_lst) 12 | -------------------------------------------------------------------------------- /newcodes/answers/q17.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import calendar 5 | 6 | years = range(1840, 2016) 7 | leap_years = [] 8 | for year in years: 9 | if calendar.isleap(year): 10 | leap_years.append(year) 11 | 12 | print(leap_years) 13 | -------------------------------------------------------------------------------- /python3code/chapter03/firstfunc.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: firstfunc.py 4 | ''' 5 | 6 | def add_function(a, b): 7 | ''' 8 | add two objects. 9 | ''' 10 | c = a + b 11 | return c 12 | 13 | result = add_function(2, 3) 14 | print(result) 15 | -------------------------------------------------------------------------------- /1code/12501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from math import sqrt 5 | 6 | for n in range(99, 1, -1): 7 | root = sqrt(n) 8 | if root == int(root): 9 | print n 10 | break 11 | 12 | else: 13 | print "Did not find it!" 14 | 15 | -------------------------------------------------------------------------------- /python3code/chapter03/fibs.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | ''' 3 | filename: fibs.py 4 | ''' 5 | 6 | def fibs(n): 7 | result = [0,1] 8 | for i in range(n-2): 9 | result.append(result[-2] + result[-1]) 10 | return result 11 | 12 | lst = fibs(10) 13 | print(lst) 14 | -------------------------------------------------------------------------------- /1code/simplewhileloop2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | a = 9 5 | while a: 6 | if a%2 == 0: 7 | a -=1 8 | continue #如果是偶数,就返回循环的开始 9 | else: 10 | print("{} is odd number".format(a)) #如果是奇数,就打印出来 11 | a -=1 12 | 13 | -------------------------------------------------------------------------------- /fib/fib01.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fib(n): 5 | if n == 0: 6 | return 0 7 | elif n == 1: 8 | return 1 9 | else: 10 | return fib(n-1) + fib(n-2) 11 | 12 | if __name__=="__main__": 13 | n = fib(4) 14 | print(n) 15 | -------------------------------------------------------------------------------- /1code/12903.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | string = "I love code." 5 | print string 6 | 7 | str_lst = string.split(" ") 8 | print str_lst 9 | 10 | words = [s for s in str_lst if s!=""] 11 | print words 12 | 13 | new_string = " ".join(words) 14 | print new_string 15 | -------------------------------------------------------------------------------- /newcodes/answers/q37.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def interest(p,r,n): 5 | a = p*pow((1+r),n) 6 | return a 7 | 8 | if __name__ == "__main__": 9 | p = 1000 10 | r = 0.05 11 | n = 2 12 | total = interest(p,r,n) 13 | print(round(total, 2)) 14 | -------------------------------------------------------------------------------- /python3code/chapter02/evenbreak.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: evenbreak.py 4 | ''' 5 | 6 | a = 8 7 | while a: 8 | if a%2 == 0: 9 | break 10 | else: 11 | print("{} is odd number".format(a)) 12 | a -= 1 13 | print("{} is even number".format(a)) 14 | -------------------------------------------------------------------------------- /newcodes/answers/q47.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | def odd(x):return x%2==1 5 | def even(x):return x%2==0 6 | 7 | if __name__=="__main__": 8 | test_lst = [7,9,12,5,4,9,8,3,12,89] 9 | print(list(filter(even,test_lst))) 10 | print(list(filter(odd,test_lst))) 11 | -------------------------------------------------------------------------------- /newcodes/fibs_rec.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fib(n): 5 | if n == 0: 6 | return 0 7 | elif n == 1: 8 | return 1 9 | else: 10 | return fib(n-1) + fib(n-2) 11 | 12 | if __name__ == "__main__": 13 | f = fib(3) 14 | print(f) 15 | -------------------------------------------------------------------------------- /python3code/chapter02/forelse.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: forelse.py 4 | ''' 5 | 6 | from math import sqrt 7 | 8 | for n in range(99, 1, -1): 9 | root = sqrt(n) 10 | if root == int(root): 11 | print(n) 12 | break 13 | 14 | else: 15 | print("Nothing.") 16 | -------------------------------------------------------------------------------- /newcodes/answers/q16.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import random 5 | 6 | lst = [random.randint(0,9) for i in range(100)] 7 | print(lst) 8 | 9 | only_int = set(lst) 10 | 11 | num = [ lst.count(i) for i in only_int ] 12 | 13 | dct = dict(zip(only_int, num)) 14 | print(dct) 15 | -------------------------------------------------------------------------------- /python3code/chapter03/fibsbetter.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | """ 3 | the better Fibonacci 4 | filename: fibsbetter.py 5 | """ 6 | 7 | m = {0:0, 1:1} 8 | 9 | def fib(n): 10 | if not n in m: 11 | m [n] = fib(n-1) + fib(n-2) 12 | return m[n] 13 | 14 | f = fib(10) 15 | print(f) 16 | -------------------------------------------------------------------------------- /2code/21501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fibs(max): 5 | n, a, b = 0, 0, 1 6 | while n < max: 7 | yield b 8 | a, b = b, a + b 9 | n = n + 1 10 | 11 | if __name__ == "__main__": 12 | f = fibs(10) 13 | for i in f: 14 | print i , 15 | -------------------------------------------------------------------------------- /newcodes/weight.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def weight(g): 5 | def cal_mg(m): 6 | return m * g 7 | return cal_mg 8 | 9 | w = weight(10) 10 | mg = w(10) 11 | print(mg) 12 | 13 | g0 = 9.78046 #赤道海平面上的重力加速度 14 | w0 = weight(g0) 15 | mg0 = w0(10) 16 | print(mg0) 17 | -------------------------------------------------------------------------------- /python3code/chapter02/evencontinue.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: evencontinue.py 4 | ''' 5 | 6 | a = 9 7 | while a: 8 | if a%2 == 0: 9 | a -=1 10 | continue #如果是偶数,就返回循环的开始 11 | else: 12 | print("{} is odd number".format(a)) #如果是奇数,就打印出来 13 | a -=1 14 | -------------------------------------------------------------------------------- /python3code/chapter03/fibs_rec.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | 3 | def fib(n): 4 | """ 5 | This is Fibonacci by Recursion. 6 | """ 7 | if n==0: 8 | return 0 9 | elif n==1: 10 | return 1 11 | else: 12 | return fib(n-1) + fib(n-2) 13 | 14 | f = fib(10) 15 | print(f) 16 | -------------------------------------------------------------------------------- /videolesson/country.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | 3 | ''' 4 | lesson 15-3 5 | filename: country.py 6 | ''' 7 | 8 | country = {"CHINA": "BEIJING", 'CANADA': "OTTAWA", 'GREECE': 'ATHENS', 'ITALY': 'ROME'} 9 | 10 | name = input("input the name of country:") 11 | capital = country[name] 12 | print(name, "-->", capital) -------------------------------------------------------------------------------- /2code/23504.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from contextlib import contextmanager 5 | 6 | @contextmanager 7 | def demo(): 8 | print "before yield." 9 | yield "contextmanager demo." 10 | print "after yield." 11 | 12 | with demo() as dd: 13 | print "the word is: %s" % dd 14 | 15 | -------------------------------------------------------------------------------- /newcodes/wrap1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def foo(fun): 5 | def wrap(): 6 | print("start") 7 | fun() 8 | print("end") 9 | print(fun.__name__) 10 | return wrap 11 | 12 | @foo 13 | def bar(): 14 | print("I am in bar()") 15 | 16 | bar() 17 | 18 | -------------------------------------------------------------------------------- /newcodes/answers/q13.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | name_lst = [] 5 | while True: 6 | name = input("Please input an English name(input 'q' then exit)") 7 | if name == "q": 8 | break 9 | else: 10 | name_lst.append(name) 11 | 12 | name_lst.sort() 13 | print(name_lst) 14 | -------------------------------------------------------------------------------- /2code/20402.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | the better Fibonacci 6 | """ 7 | 8 | meno = {0:0, 1:1} 9 | 10 | def fib(n): 11 | if not n in meno: 12 | meno[n] = fib(n-1) + fib(n-2) 13 | return meno[n] 14 | 15 | if __name__ == "__main__": 16 | f = fib(10) 17 | print f 18 | -------------------------------------------------------------------------------- /2code/21302.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class A(object): 5 | author = "qiwsir" 6 | def __getattr__(self, name): 7 | if name != "author": 8 | return "from starter to master." 9 | 10 | if __name__ == "__main__": 11 | a = A() 12 | print a.author 13 | print a.lang 14 | -------------------------------------------------------------------------------- /videolesson/odd_even.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | lesson 19-04 4 | filename: odd_even.py 5 | ''' 6 | lst = [1,2,3,4,5,6,7,8,9,10] 7 | odd = [] 8 | even = [] 9 | for i in lst: 10 | if i % 2 == 0: 11 | even.append(i) 12 | else: 13 | odd.append(i) 14 | 15 | print("odd: ", odd) 16 | print("even: ", even) -------------------------------------------------------------------------------- /1code/107.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | name = raw_input("What is your name?") 5 | age = raw_input("How old are you?") 6 | 7 | print "Your name is:", name 8 | print "You are " + age + " years old." 9 | 10 | after_ten = int(age) + 10 11 | print "You will be " + str(after_ten) + " years old after ten years." 12 | -------------------------------------------------------------------------------- /newcodes/answers/q56.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def flod_paper(n, d): 5 | h = d*2**n 6 | return h 7 | 8 | if __name__ == "__main__": 9 | d = 1/200 10 | n = 30 11 | h = flod_paper(n, d) 12 | h_meter = h / 100 13 | print('After {0} floding, its high is {1}m.'.format(n, h_meter)) 14 | -------------------------------------------------------------------------------- /python3code/chapter03/weight.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: weight.py 4 | ''' 5 | def weight(g): 6 | def cal_mg(m): 7 | return m * g 8 | return cal_mg 9 | 10 | w = weight(10) #g=10 11 | mg = w(10) 12 | print(mg) 13 | 14 | g0 = 9.78046 #赤道海平面上的重力加速度 15 | w0 = weight(g0) 16 | mg0 = w0(10) 17 | print(mg0) 18 | -------------------------------------------------------------------------------- /python3code/chapter04/convert2g.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: convert2g.py 4 | ''' 5 | 6 | class ToGram(float): 7 | def __new__(cls, jin=0.0): 8 | gram = jin / 2 * 1000 9 | return float.__new__(cls, gram) 10 | 11 | jin = 2.3 12 | value = ToGram(jin) 13 | print("{0}jin = {1:.2f}g".format(jin, value)) 14 | -------------------------------------------------------------------------------- /newcodes/answers/q26.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | users = ['xiaoxifeng', 'cangcang', 'tom'] 5 | 6 | while True: 7 | name = input("input your name:") 8 | if name in users: 9 | print("Hello, {0}".format(name)) 10 | break 11 | else: 12 | print("Sorry. Try again, please.") 13 | 14 | -------------------------------------------------------------------------------- /newcodes/answers/q31.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | #people_list = [ x for x in range(1, 101) ] 5 | #while len(people_list) != 1: 6 | # people_list = people_list[1::2] 7 | #print(people_list[0]) 8 | 9 | s = range(100) 10 | while len(s) > 1: 11 | s = [ x for i,x in enumerate(s) if i%2==1 ] 12 | print(s.pop()+1) 13 | -------------------------------------------------------------------------------- /newcodes/cal_power.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def power_seq(func, seq): 5 | return [func(i) for i in seq] 6 | 7 | def pingfang(x): 8 | return x ** 2 9 | 10 | if __name__ == "__main__": 11 | num_seq = [111, 3.14, 2.91] 12 | r = power_seq(pingfang, num_seq) 13 | print(num_seq) 14 | print(r) 15 | -------------------------------------------------------------------------------- /python3code/chapter04/fibsyield.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: fibsyield.py 4 | ''' 5 | 6 | def fibs(max): 7 | n, a, b = 0, 0, 1 8 | while n < max: 9 | yield b 10 | a, b = b, a + b 11 | n = n + 1 12 | 13 | if __name__ == "__main__": 14 | f = fibs(10) 15 | for i in f: 16 | print(i, end=',') 17 | -------------------------------------------------------------------------------- /2code/20401.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fib(n): 5 | """ 6 | This is Fibonacci by Recursion. 7 | """ 8 | if n==0: 9 | return 0 10 | elif n==1: 11 | return 1 12 | else: 13 | return fib(n-1) + fib(n-2) 14 | 15 | if __name__ == "__main__": 16 | f = fib(10) 17 | print f 18 | -------------------------------------------------------------------------------- /2code/21703.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | while 1: 4 | try: 5 | x = raw_input("the first number:") 6 | y = raw_input("the second number:") 7 | 8 | r = float(x)/float(y) 9 | print r 10 | except Exception, b: 11 | print b 12 | print "try again." 13 | else: 14 | break 15 | -------------------------------------------------------------------------------- /2code/21703p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | while 1: 4 | try: 5 | x = input("the first number:") 6 | y = input("the second number:") 7 | 8 | r = float(x)/float(y) 9 | print(r) 10 | except Exception as e: 11 | print(e) 12 | print("try again.") 13 | else: 14 | break 15 | -------------------------------------------------------------------------------- /newcodes/fibs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fibs(n): 5 | """ 6 | This is a Fibonacci sequence. 7 | """ 8 | result = [0, 1] 9 | for i in range(n-2): 10 | result.append(result[-2] + result[-1]) 11 | return result 12 | 13 | if __name__ == "__main__": 14 | lst = fibs(10) 15 | print(lst) 16 | -------------------------------------------------------------------------------- /python3code/chapter06/mypackage/A/abasic.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | path: ./mypackage/A/abasic.py 4 | filename: abasic.py 5 | ''' 6 | 7 | from . import apython 8 | from ..B import brust 9 | 10 | basic = "BASIC-" + apython.python() + "-" + brust.rust 11 | 12 | #it will be Error! 13 | if __name__ == "__main__": 14 | print(basic) 15 | -------------------------------------------------------------------------------- /1code/nameage.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: nameage.py 4 | ''' 5 | 6 | name = input("What is your name?") 7 | age = input("How old are you?") 8 | 9 | print("Your name is: ", name) 10 | print("You are " + age + " years old.") 11 | 12 | after_ten = int(age) + 10 13 | print("You will be " + str(after_ten) + " years old after ten years.") 14 | 15 | -------------------------------------------------------------------------------- /newcodes/try_else.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | while 1: 4 | try: 5 | x = input("the first number:") 6 | y = input("the second number:") 7 | 8 | r = float(x)/float(y) 9 | print(r) 10 | except Exception as e: 11 | print(e) 12 | print("try again.") 13 | else: 14 | break 15 | -------------------------------------------------------------------------------- /3code/web/handlers/sleep.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from base import BaseHandler 5 | 6 | import time 7 | 8 | class SleepHandler(BaseHandler): 9 | def get(self): 10 | time.sleep(17) 11 | self.render("sleep.html") 12 | 13 | class SeeHandler(BaseHandler): 14 | def get(self): 15 | self.render("see.html") 16 | -------------------------------------------------------------------------------- /newcodes/fibs_yield.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fibs(max): 5 | """ 6 | 斐波那契数列的生成器 7 | """ 8 | n, a, b = 0, 0, 1 9 | while n < max: 10 | yield b 11 | a, b = b, a + b 12 | n = n + 1 13 | 14 | if __name__ == "__main__": 15 | f = fibs(10) 16 | for i in f: 17 | print(i, end=',') 18 | -------------------------------------------------------------------------------- /python3code/chapter01/nameage.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: nameage.py 4 | ''' 5 | 6 | name = input("What is your name?") 7 | age = input("How old are you?") 8 | 9 | print("Your name is: ", name) 10 | print("You are " + age + " years old.") 11 | 12 | after_ten = int(age) + 10 13 | print("You will be " + str(after_ten) + " years old after ten years.") -------------------------------------------------------------------------------- /1code/chartoint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def change_char(character, n): 5 | new = [] 6 | for c in character: 7 | i = ord(c) + n 8 | new.append(chr(i)) 9 | return "".join(new) 10 | 11 | if __name__ == "__main__": 12 | one = "abc" 13 | new = change_char(one, 2) 14 | print one 15 | print new 16 | 17 | -------------------------------------------------------------------------------- /2code/20202.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def fibs(n): 5 | """ 6 | This is a Fibonacci sequence. 7 | """ 8 | result = [0,1] 9 | for i in range(n-2): 10 | result.append(result[-2] + result[-1]) 11 | return result 12 | 13 | if __name__ == "__main__": 14 | #lst = fibs(10) 15 | #print lst 16 | fibs(10) 17 | -------------------------------------------------------------------------------- /newcodes/answers/q60.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def gcd(m, n): 5 | return m if n == 0 else gcd(n, m % n) 6 | 7 | def lcm(m, n): 8 | return m * n // gcd(m, n) 9 | 10 | if __name__ == "__main__": 11 | m = int(input("input m:")) 12 | n = int(input("input n:")) 13 | print("GCD", gcd(m, n)) 14 | print("LCM", lcm(m, n)) 15 | -------------------------------------------------------------------------------- /2code/20702.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # coding:utf-8 3 | 4 | def convert(func, seq): 5 | return [func(i) for i in seq] 6 | 7 | def num(n): 8 | if n%2 == 0: 9 | return n**n 10 | else: 11 | return n*n 12 | 13 | if __name__ == "__main__": 14 | myseq = (3, 4, 5) 15 | r = convert(num, myseq) 16 | print r #Python 3: print(r) 17 | -------------------------------------------------------------------------------- /newcodes/answers/q40-2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from functools import reduce 5 | 6 | def addx(x): 7 | numbers = range((x+1)) 8 | r = reduce(lambda x,y: x+y, numbers) 9 | return r 10 | 11 | if __name__ == "__main__": 12 | x = int(input("please input a interger:")) 13 | print("0+1+2...+{0}".format(x)) 14 | print(addx(x)) 15 | -------------------------------------------------------------------------------- /2code/20704.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(fun): 3 | def wrap(): 4 | print "start" 5 | fun() 6 | print "end" 7 | print fun.__name__ 8 | return wrap 9 | 10 | @foo 11 | def bar(): 12 | print "I am in bar()" 13 | 14 | 15 | bar() 16 | 17 | 18 | #start 19 | #I am in bar() 20 | #end 21 | #bar 22 | #I am in bar() 23 | #f = foo(bar) 24 | #f() 25 | 26 | -------------------------------------------------------------------------------- /2code/22501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import urllib 5 | 6 | def go(a,b,c): 7 | per = 100.0 * a * b / c 8 | if per > 100: 9 | per = 100 10 | print "%.2f%%" % per 11 | 12 | url = "http://youxi.66wz.com/uploads/1046/1321/11410192.90d133701b06f0cc2826c3e5ac34c620.jpg" 13 | local = "/home/qw/Pictures/g.jpg" 14 | urllib.urlretrieve(url, local, go) 15 | -------------------------------------------------------------------------------- /python3code/chapter05/tryelse.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: tryelse.py 4 | ''' 5 | 6 | while 1: 7 | try: 8 | x = input("the first number:") 9 | y = input("the second number:") 10 | 11 | r = float(x)/float(y) 12 | print(r) 13 | except Exception as e: 14 | print(e) 15 | print("try again.") 16 | else: 17 | break 18 | -------------------------------------------------------------------------------- /3code/web/templates/user.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

Your informations are:

5 | {% end %} 6 | 7 | {% block body %} 8 | 15 | {% end %} 16 | -------------------------------------------------------------------------------- /newcodes/answers/q39.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def exact_division(interger): 5 | if interger % 17 == 0: 6 | return interger 7 | 8 | if __name__ == "__main__": 9 | nlst = range(100, 1000) 10 | inter_lst = [] 11 | for i in nlst: 12 | a = exact_division(i) 13 | if a: 14 | inter_lst.append(a) 15 | print(inter_lst) 16 | -------------------------------------------------------------------------------- /2code/pp.py: -------------------------------------------------------------------------------- 1 | # /usr/bin/env python 2 | # coding:utf-8 3 | 4 | __all__ = ['_private_variable', 'public_teacher'] 5 | 6 | public_variable = "Hello, I am a public variable." 7 | _private_variable = "Hi, I am a private variable." 8 | 9 | def public_teacher(): 10 | print "I am a public teacher, I am from JP." 11 | 12 | def _private_teacher(): 13 | print "I am a private teacher, I am from CN." 14 | -------------------------------------------------------------------------------- /videolesson/judge_input.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | lesson 19-03 4 | filename: judge_input.py 5 | ''' 6 | input_char = input("Input something: ") 7 | if input_char.isdigit(): 8 | result = int(input_char) * 10 9 | print("You input {0}. Output is {1}".format(input_char, result)) 10 | elif input_char.isalpha(): 11 | print(input_char + "@python") 12 | else: 13 | print(input_char) -------------------------------------------------------------------------------- /1code/you.md: -------------------------------------------------------------------------------- 1 | You Raise Me Up 2 | When I am down and, oh my soul, so weary; 3 | When troubles come and my heart burdened be; 4 | Then, I am still and wait here in the silence, 5 | Until you come and sit awhile with me. 6 | You raise me up, so I can stand on mountains; 7 | You raise me up, to walk on stormy seas; 8 | I am strong, when I am on your shoulders; 9 | You raise me up: To more than I can be. 10 | -------------------------------------------------------------------------------- /newcodes/answers/q67.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class ReverseRange: 5 | def __init__(self, n): 6 | self.n = n 7 | 8 | def __next__(self): 9 | if self.n == 0: 10 | raise StopIteration 11 | self.n -= 1 12 | return self.n 13 | 14 | def __iter__(self): 15 | return self 16 | 17 | for i in ReverseRange(9): 18 | print(i) 19 | -------------------------------------------------------------------------------- /newfiles/you.md: -------------------------------------------------------------------------------- 1 | You Raise Me Up 2 | When I am down and, oh my soul, so weary; 3 | When troubles come and my heart burdened be; 4 | Then, I am still and wait here in the silence, 5 | Until you come and sit awhile with me. 6 | You raise me up, so I can stand on mountains; 7 | You raise me up, to walk on stormy seas; 8 | I am strong, when I am on your shoulders; 9 | You raise me up: To more than I can be. 10 | -------------------------------------------------------------------------------- /videolesson/newton.py: -------------------------------------------------------------------------------- 1 | #coding: utf-8 2 | ''' 3 | calculate the square root by Newton's method. 4 | lesson 22-1 5 | filename: newton.py 6 | ''' 7 | value = 23 #f(x) = x^2 - 23 8 | epsilon = 0.001 9 | result = value / 2 10 | while abs(result*result - value) >= epsilon: 11 | result = result - ((result*result - value) / (2 * result)) 12 | print("The square root of {0} is about {1}".format(value, result)) -------------------------------------------------------------------------------- /newcodes/answers/q59.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def split_int(a): 5 | for i in range(2, 100, 1): 6 | if a % i == 0: 7 | return i 8 | return 0 9 | 10 | if __name__ == '__main__': 11 | a = int(input('input a number, please.')) 12 | val = split_int(a) 13 | while val > 1: 14 | print(val) 15 | a = a / val 16 | val = split_int(a) 17 | -------------------------------------------------------------------------------- /newcodes/answers/q22-2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def split_number(num): 5 | w = len(str(num)) 6 | w_lst = [10**i for i in range(w)] 7 | num_lst = [] 8 | for n in w_lst: 9 | a = (num // n) % 10 10 | num_lst.append(a) 11 | return num_lst 12 | 13 | if __name__ == "__main__": 14 | n = 2016 15 | r = split_number(n) 16 | r.reverse() 17 | print(r) 18 | -------------------------------------------------------------------------------- /python3code/chapter06/pp.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: pp.py 4 | ''' 5 | __all__ = ['_private_variable', 'public_teacher'] 6 | 7 | public_variable = "Hello, I am a public variable." 8 | _private_variable = "Hi, I am a private variable." 9 | 10 | def public_teacher(): 11 | print("I am a public teacher, I am from JP.") 12 | 13 | def _private_teacher(): 14 | print("I am a private teacher, I am from CN.") 15 | -------------------------------------------------------------------------------- /newcodes/answers/youraisemeup.txt: -------------------------------------------------------------------------------- 1 | You Raise Me Up 2 | When I am down and oh my soul so weary 3 | When troubles come and my heart burdened be 4 | Then I am still and wait here in the silenceUntil you come and sit awhile with me 5 | 6 | You raise me up 7 | so I can stand on mountains 8 | You raise me up to walk on stormy seas 9 | 10 | I am strong when I am on your shoulders 11 | 12 | You raise me up 13 | To more than I can be 14 | -------------------------------------------------------------------------------- /newcodes/answers/q62.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class PayCalculator: 5 | def __init__(self, pay_rate): 6 | self.pay_rate = pay_rate 7 | 8 | def compute_pay(self, hours): 9 | total_pay = self.pay_rate * hours 10 | return round(total_pay, 2) 11 | 12 | if __name__ == "__main__": 13 | worker = PayCalculator(25.7) 14 | total = worker.compute_pay(8) 15 | print(total) 16 | -------------------------------------------------------------------------------- /1code/judgenumber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | print("请输入任意一个整数数字:") 5 | number = int(input()) 6 | 7 | if number == 10: 8 | print("您输入的数字是:{}".format(number)) 9 | print("You are SMART.") 10 | elif number > 10: 11 | print("您输入的数字是:{}".format(number)) 12 | print("This number is more than 10.") 13 | else: 14 | print("您输入的数字是:{}".format(number)) 15 | print("This number is less than 10.") 16 | 17 | -------------------------------------------------------------------------------- /newcodes/answers/q29.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | d = {} 5 | with open("youraisemeup.txt") as f: 6 | for line in f: 7 | if bool(line): 8 | line_lst = line.split() 9 | for word in line_lst: 10 | word = word.lower() 11 | if word in d: 12 | d[word] += 1 13 | else: 14 | d[word] = 1 15 | print(d) 16 | -------------------------------------------------------------------------------- /newcodes/answers/q49.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # encoding:utf-8 3 | 4 | def divided(m,r,out): 5 | if(r==0): 6 | return True 7 | tm=r 8 | while tm>0: 9 | if(tm<=m): 10 | out.append(tm) 11 | if(divided(tm, r-tm, out)): 12 | print(out) 13 | out.pop() 14 | tm = tm-1 15 | return False 16 | 17 | 18 | n=6 19 | output=[] 20 | divided(n-1, n, output) 21 | -------------------------------------------------------------------------------- /python3code/chapter04/gcdlcm.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: gcdlcm.py 4 | ''' 5 | 6 | def gcd(a, b): #最大公约数 7 | if not a > b: 8 | a, b = b, a 9 | while b != 0: 10 | remainder = a % b 11 | a, b = b, remainder 12 | return a 13 | 14 | def lcm(a, b): #最小公倍数 15 | return (a * b) / gcd(a,b) 16 | 17 | if __name__ == "__main__": 18 | print(gcd(8, 20)) 19 | print(lcm(8, 20)) 20 | -------------------------------------------------------------------------------- /python3code/chapter04/simlist.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: simlist.py 4 | ''' 5 | 6 | class SimLst: 7 | def __init__(self, total): 8 | self.__num = [None] * total 9 | def __setitem__(self, n, data): 10 | self.__num[n] = data 11 | def __getitem__(self, n): 12 | return self.__num[n] 13 | def __len__(self): 14 | return len(self.__num) 15 | 16 | slst = SimLst(3) 17 | print(len(slst)) 18 | -------------------------------------------------------------------------------- /python3code/chapter04/definefraction.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: definefraction.py 4 | ''' 5 | class Fraction: 6 | def __init__(self, number, denom=1): 7 | self.number = number 8 | self.denom = denom 9 | 10 | def __str__(self): 11 | return str(self.number) + '/' + str(self.denom) 12 | 13 | __repr__ = __str__ 14 | 15 | 16 | if __name__ == "__main__": 17 | f = Fraction(2, 3) 18 | print(f) 19 | -------------------------------------------------------------------------------- /python3code/chapter04/private.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | 3 | class ProtectMe: 4 | def __init__(self): 5 | self.me = "qiwsir" 6 | self.__name = "kivi" 7 | 8 | def __python(self): 9 | print("I love Python.") 10 | 11 | def code(self): 12 | print("Which language do you like?") 13 | self.__python() 14 | 15 | if __name__ == "__main__": 16 | p = ProtectMe() 17 | print(p.me) 18 | print(p.__name) 19 | -------------------------------------------------------------------------------- /newcodes/answers/q42.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def find_int(n): 5 | x = n ** 2 6 | if x>99 and x<1000: 7 | last_two = x % 100 8 | if last_two == n: 9 | return True 10 | else: 11 | return False 12 | 13 | if __name__ == "__main__": 14 | numbers = [] 15 | for i in range(10, 100): 16 | if find_int(i): 17 | numbers.append(i) 18 | print(numbers) 19 | 20 | -------------------------------------------------------------------------------- /newcodes/round_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class RoundFloat: 5 | def __init__(self, val): 6 | assert isinstance(val, float), "value must be a float." 7 | self.value = round(val, 2) 8 | 9 | def __str__(self): 10 | return "{:.2f}".format(self.value) 11 | 12 | __repr__ = __str__ 13 | 14 | if __name__ == "__main__": 15 | r = RoundFloat(2.185) 16 | print(r) 17 | print(type(r)) 18 | -------------------------------------------------------------------------------- /python3code/chapter02/judgenumber.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: judgenumber.py 4 | ''' 5 | 6 | print("请输入任意一个整数数字:") 7 | number = int(input()) 8 | 9 | if number == 10: 10 | print("您输入的数字是:{}".format(number)) 11 | print("You are SMART.") 12 | elif number > 10: 13 | print("您输入的数字是:{}".format(number)) 14 | print("This number is more than 10.") 15 | else: 16 | print("您输入的数字是:{}".format(number)) 17 | print("This number is less than 10.") 18 | -------------------------------------------------------------------------------- /python3code/chapter04/singleton.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: singleton.py 4 | ''' 5 | class Singleton: 6 | _instance = None 7 | def __new__(cls, *args, **kwargs): 8 | if not cls._instance: 9 | cls._instance = super().__new__(cls) 10 | return cls._instance 11 | 12 | class MyClass(Singleton): 13 | a = 1 14 | 15 | x = MyClass() 16 | y = MyClass() 17 | 18 | print(x) 19 | print(y) 20 | print("x is y: ", x is y) 21 | -------------------------------------------------------------------------------- /newcodes/answers/q40.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | the_num = input("Please enter a number to check:") 5 | the_num = int(the_num) 6 | 7 | divisor = 1 8 | sum_of_divisors = 0 9 | while divisor < the_num: 10 | if the_num % divisor == 0: 11 | sum_of_divisors = sum_of_divisors + divisor 12 | divisor = divisor + 1 13 | 14 | if the_num == sum_of_divisors: 15 | print(the_num, "is perfect") 16 | else: 17 | print(the_num, "is not perfect") 18 | -------------------------------------------------------------------------------- /python3code/chapter04/roundfloat.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: roundfloat.py 4 | ''' 5 | class RoundFloat: 6 | def __init__(self, val): 7 | assert isinstance(val, float), "value must be a float." 8 | self.value = round(val, 2) 9 | 10 | def __str__(self): #① 11 | return "{:.2f}".format(self.value) 12 | 13 | __repr__ = __str__ #② 14 | 15 | if __name__ == "__main__": 16 | r = RoundFloat(2.185) 17 | print(r) 18 | print(type(r)) 19 | -------------------------------------------------------------------------------- /2code/20503.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | find the prime 6 | """ 7 | 8 | import math 9 | 10 | def is_prime(n): 11 | """ 12 | a integer is prime or not 13 | """ 14 | if n <= 1: 15 | return False 16 | for i in range(2, int(math.sqrt(n) + 1)): 17 | if n % i == 0: 18 | return False 19 | return True 20 | 21 | if __name__ == "__main__": 22 | primes = [i for i in range(2,100) if is_prime(i)] 23 | print primes 24 | -------------------------------------------------------------------------------- /2code/23501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | #read_file = open("23501.txt") 5 | #write_file = open("23502.txt", "w") 6 | 7 | #try: 8 | # r = read_file.readlines() 9 | # for line in r: 10 | # write_file.write(line) 11 | #finally: 12 | # read_file.close() 13 | # write_file.close() 14 | 15 | with open("23501.txt") as read_file, open("23503.txt", "w") as write_file: 16 | for line in read_file.readlines(): 17 | write_file.write(line) 18 | 19 | 20 | -------------------------------------------------------------------------------- /3code/web/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

登录页面

5 |

用用户名为:{{user}}登录

6 | {% end %} 7 | {% block body %} 8 |
9 | {% raw xsrf_form_html() %} 10 |

UserName:

11 |

Password:

12 |

13 |
14 | {% end %} 15 | -------------------------------------------------------------------------------- /3code/web/templates/register.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block header %} 4 |

注册页面

5 | {% end %} 6 | {% block body %} 7 |
8 |

UserName:

9 |

Password:

10 |

Email:

11 |

12 |
13 | {% end %} 14 | -------------------------------------------------------------------------------- /python3code/chapter05/calculator.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | class Calculator(object): 4 | is_raise = False 5 | def calc(self, express): 6 | try: 7 | return eval(express) 8 | except ZeroDivisionError: 9 | if self.is_raise: 10 | return "zero can not be division." 11 | else: 12 | raise 13 | 14 | if __name__ == "__main__": 15 | c = Calculator() 16 | c.is_raise = True 17 | print(c.calc("8/0")) 18 | -------------------------------------------------------------------------------- /2code/21602.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Calculator(object): 5 | is_raise = False 6 | def calc(self, express): 7 | try: 8 | return eval(express) 9 | except ZeroDivisionError: 10 | if self.is_raise: 11 | print "zero can not be division." 12 | else: 13 | raise 14 | 15 | if __name__ == "__main__": 16 | c = Calculator() 17 | c.is_raise = True 18 | print c.calc("8/0") 19 | -------------------------------------------------------------------------------- /1code/122p3.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #coding:utf-8 3 | 4 | print("请输入任意一个整数数字:") 5 | 6 | number = int(input()) 7 | 8 | if number == 10: 9 | print("您输入的数字是:{}".format(number)) 10 | print("You are SMART.") 11 | elif number > 10: 12 | print("您输入的数字是:{}".format(number)) 13 | print("This number is more than 10.") 14 | elif number < 10: 15 | print("您输入的数字是:{}".format(number)) 16 | print("This number is less than 10.") 17 | else: 18 | print("Are you a human?") 19 | 20 | -------------------------------------------------------------------------------- /2code/23901p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class RoundFloat: 4 | def __init__(self, val): 5 | assert isinstance(val, float), "value must be a float." 6 | self.value = round(val, 2) 7 | 8 | def __str__(self): 9 | return "{:.2f}".format(self.value) 10 | 11 | __repr__ = __str__ 12 | 13 | #def __repr__(self): 14 | # return self.__str__() 15 | 16 | if __name__ == "__main__": 17 | r = RoundFloat(2.0) 18 | print(r) 19 | print(type(r)) 20 | -------------------------------------------------------------------------------- /newcodes/calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Calculator(object): 5 | is_raise = False 6 | def calc(self, express): 7 | try: 8 | return eval(express) 9 | except ZeroDivisionError: 10 | if self.is_raise: 11 | return "zero can not be division." 12 | else: 13 | raise 14 | 15 | if __name__ == "__main__": 16 | c = Calculator() 17 | c.is_raise = True 18 | print(c.calc("8/0")) 19 | -------------------------------------------------------------------------------- /videolesson/arithmetic.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | 3 | ''' 4 | lesson 07-6 5 | filename: arithmetic.py 6 | ''' 7 | 8 | print('Please input two int:') 9 | a = input('a number:') 10 | b = input('another number:') 11 | a = int(a) 12 | b = int(b) 13 | 14 | add_result = a + b 15 | sub_result = a - b 16 | mul_result = a * b 17 | div_result = a / b 18 | 19 | print(a, " + ", b, ' = ', add_result) 20 | print(a, " - ", b, ' = ', sub_result) 21 | print(a, " * ", b, ' = ', mul_result) 22 | print(a, " / ", b, ' = ', div_result) -------------------------------------------------------------------------------- /1code/12902.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from __future__ import division 5 | import random 6 | 7 | score = [random.randint(0,100) for i in range(40)] 8 | print score 9 | 10 | num = len(score) 11 | sum_score = sum(score) 12 | ave_num = sum_score/num 13 | less_ave = len([i for i in score if i{0}

".format(func(name)) 9 | return wrapper 10 | 11 | def div_decorate(func): 12 | def wrapper(name): 13 | return "
{0}
".format(func(name)) 14 | return wrapper 15 | 16 | @div_decorate 17 | @p_decorate 18 | def book(name): 19 | return "the name of my book is {0}".format(name) 20 | 21 | result = book("PYTHON") 22 | print(result) 23 | -------------------------------------------------------------------------------- /2code/20904.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class K1(object): 5 | def foo(self): 6 | print "K1-foo" 7 | 8 | class K2(object): 9 | def foo(self): 10 | print "K2-foo" 11 | def bar(self): 12 | print "K2-bar" 13 | 14 | class J1(K1, K2): 15 | pass 16 | 17 | class J2(K1, K2): 18 | def bar(self): 19 | print "J2-bar" 20 | 21 | class C(J1, J2): 22 | pass 23 | 24 | if __name__ == "__main__": 25 | print C.__mro__ 26 | m = C() 27 | m.foo() 28 | m.bar() 29 | 30 | -------------------------------------------------------------------------------- /2code/24001p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Rectangle(object): 5 | 6 | def __init__(self): 7 | self.width = 0 8 | self.length = 0 9 | 10 | def setSize(self, size): 11 | self.width, self.length = size 12 | def getSize(self): 13 | return self.width, self.length 14 | 15 | if __name__ == "__main__": 16 | r = Rectangle() 17 | r.width = 3 18 | r.length = 4 19 | print(r.getSize()) 20 | r.setSize( (30, 40) ) 21 | print(r.width) 22 | print(r.length) 23 | -------------------------------------------------------------------------------- /3code/web/application.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from url import url 5 | 6 | import tornado.web 7 | import os 8 | 9 | setting = dict( 10 | template_path = os.path.join(os.path.dirname(__file__), "templates"), 11 | static_path = os.path.join(os.path.dirname(__file__), "statics"), 12 | cookie_secret = "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=", 13 | xsrf_cookies = True, 14 | login_url = '/', 15 | ) 16 | application = tornado.web.Application( 17 | handlers = url, 18 | **setting 19 | ) 20 | -------------------------------------------------------------------------------- /newcodes/fibs_iter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Fibs: 5 | def __init__(self, max): 6 | self.max = max 7 | self.a = 0 8 | self.b = 1 9 | 10 | def __iter__(self): 11 | return self 12 | 13 | def __next__(self): 14 | fib = self.a 15 | if fib > self.max: 16 | raise StopIteration 17 | self.a, self.b = self.b, self.a + self.b 18 | return fib 19 | 20 | if __name__ == "__main__": 21 | fibs = Fibs(5) 22 | print(list(fibs)) 23 | -------------------------------------------------------------------------------- /python3code/chapter04/myrange.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: myrange.py 4 | ''' 5 | 6 | class MyRange: 7 | def __init__(self, n): 8 | self.i = 1 9 | self.n = n 10 | 11 | def __iter__(self): 12 | return self 13 | 14 | def __next__(self): 15 | if self.i <= self.n: 16 | i = self.i 17 | self.i += 1 18 | return i 19 | else: 20 | raise StopIteration() 21 | 22 | if __name__ == "__main__": 23 | x = MyRange(7) 24 | print([i for i in x]) 25 | -------------------------------------------------------------------------------- /2code/20902.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class Person: 7 | 8 | def eye(self): 9 | print "two eyes" 10 | 11 | def breast(self, n): 12 | print "The breast is: ",n 13 | 14 | class Girl: 15 | age = 28 16 | def color(self): 17 | print "The girl is white" 18 | 19 | class HotGirl(Person, Girl): 20 | pass 21 | 22 | if __name__ == "__main__": 23 | kong = HotGirl() 24 | kong.eye() 25 | kong.breast(90) 26 | kong.color() 27 | print kong.age 28 | -------------------------------------------------------------------------------- /python3code/chapter04/about_self.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | 3 | class Person: 4 | def __init__(self, name): 5 | self.name = name 6 | 7 | def get_name(self): 8 | return self.name 9 | 10 | def breast(self, n): 11 | self.breast = n 12 | 13 | def color(self, color): 14 | print("{0} is {1}".format(self.name, color)) 15 | 16 | def how(self): 17 | print("{0} breast is {1}".format(self.name, self.breast)) 18 | 19 | girl = Person('canglaoshi') 20 | girl.breast(90) 21 | 22 | girl.color("white") 23 | girl.how() 24 | -------------------------------------------------------------------------------- /2code/21601p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | while 1: 5 | print("this is a division program.") 6 | c = input("input 'c' continue, otherwise logout:") 7 | if c == 'c': 8 | a = input("first number:") 9 | b = input("second number:") 10 | try: 11 | print(float(a)/float(b)) 12 | print("*************************") 13 | except ZeroDivisionError: 14 | print("The second number can't be zero!") 15 | print("*************************") 16 | else: 17 | break 18 | -------------------------------------------------------------------------------- /2code/22601.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Everyday Italian 4 | Giada De Laurentiis 5 | 2005 6 | 37.0 7 | 8 | python -------------------------------------------------------------------------------- /2code/21101.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | "the code is from: http://zetcode.com/lang/python/oop/" 5 | 6 | __metaclass__ = type 7 | 8 | class Animal: 9 | def __init__(self, name=""): 10 | self.name = name 11 | 12 | def talk(self): 13 | pass 14 | 15 | class Cat(Animal): 16 | def talk(self): 17 | print "Meow!" 18 | 19 | class Dog(Animal): 20 | def talk(self): 21 | print "Woof!" 22 | 23 | 24 | a = Animal() 25 | a.talk() 26 | 27 | c = Cat("Missy") 28 | c.talk() 29 | 30 | d = Dog("Rocky") 31 | d.talk() 32 | -------------------------------------------------------------------------------- /newcodes/answers/q41.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import math 5 | 6 | def trail_sqrt(n): 7 | d = {} 8 | i = 0 9 | while n >= 2: 10 | n = math.sqrt(n) 11 | i += 1 12 | d[i] = n 13 | return d 14 | 15 | if __name__ == "__main__": 16 | n = int(input("please input a interger, and it should more than 2.")) 17 | if n < 2: 18 | print("sorry, your interger should more than 2.") 19 | 20 | else: 21 | d = trail_sqrt(n) 22 | for k,v in d.items(): 23 | print("{0}--->{1}".format(k,v)) 24 | -------------------------------------------------------------------------------- /python3code/chapter04/fibsiterator.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: fibsiterator.py 4 | ''' 5 | 6 | class Fibs: 7 | def __init__(self, max): 8 | self.max = max 9 | self.a = 0 10 | self.b = 1 11 | 12 | def __iter__(self): 13 | return self 14 | 15 | def __next__(self): 16 | fib = self.a 17 | if fib > self.max: 18 | raise StopIteration 19 | self.a, self.b = self.b, self.a + self.b 20 | return fib 21 | 22 | fibs = Fibs(10000) 23 | lst = [fibs.__next__() for i in range(10)] 24 | print(lst) -------------------------------------------------------------------------------- /2code/21801.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Account(object): 5 | def __init__(self, number): 6 | self.number = number 7 | self.balance = 0 8 | 9 | def deposit(self, amount): 10 | assert amount > 0 11 | self.balance += balance 12 | 13 | def withdraw(self, amount): 14 | assert amount > 0 15 | if amount <= self.balance: 16 | self.balance -= amount 17 | else: 18 | print "balance is not enough." 19 | 20 | if __name__ == "__main__": 21 | a = Account(1000) 22 | a.deposit(-10) 23 | -------------------------------------------------------------------------------- /newcodes/static_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import random 5 | 6 | 7 | class Foo: 8 | def __init__(self, name): 9 | self.name = name 10 | 11 | def get_name(self, age): 12 | if self.select(age): 13 | return self.name 14 | else: 15 | return "the name is secret." 16 | 17 | @staticmethod 18 | def select(n): 19 | a = random.randint(1, 100) 20 | return a - n > 0 21 | 22 | 23 | if __name__ == "__main__": 24 | f = Foo("luolaoshi") 25 | name = f.get_name(22) 26 | print(name) 27 | -------------------------------------------------------------------------------- /python3code/chapter05/tryexceptccb.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: tryexceptccb.py 4 | ''' 5 | 6 | while 1: 7 | print("this is a division program.") 8 | c = input("input 'c' continue, otherwise logout:") 9 | if c == 'c': 10 | a = input("first number:") 11 | b = input("second number:") 12 | try: 13 | print(float(a)/float(b)) 14 | print("*************************") 15 | except ZeroDivisionError: 16 | print("The second number can't be zero!") 17 | print("*************************") 18 | else: 19 | break 20 | -------------------------------------------------------------------------------- /2code/20902_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class Person: 7 | 8 | def eye(self): 9 | print "two eyes" 10 | 11 | def breast(self, n): 12 | print "The breast is: ",n 13 | 14 | class Girl: 15 | age = 28 16 | def color(self): 17 | print "The girl is white" 18 | def eye(self): 19 | print "girl's eyes are big." 20 | 21 | class HotGirl(Person, Girl): 22 | pass 23 | 24 | if __name__ == "__main__": 25 | kong = HotGirl() 26 | kong.eye() 27 | kong.breast(90) 28 | kong.color() 29 | print kong.age 30 | -------------------------------------------------------------------------------- /2code/21402.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | """ 4 | compute Fibonacci by iterator 5 | """ 6 | __metaclass__ = type 7 | 8 | class Fibs: 9 | def __init__(self, max): 10 | self.max = max 11 | self.a = 0 12 | self.b = 1 13 | 14 | def __iter__(self): 15 | return self 16 | 17 | def next(self): 18 | fib = self.a 19 | if fib > self.max: 20 | raise StopIteration 21 | self.a, self.b = self.b, self.a + self.b 22 | return fib 23 | 24 | if __name__ == "__main__": 25 | fibs = Fibs(5) 26 | print list(fibs) 27 | 28 | 29 | -------------------------------------------------------------------------------- /2code/20701p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Person: 5 | """ 6 | This is a sample of class. 7 | """ 8 | 9 | def __init__(self, name): 10 | self.name = name 11 | 12 | def get_name(self): 13 | return self.name 14 | 15 | def color(self, color): 16 | d = {} 17 | d[self.name] = color 18 | return d 19 | 20 | if __name__ == "__main__": 21 | girl = Person("canglaoshi") 22 | print(girl.name) 23 | name = girl.get_name() 24 | print(name) 25 | her_color = girl.color("white") 26 | print(her_color) 27 | 28 | -------------------------------------------------------------------------------- /2code/21601.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | try... except 6 | """ 7 | 8 | while 1: 9 | print "this is a division program." 10 | c = raw_input("input 'c' continue, otherwise logout:") 11 | if c == 'c': 12 | a = raw_input("first number:") 13 | b = raw_input("second number:") 14 | try: 15 | print float(a)/float(b) 16 | print "*************************" 17 | except ZeroDivisionError: 18 | print "The second number can't be zero!" 19 | print "*************************" 20 | else: 21 | break 22 | 23 | -------------------------------------------------------------------------------- /2code/21001.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class StaticMethod: 7 | @staticmethod 8 | def foo(): 9 | print "This is static method foo()." 10 | 11 | 12 | class ClassMethod: 13 | @classmethod 14 | def bar(cls): 15 | print "This is class method bar()." 16 | print "bar() is part of class:", cls.__name__ 17 | 18 | if __name__ == "__main__": 19 | static_foo = StaticMethod() 20 | static_foo.foo() 21 | StaticMethod.foo() 22 | print "********" 23 | class_bar = ClassMethod() 24 | class_bar.bar() 25 | ClassMethod.bar() 26 | -------------------------------------------------------------------------------- /2code/21102.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class ProtectMe: 7 | def __init__(self): 8 | self.me = "qiwsir" 9 | self.__name = "kivi" 10 | 11 | def __python(self): 12 | print "I love Python." 13 | 14 | def code(self): 15 | print "Which language do you like?" 16 | self.__python() 17 | 18 | @property 19 | def name(self): 20 | return self.__name 21 | 22 | if __name__ == "__main__": 23 | p = ProtectMe() 24 | #print p.me 25 | print p.name 26 | #p.code() 27 | #p._ProtectMe.__python() 28 | 29 | -------------------------------------------------------------------------------- /python3code/chapter04/rectangle1.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: rectangle1.py 4 | ''' 5 | 6 | class Rectangle: 7 | """ 8 | the width and length of Rectangle 9 | """ 10 | def __init__(self): 11 | self.width = 0 12 | self.length = 0 13 | 14 | def setSize(self, size): 15 | self.width, self.length = size 16 | def getSize(self): 17 | return self.width, self.length 18 | 19 | if __name__ == "__main__": 20 | r = Rectangle() 21 | r.width = 3 22 | r.length = 4 23 | print(r.getSize()) 24 | r.setSize( (30, 40) ) 25 | print(r.width) 26 | print(r.length) 27 | -------------------------------------------------------------------------------- /python3code/chapter04/simdict.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: simdict.py 4 | ''' 5 | 6 | class SimDit: 7 | def __init__(self, k, v): 8 | self.dct = dict([(k, v)]) 9 | 10 | def __setitem__(self, k, v): 11 | self.dct[k] = v 12 | 13 | def __getitem__(self, k): 14 | return self.dct[k] 15 | 16 | def __len__(self): 17 | return len(self.dct) 18 | 19 | def __delitem__(self, k): 20 | del self.dct[k] 21 | 22 | d = SimDit('name', 'Laoqi') 23 | d['lang'] = 'python' 24 | d['city'] = 'Soochow' 25 | print(d['city']) 26 | print(len(d)) 27 | del d['city'] 28 | print(d.dct) 29 | -------------------------------------------------------------------------------- /newcodes/about_self.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Person: 5 | def __init__(self, name): 6 | self.name = name 7 | 8 | def get_name(self): 9 | return self.name 10 | 11 | def breast(self, n): 12 | self.breast = n 13 | 14 | def color(self, color): 15 | print("{0} is {1}".format(self.name, color)) 16 | 17 | def how(self): 18 | print("{0} breast is {1}".format(self.name, self.breast)) 19 | 20 | girl = Person('canglaoshi') 21 | girl.breast(90) 22 | 23 | girl.color("white") 24 | 25 | girl.how() 26 | 27 | -------------------------------------------------------------------------------- /python3code/chapter06/moduleexample.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: moduleexample.py 4 | ''' 5 | 6 | class Book: 7 | lang = "python" 8 | 9 | def __init__(self, author): 10 | self.author = author 11 | 12 | def get_name(self): 13 | return self.author 14 | 15 | def foo(x): 16 | return x * 2 17 | 18 | #python = Book("laoqi") 19 | #python_name = python.get_name() 20 | 21 | #mul_result = foo(2) 22 | 23 | if __name__ == "__main__": #⑤ 24 | python = Book("laoqi") 25 | python_name = python.get_name() 26 | print(python_name) 27 | 28 | mul_result = foo(2) 29 | print(mul_result) 30 | -------------------------------------------------------------------------------- /3code/web/handlers/user.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import tornado.web 5 | import tornado.escape 6 | import methods.readdb as mrd 7 | from base import BaseHandler 8 | 9 | class UserHandler(BaseHandler): 10 | @tornado.web.authenticated 11 | def get(self): 12 | #username = self.get_argument("user") 13 | username = tornado.escape.json_decode(self.current_user) 14 | print username 15 | print type(username) 16 | user_infos = mrd.select_table(table="users",column="*",condition="username",value=username) 17 | print user_infos 18 | self.render("user.html", users = user_infos) 19 | -------------------------------------------------------------------------------- /newcodes/answers/q57.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def palindrome(word): 5 | word_lst = [ i for i in word ] 6 | word_lst.reverse() 7 | new_word = "".join(word_lst) 8 | if word == new_word: 9 | return True 10 | else: 11 | return False 12 | 13 | if __name__ == "__main__": 14 | while True: 15 | word = input("input a word:('q'-exit)") 16 | if word == "q": 17 | break 18 | else: 19 | if palindrome(word): 20 | print("{0} is a palindrome".format(word)) 21 | else: 22 | print("The word is not palindrome") 23 | 24 | -------------------------------------------------------------------------------- /newcodes/normal_rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | study __getattr__ and __setattr__ 6 | """ 7 | 8 | class Rectangle: 9 | """ 10 | the width and length of Rectangle 11 | """ 12 | def __init__(self): 13 | self.width = 0 14 | self.length = 0 15 | 16 | def setSize(self, size): 17 | self.width, self.length = size 18 | def getSize(self): 19 | return self.width, self.length 20 | 21 | if __name__ == "__main__": 22 | r = Rectangle() 23 | r.width = 3 24 | r.length = 4 25 | print(r.getSize()) 26 | r.setSize( (30, 40) ) 27 | print(r.width) 28 | print(r.length) 29 | -------------------------------------------------------------------------------- /2code/20701.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class Person: 7 | def __init__(self, name): 8 | self.name = name 9 | 10 | def getName(self): 11 | #return self.name 12 | return girl.name 13 | 14 | def breast(self, n): 15 | self.breast = n 16 | 17 | def color(self, color): 18 | print "%s is %s" % (self.name, color) 19 | 20 | def how(self): 21 | print "%s breast is %s" % (self.name, self.breast) 22 | 23 | girl = Person('canglaoshi') 24 | name = girl.getName() 25 | print name 26 | 27 | girl.breast(90) 28 | 29 | girl.color("white") 30 | girl.how() 31 | -------------------------------------------------------------------------------- /3code/web/url.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | """ 4 | the url structure of website 5 | """ 6 | import sys 7 | reload(sys) 8 | sys.setdefaultencoding("utf-8") 9 | 10 | from handlers.index import IndexHandler 11 | from handlers.index import ErrorHandler 12 | from handlers.index import RegisterHandler 13 | from handlers.user import UserHandler 14 | from handlers.sleep import SleepHandler 15 | from handlers.sleep import SeeHandler 16 | 17 | url = [ 18 | (r'/', IndexHandler), 19 | (r'/error', ErrorHandler), 20 | (r'/login', RegisterHandler), 21 | (r'/user', UserHandler), 22 | (r'/sleep', SleepHandler), 23 | (r'/see', SeeHandler), 24 | ] 25 | -------------------------------------------------------------------------------- /2code/20903.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | __metaclass__ = type 5 | 6 | class Person: 7 | def __init__(self): 8 | self.height = 160 9 | 10 | def about(self, name): 11 | print "{} is about {}".format(name, self.height) 12 | 13 | class Girl(Person): 14 | def __init__(self): 15 | super(Girl, self).__init__() 16 | self.breast = 90 17 | 18 | def about(self, name): 19 | print "{} is a hot girl, she is about {}, and her breast is {}".format(name, self.height, self.breast) 20 | super(Girl, self).about(name) 21 | 22 | if __name__ == "__main__": 23 | cang = Girl() 24 | cang.about("canglaoshi") 25 | -------------------------------------------------------------------------------- /newcodes/answers/q66.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class RoundFloat(object): #Python 3: class RoundFloat: 5 | def __init__(self, val): 6 | assert isinstance(val, float), "value must be a float." 7 | self.value = round(val, 2) 8 | 9 | def __str__(self): 10 | return "{:.2f}".format(self.value) 11 | 12 | __repr__ = __str__ 13 | 14 | if __name__ == "__main__": 15 | while True: 16 | n = input("Input a float:('q'-exit)") 17 | if n == 'q': 18 | print('See you next time.') 19 | break 20 | else: 21 | n = float(n) 22 | r = RoundFloat(n) 23 | print(r) 24 | -------------------------------------------------------------------------------- /newcodes/try_except.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | while 1: 5 | print("this is a division program.") 6 | c = input("input 'c' continue, otherwise logout:") 7 | if c == 'c': 8 | a = input("first number:") 9 | b = input("second number:") 10 | try: 11 | print(float(a)/float(b)) 12 | print("*************************") 13 | except (ZeroDivisionError, ValueError) as e: 14 | print(e) 15 | print("*************************") 16 | #except ValueError: 17 | # print("please input number.") 18 | # print("************************") 19 | else: 20 | break 21 | -------------------------------------------------------------------------------- /python3code/chapter05/customexception.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: customexception.py 4 | ''' 5 | 6 | class NegativeAgeException(RuntimeError): 7 | def __init__(self, age): 8 | super().__init__() 9 | self.age = age 10 | 11 | def enterage(age): 12 | if age < 0: 13 | raise NegativeAgeException("Only positive integers are allowed") 14 | 15 | if age % 2 == 0: 16 | print("age is even") 17 | else: 18 | print("age is odd") 19 | 20 | try: 21 | num = int(input("Enter your age: ")) 22 | enterage(num) 23 | except NegativeAgeException: 24 | print("Only integers are allowed") 25 | except: 26 | print("something is wrong") 27 | -------------------------------------------------------------------------------- /newcodes/account.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Account(object): 5 | def __init__(self, number): 6 | self.number = number 7 | self.balance = 0 8 | 9 | def deposit(self, amount): 10 | try: 11 | assert amount > 0 12 | self.balance += amount 13 | except: 14 | print("The money should be bigger than zero.") 15 | 16 | def withdraw(self, amount): 17 | assert amount > 0 18 | if amount <= self.balance: 19 | self.balance -= amount 20 | else: 21 | print("balance is not enough.") 22 | 23 | if __name__ == "__main__": 24 | a = Account(1000) 25 | a.deposit(-10) 26 | -------------------------------------------------------------------------------- /newcodes/answers/q38.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import re 5 | 6 | def validate_email(email): 7 | if len(email) > 4: 8 | if re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,6}$", email) != None: 9 | return True 10 | else: 11 | return False 12 | 13 | if __name__ == "__main__": 14 | while True: 15 | e = input("Input your email('q'-exit):") 16 | if e == "q": 17 | print("Bye!") 18 | break 19 | else: 20 | r = validate_email(e) 21 | if r: 22 | print("The email is right.") 23 | else: 24 | print("sorry, the email is not right.") 25 | -------------------------------------------------------------------------------- /newcodes/single_inhance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Person: 5 | def __init__(self, name): 6 | self.name = name 7 | 8 | def height(self, m): 9 | h = dict((["height", m],)) 10 | return h 11 | 12 | def breast(self, n): 13 | b = dict((["breast", n],)) 14 | return b 15 | 16 | class Girl(Person): 17 | def __init__(self): 18 | self.name = "Aoi sola" 19 | 20 | def get_name(self): 21 | return self.name 22 | 23 | if __name__ == "__main__": 24 | cang = Girl("canglaoshi") 25 | print(cang.get_name()) 26 | print(cang.height(160)) 27 | print(cang.breast(90)) 28 | 29 | -------------------------------------------------------------------------------- /2code/20905p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Person: 5 | def __init__(self, name): 6 | self.name = name 7 | 8 | def height(self, m): 9 | h = dict((["height", m],)) 10 | return h 11 | 12 | def breast(self, n): 13 | b = dict((["breast", n],)) 14 | return b 15 | 16 | class Girl(Person): 17 | def __init__(self,name): 18 | super(Girl, self).__init__(name) 19 | self.real_name = "Aoi sola" 20 | 21 | def get_name(self): 22 | return self.name 23 | 24 | if __name__ == "__main__": 25 | cang = Girl("canglaoshi") 26 | print(cang.get_name()) 27 | print(cang.height(160)) 28 | print(cang.breast(90)) 29 | -------------------------------------------------------------------------------- /1code/guessnumber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import random 5 | 6 | i=0 7 | while i < 4: 8 | print('********************************') 9 | num = input('请您输入0到9任一个数:') 10 | 11 | xnum = random.randint(0,9) 12 | 13 | x = 3 - i 14 | 15 | if num == xnum: 16 | print('运气真好,您猜对了!') 17 | break 18 | elif num > xnum: 19 | print('''您猜大了!\n哈哈,正确答案是:%s\n您还有%s次机会!''' %(xnum,x)) 20 | elif num < xnum: 21 | print('''您猜小了!\n哈哈,正确答案是:%s\n您还有%s次机会!''' %(xnum,x)) 22 | print('********************************') 23 | 24 | i += 1 25 | 26 | -------------------------------------------------------------------------------- /python3code/chapter05/account.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: account.py 4 | ''' 5 | class Account(object): 6 | def __init__(self, number): 7 | self.number = number 8 | self.balance = 0 9 | 10 | def deposit(self, amount): 11 | try: 12 | assert amount > 0 13 | self.balance += amount 14 | except: 15 | print("The money should be bigger than zero.") 16 | 17 | def withdraw(self, amount): 18 | assert amount > 0 19 | if amount <= self.balance: 20 | self.balance -= amount 21 | else: 22 | print("balance is not enough.") 23 | 24 | if __name__ == "__main__": 25 | a = Account(1000) 26 | a.deposit(-10) 27 | -------------------------------------------------------------------------------- /3code/web/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import tornado.ioloop 5 | import tornado.options 6 | import tornado.httpserver 7 | 8 | from application import application 9 | 10 | from tornado.options import define, options 11 | 12 | define("port", default = 8000, help = "run on the given port", type = int) 13 | 14 | def main(): 15 | tornado.options.parse_command_line() 16 | http_server = tornado.httpserver.HTTPServer(application) 17 | http_server.listen(options.port) 18 | 19 | print "Development server is running at http://127.0.0.1:%s" % options.port 20 | print "Quit the server with Control-C" 21 | 22 | tornado.ioloop.IOLoop.instance().start() 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /2code/21401p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | the interator as range() 6 | """ 7 | class MyRange(object): 8 | def __init__(self, n): 9 | self.i = 1 10 | self.n = n 11 | 12 | def __iter__(self): 13 | return self 14 | 15 | def __next__(self): 16 | if self.i <= self.n: 17 | i = self.i 18 | self.i += 1 19 | return i 20 | else: 21 | raise StopIteration() 22 | 23 | if __name__ == "__main__": 24 | x = MyRange(7) 25 | print([i for i in x]) 26 | #print list(x) 27 | #print "x.next()==>", x.next() 28 | #print "x.next()==>", x.next() 29 | #print "------for loop--------" 30 | #for i in x: 31 | # print i 32 | -------------------------------------------------------------------------------- /newcodes/answers/q71.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class StatWrod(dict): 5 | def add(self, item, increment=1): 6 | self[item] = increment + self.get(item, 0) 7 | def counts(self, reverse=False): 8 | aux = [(self[k], k) for k in self] 9 | aux.sort() 10 | if reverse: 11 | aux.reverse() 12 | return [(v, k) for v,k in aux] 13 | 14 | if __name__ == "__main__": 15 | sentence = "Don't stay in bed, unless you can make money in bed." 16 | words = sentence.split() 17 | c = StatWrod() 18 | for word in words: 19 | c.add(word) 20 | print("Ascending count:") 21 | print(c.counts()) 22 | print("Descending count:") 23 | print(c.counts(reverse=True)) 24 | -------------------------------------------------------------------------------- /newcodes/special_rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class NewRectangle: 5 | def __init__(self): 6 | self.width = 0 7 | self.length = 0 8 | 9 | def __setattr__(self, name, value): 10 | if name == "size": 11 | self.width, self.length = value 12 | else: 13 | self.__dict__[name] = value 14 | 15 | def __getattr__(self, name): 16 | if name == "size": 17 | return self.width, self.length 18 | else: 19 | raise AttributeError 20 | 21 | if __name__ == "__main__": 22 | r = NewRectangle() 23 | r.width = 3 24 | r.length = 4 25 | print(r.size) 26 | r.size = 30, 40 27 | print(r.width) 28 | print(r.length) 29 | -------------------------------------------------------------------------------- /newcodes/answers/q58.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | 5 | def clean_word(word): 6 | return word.strip().lower() 7 | 8 | def get_vowels_in_word(word): 9 | vowel_str = "aeiou" 10 | vowels_in_word = "" 11 | for char in word: 12 | if char in vowel_str: 13 | vowels_in_word += char 14 | return vowels_in_word 15 | 16 | if __name__ == "__main__": 17 | data_file = open("dictionary.txt", "r") 18 | print("Find words containing vowels 'aeiou' in that order:") 19 | for word in data_file: 20 | word = clean_word(word) 21 | if len(word) <= 6: 22 | continue 23 | vowel_str = get_vowels_in_word(word) 24 | if vowel_str == "aeiou": 25 | print(word) 26 | -------------------------------------------------------------------------------- /newcodes/answers/q70.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import re 5 | 6 | class make_xlat: 7 | def __init__(self, *args, **kwargs): 8 | self.adict = dict(*args, **kwargs) 9 | self.rx = self.make_rx() 10 | 11 | def make_rx(self): 12 | return re.compile('|'.join(map(re.escape, self.adict))) 13 | 14 | def one_xlat(self, match): 15 | return self.adict[match.group(0)] 16 | 17 | def __call__(self, text): 18 | return self.rx.sub(self.one_xlat, text) 19 | 20 | if __name__ == "__main__": 21 | text = "PHP is the best language" 22 | adict = {"PHP": "Canglaoshi", "language":"teacher",} 23 | t = make_xlat(adict) 24 | print(text) 25 | print("--->") 26 | print(t(text)) 27 | -------------------------------------------------------------------------------- /2code/20501p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | solving a quadratic equation 6 | """ 7 | 8 | import math 9 | 10 | def quadratic_equation(a,b,c): 11 | delta = b*b - 4*a*c 12 | if delta<0: 13 | return False 14 | elif delta==0: 15 | return -(b/(2*a)) 16 | else: 17 | sqrt_delta = math.sqrt(delta) 18 | x1 = (-b + sqrt_delta)/(2*a) 19 | x2 = (-b - sqrt_delta)/(2*a) 20 | return x1, x2 21 | if __name__ == "__main__": 22 | print("a quadratic equation: x^2 + 2x + 1 = 0") 23 | coefficients = (1, 2, 1) 24 | roots = quadratic_equation(*coefficients) 25 | if roots: 26 | print("the result is:{}".format(roots)) 27 | else: 28 | print("this equation has no solution.") 29 | -------------------------------------------------------------------------------- /python3code/chapter04/rectangle2.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: rectangle2.py 4 | ''' 5 | 6 | class NewRectangle: 7 | def __init__(self): 8 | self.width = 0 9 | self.length = 0 10 | 11 | def __setattr__(self, name, value): 12 | if name == "size": 13 | self.width, self.length = value 14 | else: 15 | self.__dict__[name] = value 16 | 17 | def __getattr__(self, name): 18 | if name == "size": 19 | return self.width, self.length 20 | else: 21 | raise AttributeError 22 | 23 | if __name__ == "__main__": 24 | r = NewRectangle() 25 | r.width = 3 26 | r.length = 4 27 | print(r.size) 28 | r.size = 30, 40 29 | print(r.width) 30 | print(r.length) 31 | -------------------------------------------------------------------------------- /3code/web/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Learning Python 7 | 9 | 10 |
11 | {% block header %}{% end %} 12 |
13 | 14 | {% block body %}{% end %} 15 | 16 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /2code/20905.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Person(object): 5 | def __init__(self, name): 6 | self.name = name 7 | 8 | def height(self, m): 9 | h = dict((["height", m],)) 10 | return h 11 | 12 | def breast(self, n): 13 | b = dict((["breast", n],)) 14 | return b 15 | 16 | class Girl(Person): 17 | def __init__(self, name): 18 | #Person.__init__(self, name) 19 | super(Girl, self).__init__(name) 20 | self.real_name = "Aoi sola" 21 | 22 | def get_name(self): 23 | return self.name 24 | 25 | if __name__ == "__main__": 26 | cang = Girl("canglaoshi") 27 | print cang.real_name 28 | print cang.get_name() 29 | print cang.height(160) 30 | print cang.breast(90) 31 | -------------------------------------------------------------------------------- /2code/23503.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import cairo 5 | from contextlib import contextmanager 6 | 7 | @contextmanager 8 | def saved(cr): 9 | cr.save() 10 | try: 11 | yield cr 12 | finally: 13 | cr.restore() 14 | 15 | def tree(angle): 16 | cr.move_to(0, 0) 17 | cr.translate(0, -65) 18 | cr.line_to(0, 0) 19 | cr.stroke() 20 | cr.scale(0.72, 0.72) 21 | if angle > 0.72: 22 | for a in [-angle, angle]: 23 | with saved(cr): 24 | cr.rotate(a) 25 | tree(angle * 0.75) 26 | 27 | surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 280, 204) 28 | cr = cairo.Context(surf) 29 | cr.translate(140, 203) 30 | cr.set_line_width(5) 31 | tree(0.75) 32 | surf.write_to_png('fractal-tree.png') 33 | -------------------------------------------------------------------------------- /2code/20501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | solving a quadratic equation 6 | """ 7 | 8 | from __future__ import division 9 | import math 10 | 11 | def quadratic_equation(a,b,c): 12 | delta = b*b - 4*a*c 13 | if delta<0: 14 | return False 15 | elif delta==0: 16 | return -(b/(2*a)) 17 | else: 18 | sqrt_delta = math.sqrt(delta) 19 | x1 = (-b + sqrt_delta)/(2*a) 20 | x2 = (-b - sqrt_delta)/(2*a) 21 | return x1, x2 22 | 23 | if __name__ == "__main__": 24 | print "a quadratic equation: x^2 + 3x + 2 = 0" 25 | coefficients = (1, 3, 2) 26 | roots = quadratic_equation(*coefficients) 27 | if roots: 28 | print "the result is:",roots 29 | else: 30 | print "this equation has no solution." 31 | -------------------------------------------------------------------------------- /2code/23502.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class ContextManagerOpenDemo(object): 5 | def __init__(self, filename, mode): 6 | self.filename = filename 7 | self.mode = mode 8 | 9 | def __enter__(self): 10 | print "Starting the Manager." 11 | self.open_file = open(self.filename, self.mode) 12 | return self.open_file 13 | 14 | #def __exit__(self, *others): 15 | # self.open_file.close() 16 | # print "Exiting the Manager." 17 | 18 | def __exit__(self, exc_type, exc_value, exc_traceback): 19 | #return SyntaxError != exc_type 20 | return False 21 | 22 | with ContextManagerOpenDemo("23501.txt", 'r') as reader: 23 | print "In the Manager." 24 | for line in reader: 25 | print lines 26 | 27 | -------------------------------------------------------------------------------- /3code/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import tornado.httpserver 5 | import tornado.ioloop 6 | import tornado.options 7 | import tornado.web 8 | 9 | from tornado.options import define, options 10 | define("port", default=8000, help="run on the given port", type=int) 11 | 12 | class IndexHandler(tornado.web.RequestHandler): 13 | def get(self): 14 | greeting = self.get_argument('greeting', 'Helloi World') 15 | self.write(greeting + '\nwelcome you to read: www.itdiffer.com') 16 | 17 | if __name__ == "__main__": 18 | tornado.options.parse_command_line() 19 | app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) 20 | http_server = tornado.httpserver.HTTPServer(app) 21 | http_server.listen(options.port) 22 | tornado.ioloop.IOLoop.instance().start() 23 | -------------------------------------------------------------------------------- /newcodes/answers/q68.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import math 5 | 6 | class Point: 7 | def __init__(self, x=0.0, y=0.0): 8 | self.x = x 9 | self.y = y 10 | 11 | def __str__(self): 12 | return "({:.2f}, {:.2f})".format(self.x, self.y) 13 | 14 | def distance(self, p): 15 | delta_x = self.x - p.x 16 | delta_y = self.y - p.y 17 | return math.sqrt(delta_x ** 2 + delta_y ** 2) 18 | 19 | def sum(self, p): 20 | x_new = self.x + p.x 21 | y_new = self.y + p.y 22 | return Point(x_new, y_new) 23 | 24 | if __name__ == "__main__": 25 | p1 = Point(2.0, 4.0) 26 | p2 = Point(1.0, 5.0) 27 | d = p1.distance(p2) 28 | print("The distance is {0}".format(d)) 29 | s = p1.sum(p2) 30 | print("The new point is:{0}".format(s)) 31 | -------------------------------------------------------------------------------- /2code/23502p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class ContextManagerOpenDemo(object): 5 | def __init__(self, filename, mode): 6 | self.filename = filename 7 | self.mode = mode 8 | 9 | def __enter__(self): 10 | print("Starting the Manager.") 11 | self.open_file = open(self.filename, self.mode) 12 | return self.open_file 13 | 14 | def __exit__(self, *others): 15 | self.open_file.close() 16 | print("Exiting the Manager.") 17 | 18 | #def __exit__(self, exc_type, exc_value, exc_traceback): 19 | #return SyntaxError != exc_type 20 | #return False 21 | 22 | with ContextManagerOpenDemo("23501.txt", 'r') as reader: 23 | #with ContextManagerOpenDemo(): 24 | print("In the Manager.") 25 | for line in reader: 26 | print(line) 27 | 28 | -------------------------------------------------------------------------------- /newcodes/answers/q48.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #coding:utf-8 3 | 4 | def char_to_number(by_list, char): #根据排序依据字母顺序,给另外一个字母编号 5 | try: 6 | return by_list.index(char) 7 | except: 8 | return 1000 9 | 10 | def sort_by_list(by_list, input_list): 11 | result={} 12 | for word in input_list: 13 | number_list = [char_to_number(by_list,word[i]) for i in range(len(word))] 14 | result[word] = number_list 15 | return [v[0] for v in sorted(result.items(), key=lambda x:x[1])] 16 | 17 | if __name__=="__main__": 18 | word = ["bed","dog","dear","eye"] 19 | by_string = ['d','g','e','c','f','b','o','a'] 20 | print("the word list is:") 21 | print(word) 22 | print("\nwill sorted by:") 23 | print(by_string) 24 | print("\nthe result is:") 25 | print(sort_by_list(by_string,word)) 26 | -------------------------------------------------------------------------------- /newcodes/answers/q43.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import random 5 | 6 | number = random.randint(1,100) 7 | guess = 0 8 | 9 | while True: 10 | num_input = input("please input one integer that is in 1 to 100:") 11 | guess += 1 12 | 13 | if not num_input.isdigit(): 14 | print("Please input interger.") 15 | elif int(num_input) < 0 or int(num_input) >= 100: 16 | print("The number should be in 1 to 100.") 17 | else: 18 | if number == int(num_input): 19 | print("OK, you are good. It is only {0}, then you successed the number is {1}.".format(guess, num_input)) 20 | break 21 | elif number > int(num_input): 22 | print("your number is smaller.") 23 | elif number < int(num_input): 24 | print("your number is bigger.") 25 | -------------------------------------------------------------------------------- /2code/21702.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | try... except 6 | """ 7 | 8 | while 1: 9 | print "this is a division program." 10 | c = raw_input("input 'c' continue, otherwise logout:") 11 | if c == 'c': 12 | a = raw_input("first number:") 13 | b = raw_input("second number:") 14 | try: 15 | print float(a)/float(b) 16 | print "*************************" 17 | #except ZeroDivisionError: 18 | # print "The second number can't be zero!" 19 | # print "*************************" 20 | #except ValueError: 21 | # print "please input number." 22 | # print "************************" 23 | except: 24 | print "some wrong..." 25 | print "********************" 26 | else: 27 | break 28 | 29 | -------------------------------------------------------------------------------- /newcodes/answers/q64.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Goods: 5 | def __init__(self, price,whole_sale, discount): 6 | self.price = price 7 | self.whole_sale = whole_sale 8 | self.discount = discount 9 | 10 | def register_sale(self, count): 11 | self.count = count 12 | if self.count > self.whole_sale: 13 | self.price = self.price * self.discount 14 | 15 | def display_sale(self): 16 | print("The count of goods is:{0}".format(self.count)) 17 | sales = self.price * self.count 18 | print("The total sales is:{0}".format(round(sales, 2))) 19 | 20 | if __name__ == "__main__": 21 | price = 106.78 22 | whole_sale = 60 23 | discount = 0.7 24 | goods = Goods(price, whole_sale, discount) 25 | goods.register_sale(100) 26 | goods.display_sale() 27 | 28 | -------------------------------------------------------------------------------- /newcodes/answers/q35.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def salary(base_salary, work_days, off_days, add_days): 5 | salary = base_salary 6 | if off_days == 0: 7 | salary = salary + salary*0.2 8 | elif off_days > 0 and off_days <= 2: 9 | salary = salary 10 | elif off_days > 2 and off_days <=7: 11 | salary = salary * 0.9 12 | elif off_days > 7 and off_days <= 14: 13 | salary = salary * 0.5 14 | else: 15 | return 0 16 | 17 | if add_days > 0: 18 | more_salary = add_days * base_salary / work_days 19 | salary = salary + more_salary 20 | 21 | return salary 22 | 23 | if __name__ == "__main__": 24 | base_salary = 5000.00 25 | work_days = 21 26 | off_days = 0 27 | add_days = 5 28 | s = salary(base_salary, work_days, off_days, add_days) 29 | print(round(s, 2)) 30 | -------------------------------------------------------------------------------- /1code/guessnumber2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import random 5 | 6 | number = random.randint(1,100) 7 | 8 | guess = 0 9 | 10 | while True: 11 | 12 | num_input = input("please input one integer that is in 1 to 100:") 13 | guess += 1 14 | 15 | if not num_input.isdigit(): 16 | print("Please input interger.") 17 | elif int(num_input) < 0 or int(num_input) >= 100: 18 | print("The number should be in 1 to 100.") 19 | else: 20 | if number == int(num_input): 21 | print("OK, you are good.It is only %d, then you successed." % guess) 22 | break 23 | elif number > int(num_input): 24 | print("your number is smaller.") 25 | elif number < int(num_input): 26 | print("your number is bigger.") 27 | else: 28 | print("There is something bad, I will not work") 29 | 30 | -------------------------------------------------------------------------------- /newcodes/answers/q21.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def f_and_c(value): 5 | unite = value[-1] 6 | v = int(value[:-1]) 7 | try: 8 | if unite == "F": 9 | c = (5*v - 32)/9 10 | return round(c, 2) 11 | elif unite == "C": 12 | f = 9*v/5 + 32 13 | return round(f, 2) 14 | else: 15 | return False 16 | except: 17 | return False 18 | 19 | if __name__ == "__main__": 20 | while True: 21 | print("you should input the tempreture like: 23C or 65F, NOTE: F and C is upper.") 22 | t = input("input the tempreture:('q'-exit)") 23 | if t == "q": 24 | break 25 | else: 26 | result = f_and_c(t) 27 | if result: 28 | print("the tempreture is {}".format(result)) 29 | else: 30 | print("your value is not right") 31 | -------------------------------------------------------------------------------- /2code/21701.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | try... except 6 | """ 7 | 8 | while 1: 9 | print("this is a division program.") 10 | c = input("input 'c' continue, otherwise logout:") 11 | if c == 'c': 12 | a = input("first number:") 13 | b = input("second number:") 14 | try: 15 | print(float(a)/float(b)) 16 | print("*************************") 17 | #except ZeroDivisionError: 18 | # print("The second number can't be zero!") 19 | # print("*************************") 20 | #except ValueError: 21 | # print("please input number.") 22 | # print("************************") 23 | except (ZeroDivisionError, ValueError) as e: 24 | print(e) 25 | #print("please input rightly.") 26 | print("********************") 27 | else: 28 | break 29 | 30 | -------------------------------------------------------------------------------- /3code/web/statics/js/script.js: -------------------------------------------------------------------------------- 1 | function getCookie(name){ 2 | var x = document.cookie.match("\\b" + name + "=([^;]*)\\b"); 3 | return x ? x[1]:undefined; 4 | } 5 | $(document).ready(function(){ 6 | $("#login").click(function(){ 7 | var user = $("#username").val(); 8 | var pwd = $("#password").val(); 9 | var pd = {"username":user, "password":pwd, "_xsrf":getCookie("_xsrf")}; 10 | $.ajax({ 11 | type:"post", 12 | url:"/", 13 | data:pd, 14 | cache:false, 15 | success:function(data){ 16 | if (data=="-1"){ 17 | window.location.href="/error"; 18 | }else{ 19 | window.location.href = "/user?user="+data; 20 | } 21 | }, 22 | error:function(){ 23 | alert("error!"); 24 | }, 25 | }); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /python3code/chapter02/guessnumber.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: guessnumber.py 4 | ''' 5 | 6 | import random 7 | 8 | number = random.randint(1,100) 9 | 10 | guess = 0 11 | 12 | while True: 13 | 14 | num_input = input("please input one integer that is in 1 to 100:") 15 | guess += 1 16 | 17 | if not num_input.isdigit(): 18 | print("Please input interger.") 19 | elif int(num_input) < 0 or int(num_input) >= 100: 20 | print("The number should be in 1 to 100.") 21 | else: 22 | if number == int(num_input): 23 | print("OK, you've done well.It is only %d, then you succeed." % guess) 24 | break 25 | elif number > int(num_input): 26 | print("your number is smaller.") 27 | elif number < int(num_input): 28 | print("your number is bigger.") 29 | else: 30 | print("There is something bad, I will not work") 31 | -------------------------------------------------------------------------------- /newcodes/answers/q34.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | def average(lst): 5 | total = 0 6 | for i in lst: 7 | total = total + i 8 | ave = total / len(lst) 9 | return ave 10 | 11 | def max_student(dct): 12 | max = 0 13 | for k,v in dct.items(): 14 | if v > max: 15 | max = v 16 | name = k 17 | return (name, max) 18 | 19 | if __name__ == "__main__": 20 | d = {} 21 | score_lst = [] 22 | while True: 23 | name = input("input name:('q'-exit)") 24 | if name == "q": 25 | break 26 | else: 27 | score = int(input("input score:")) 28 | d[name] = score 29 | score_lst.append(score) 30 | 31 | ave = average(score_lst) 32 | print("the average scroe is:{}".format(round(ave, 2))) 33 | name, score = max_student(d) 34 | print("xueba is {0}, his/her score is {1}".format(name, score)) 35 | 36 | 37 | -------------------------------------------------------------------------------- /newcodes/answers/q53.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import math 5 | import cmath 6 | 7 | def solve_be(a, b, c): 8 | delta = b**2 - 4*a*c 9 | if delta == 0: 10 | #x = fractions.Fraction(-b, 2*a) 11 | x = -b / (2*a) 12 | return x 13 | elif delta > 0: 14 | sqrt_delata = math.sqrt(delta) 15 | else: 16 | sqrt_delata = cmath.sqrt(delta) 17 | #x1 = fractions.Fraction((-b + sqrt_delata), 2*a) 18 | #x2 = fractions.Fraction((-b - sqrt_delata), 2*a) 19 | x1 = (-b + sqrt_delata) / (2*a) 20 | x2 = (-b - sqrt_delata) / (2*a) 21 | return (x1, x2) 22 | 23 | if __name__ == "__main__": 24 | print("The binary linear equation is x^2 + 2^x + 3 = 0") 25 | r = solve_be(1, 2, 3) 26 | if len(r) == 1: 27 | print("The equation only has one root. It is:") 28 | print(r) 29 | else: 30 | print("The equation have two root. They are:") 31 | print(r) 32 | -------------------------------------------------------------------------------- /newcodes/answers/q61.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class SchoolKid: 5 | def __init__(self, name, years): 6 | self.name = name 7 | self.years = years 8 | 9 | def get_name(self): 10 | return self.name 11 | 12 | def get_years(self): 13 | return self.years 14 | 15 | def change_name(self, new_name): 16 | self.name = new_name 17 | return self.name 18 | 19 | def change_years(self, new_years): 20 | self.years = new_years 21 | return self.years 22 | 23 | 24 | class ExaggeratingKid(SchoolKid): 25 | def get_years(self): 26 | return self.years + 2 27 | 28 | 29 | if __name__ == "__main__": 30 | tom = SchoolKid("Tom", 12) 31 | print(tom.get_name()) 32 | print(tom.get_years()) 33 | tom.change_years(28) 34 | print(tom.get_years()) 35 | 36 | john = ExaggeratingKid("John", 13) 37 | print(john.get_name()) 38 | print(john.get_years()) 39 | -------------------------------------------------------------------------------- /python3code/chapter04/addfractions.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: addfractions.py 4 | ''' 5 | 6 | def gcd(a, b): 7 | if not a > b: 8 | a, b = b, a 9 | while b != 0: 10 | remainder = a % b 11 | a, b = b, remainder 12 | return a 13 | 14 | def lcm(a, b): 15 | return (a * b) / gcd(a,b) 16 | 17 | class Fraction: 18 | def __init__(self, number, denom=1): 19 | self.number = number 20 | self.denom = denom 21 | 22 | def __str__(self): 23 | return str(self.number) + '/' + str(self.denom) 24 | 25 | __repr__ = __str__ 26 | 27 | def __add__(self, other): 28 | lcm_num = lcm(self.denom, other.denom) 29 | number_sum = (lcm_num / self.denom * self.number) + (lcm_num / other.denom * other.number) 30 | return Fraction(number_sum, lcm_num) 31 | 32 | if __name__ == "__main__": 33 | m = Fraction(1, 3) 34 | n = Fraction(1, 2) 35 | s = m + n 36 | print(m,"+",n,"=",s) 37 | -------------------------------------------------------------------------------- /newcodes/answers/q63.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from datetime import date 5 | 6 | class DateDiff: 7 | def __init__(self, start, end): 8 | self.start = start 9 | self.end = end 10 | 11 | def diff_days(self): 12 | return (self.end - self.start).days 13 | 14 | def diff_months(self): 15 | delta_years = self.end.year - self.start.year 16 | delta_months = delta_years * 12 + (self.end.month - self.start.month) 17 | return delta_months 18 | 19 | def diff_years(self): 20 | delta_years = self.end.year - self.start.year 21 | return delta_years 22 | 23 | if __name__ == "__main__": 24 | start = date(2015,1,1) 25 | end = date(2016,9,3) 26 | print(start, "-->", end) 27 | di = DateDiff(start, end) 28 | print("the days is:{0}".format(di.diff_days())) 29 | print("the months is:{0}".format(di.diff_months())) 30 | print("the years is:{0}".format(di.diff_years())) 31 | -------------------------------------------------------------------------------- /newcodes/answers/q74.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | import time 7 | 8 | def get_data(url): 9 | req = requests.get(url) 10 | 11 | soup = BeautifulSoup(req.text, 'lxml') 12 | try: 13 | table = soup.select("#ContentPlaceHolder1_lbldata table table")[0].find_all("td") 14 | province = table[0].find("b").string 15 | province = str(province) 16 | crop_name = str(table[6].string) 17 | crop_number = str(table[7].string) 18 | return province, crop_name, crop_number 19 | except: 20 | return False 21 | 22 | if __name__ == "__main__": 23 | for i in range(11, 66): 24 | url = "http://202.127.42.157/moazzys/nongqing_result.aspx?year=2015&prov={}%20%20%20&item=01&type=1&radio=1&order1=year_code&order2=prov_code&order3=item_code".format(i) 25 | result = get_data(url) 26 | if result: 27 | print(result) 28 | else: 29 | print("hahha") 30 | time.sleep(1) 31 | -------------------------------------------------------------------------------- /2code/21401.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | the interator as range() 6 | """ 7 | class MyRange(object): 8 | def __init__(self, n): 9 | self.i = 1 10 | self.n = n 11 | 12 | def __iter__(self): 13 | return self 14 | 15 | def next(self): 16 | if self.i <= self.n: 17 | i = self.i 18 | self.i += 1 19 | return i 20 | else: 21 | raise StopIteration() 22 | 23 | if __name__ == "__main__": 24 | x = MyRange(3) 25 | print "self.n=",x.n,";","self.i=",x.i 26 | x.next() 27 | print "self.n=",x.n,";","self.i=",x.i 28 | x.next() 29 | print "self.n=",x.n,";","self.i=",x.i 30 | x.next() 31 | print "self.n=",x.n,";","self.i=",x.i 32 | x.next() 33 | print "self.n=",x.n,";","self.i=",x.i 34 | 35 | #print [i for i in x] 36 | #print list(x) 37 | #print "x.next()==>", x.next() 38 | #print "x.next()==>", x.next() 39 | #print "------for loop--------" 40 | #for i in x: 41 | # print i 42 | -------------------------------------------------------------------------------- /newcodes/answers/q65.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Flower: 5 | def __init__(self, price_table): 6 | self.price_table = price_table 7 | 8 | def buy_flower(self, count, name): 9 | if name in self.price_table: 10 | self.count = count 11 | self.name = name 12 | self.sales = self.price_table[self.name] * self.count 13 | else: 14 | self.sales = 0 15 | 16 | def total(self): 17 | return self.sales 18 | 19 | if __name__ == "__main__": 20 | price = {"petunia":50, "pansy":15, "rose":75, "violet":20, "carnation":80} 21 | print(price) 22 | f = Flower(price) 23 | while True: 24 | my = input("input the name of flower:('q'-exit)") 25 | if my == "q": 26 | print("Bye") 27 | break 28 | else: 29 | count = int(input("input the number that you want to buy_flower:")) 30 | f.buy_flower(count, my) 31 | print("You should pay:{0}".format(round(f.total(), 2))) 32 | 33 | -------------------------------------------------------------------------------- /3code/31301.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # coding = utf-8 3 | 4 | import pandas 5 | import pandas.io.data 6 | import datetime 7 | import urllib2 8 | import csv 9 | 10 | YAHOO = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1" 11 | 12 | def get_quote_today(symbol): 13 | response = urllib2.urlopen(YAHOO % symbol) 14 | reader = csv.reader(response, delimiter=",", quotechar='"') 15 | for row in reader: 16 | if row[0] == symbol: 17 | return row 18 | 19 | def main(): 20 | symbol = "BABA" 21 | 22 | history = pandas.io.data.DataReader(symbol, "yahoo", start="2014/11/11") 23 | print history.tail(3) 24 | 25 | today = datetime.date.today() 26 | df = pandas.DataFrame( columns=["Open", "High", "Low", "Close", "Volume", "Adj Close"], dtype=float) 27 | 28 | row = get_quote_today(symbol) 29 | df.ix[0] = map(float, row[2:]) 30 | 31 | history = history.append(df) 32 | 33 | print "today is %s" % today 34 | print history.tail(2) 35 | 36 | if __name__ == "__main__": 37 | main() 38 | -------------------------------------------------------------------------------- /newcodes/fraction.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding=utf-8 3 | 4 | class Fraction: 5 | def __init__(self, number, denom=1): 6 | self.number = number 7 | self.denom = denom 8 | 9 | def __str__(self): 10 | return str(self.number) + '/' + str(self.denom) 11 | 12 | __repr__ = __str__ 13 | 14 | def __add__(self, other): 15 | lcm_num = lcm(self.denom, other.denom) 16 | number_sum = (lcm_num / self.denom * self.number) + (lcm_num / other.denom * other.number) 17 | return Fraction(number_sum, lcm_num) 18 | 19 | 20 | 21 | def gcd(a, b): #最大公约数 22 | if not a > b: 23 | a, b = b, a 24 | while b != 0: 25 | remainder = a % b 26 | a, b = b, remainder 27 | return a 28 | 29 | def lcm(a, b): #最小公倍数 30 | return (a * b) / gcd(a,b) 31 | 32 | 33 | if __name__ == "__main__": 34 | #f = Fraction(2, 3) 35 | #print(f) 36 | 37 | #print(gcd(8, 20)) 38 | #print(lcm(8, 20)) 39 | 40 | m = Fraction(1, 3) 41 | n = Fraction(1, 2) 42 | s = m + n 43 | print(m,"+",n,"=",s) 44 | -------------------------------------------------------------------------------- /2code/21301.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | """ 5 | study __getattr__ and __setattr__ 6 | """ 7 | 8 | class Rectangle(object): 9 | """ 10 | the width and length of Rectangle 11 | """ 12 | def __init__(self): 13 | self.width = 0 14 | self.length = 0 15 | 16 | def setSize(self, size): 17 | self.width, self.length = size 18 | def getSize(self): 19 | return self.width, self.length 20 | size = property(getSize, setSize) 21 | 22 | class NewRectangle(object): 23 | def __init__(self): 24 | self.width = 0 25 | self.length = 0 26 | 27 | def __setattr__(self, name, value): 28 | if name == "size": 29 | self.width, self.length = value 30 | else: 31 | self.__dict__[name] = value 32 | 33 | def __getattr__(self, name): 34 | if name == "size": 35 | return self.width, self.length 36 | else: 37 | raise AttributeError 38 | 39 | if __name__ == "__main__": 40 | r = NewRectangle() 41 | r.width = 3 42 | r.length = 4 43 | print r.size 44 | r.size = 30, 40 45 | print r.width 46 | print r.length 47 | 48 | -------------------------------------------------------------------------------- /newcodes/answers/q44.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import math 5 | 6 | def isPrime1(n): 7 | if n <= 1: 8 | return False 9 | for i in range(2, int(math.sqrt(n)) + 1): 10 | if n % i == 0: 11 | return False 12 | return True 13 | 14 | def isPrime2(n): 15 | if n <= 1: 16 | return False 17 | i = 2 18 | while i*i <= n: 19 | if n % i == 0: 20 | return False 21 | i += 1 22 | return True 23 | 24 | from itertools import count 25 | 26 | def isPrime3(n): 27 | if n <= 1: 28 | return False 29 | for i in count(2): 30 | if i * i > n: 31 | return True 32 | if n % i == 0: 33 | return False 34 | 35 | def isPrime4(n): 36 | if n <= 1: 37 | return False 38 | if n == 2: 39 | return True 40 | if n % 2 == 0: 41 | return False 42 | i = 3 43 | while i * i <= n: 44 | if n % i == 0: 45 | return False 46 | i += 2 47 | return True 48 | 49 | if __name__ == "__main__": 50 | p = [] 51 | for i in range(1, 10): 52 | if isPrime4(i): 53 | p.append(i) 54 | print(p) 55 | -------------------------------------------------------------------------------- /python3code/chapter04/schoolwork.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: schoolwork.py 4 | ''' 5 | 6 | class Student: 7 | def __init__(self, name, grade, subject): 8 | self.name = name 9 | self.grade = grade 10 | self.subject = subject 11 | def do_work(self, time): 12 | if self.grade > 3 and time > 2: 13 | return True 14 | elif self.grade < 3 and time > 0.5: 15 | return True 16 | else: 17 | return False 18 | 19 | class Teacher: 20 | def __init__(self, name, subject): 21 | self.name = name 22 | self.subject = subject 23 | def evaluate(self, result=True): 24 | if result: 25 | return "You are great." 26 | else: 27 | return "You should work hard" 28 | 29 | stu_zhang = Student('zhang', 5, 'math') 30 | tea_wang = Teacher('wang', 'math') 31 | teacher_said = tea_wang.evaluate(stu_zhang.do_work(1)) 32 | print("Teacher {0} said: {1}, {2}".format(tea_wang.name, stu_zhang.name, teacher_said)) 33 | 34 | stu_newton = Student('Newton', 6, 'physics') 35 | teacher_newton = tea_wang.evaluate(stu_newton.do_work(4)) 36 | print("Teacher {0} said: {1}, {2}".format(tea_wang.name, stu_newton.name, teacher_newton)) 37 | -------------------------------------------------------------------------------- /python3code/chapter05/try_except.py: -------------------------------------------------------------------------------- 1 | # coding:utf-8 2 | ''' 3 | filename: try_except.py 4 | ''' 5 | 6 | # while 1: 7 | # print("this is a division program.") 8 | # c = input("input 'c' continue, otherwise logout:") 9 | # if c == 'c': 10 | # a = input("first number:") 11 | # b = input("second number:") 12 | # try: 13 | # print(float(a)/float(b)) 14 | # print("*************************") 15 | # except ZeroDivisionError: 16 | # print("The second number can't be zero!") 17 | # print("*************************") 18 | # except ValueError: 19 | # print("please input number.") 20 | # print("************************") 21 | # else: 22 | # break 23 | 24 | while 1: 25 | print("this is a division program.") 26 | c = input("input 'c' continue, otherwise logout:") 27 | if c == 'c': 28 | a = input("first number:") 29 | b = input("second number:") 30 | try: 31 | print(float(a)/float(b)) 32 | print("*************************") 33 | except (ZeroDivisionError, ValueError) as e: 34 | print(e) 35 | print("********************") 36 | else: 37 | break 38 | -------------------------------------------------------------------------------- /python3code/chapter04/temperature.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | ''' 3 | filename: temperature.py 4 | ''' 5 | 6 | class Temperature: 7 | coefficient = {"c": (1.0, 0.0, -273.15), "f": (1.8, -273.15, 32.0)} 8 | def __init__(self, **kargs): 9 | assert set(kargs.keys()).intersection("kfcKFC"), "invalid arguments {0}".format(kargs) 10 | name, value = kargs.popitem() 11 | name = name.lower() 12 | setattr(self, name, float(value)) 13 | 14 | def __getattr__(self, name): 15 | try: 16 | eq = self.coefficient[name.lower()] 17 | except KeyError: 18 | raise AttributeError(name) 19 | return (self.k + eq[1]) * eq[0] + eq[2] 20 | 21 | def __setattr__(self, name, value): 22 | name = name.lower() 23 | if name in self.coefficient: 24 | eq = self.coefficient[name] 25 | self.k = (value - eq[2]) / eq[0] - eq[1] 26 | elif name == 'k': 27 | object.__setattr__(self, name, value) 28 | else: 29 | raise AttributeError(name) 30 | 31 | def __str__(self): 32 | return "{0}K".format(self.k) 33 | 34 | def __repr__(self): 35 | return "Temperature(K={0}".format(self.k) 36 | 37 | t = Temperature(c=64) 38 | print("c=64, f=", t.f) 39 | t.f = 23 40 | print("f=23, c=", t.c) 41 | -------------------------------------------------------------------------------- /newcodes/answers/q69.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | class Temperature: 5 | coefficients = {'c':(1.0, 0.0, -273.15), 'f':(1.8, -273.15, 32.0)} 6 | 7 | def __init__(self, **kwargs): 8 | try: 9 | name, value = kwargs.popitem() 10 | except KeyError: 11 | name, value = 'k', 0 12 | 13 | if kwargs or name not in "kcf": 14 | kwargs[name] = value 15 | raise TypeError( 'invalid arguments {0}'.format(kwargs)) 16 | setattr(self, name, float(value)) 17 | 18 | def __getattr__(self, name): 19 | try: 20 | eq = self.coefficients[name] 21 | except KeyError: 22 | raise AttributeError(name) 23 | return (self.k + eq[1]) * eq[0] + eq[2] 24 | 25 | def __setattr__(self, name, value): 26 | if name in self.coefficients: 27 | eq = self.coefficients[name] 28 | self.k = (value - eq[2] ) / eq[0] - eq[1] 29 | elif name == 'k': 30 | object.__setattr__(self, name, value) 31 | else: 32 | raise AttributeError(name) 33 | 34 | def __str__(self): 35 | return "{0}K".format(self.k) 36 | 37 | if __name__ == "__main__": 38 | t = Temperature(f = 70) 39 | print(t.c) 40 | t.c = 23 41 | print(t.f) 42 | print(t.k) 43 | -------------------------------------------------------------------------------- /2code/22701.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import json 5 | 6 | class Person(object): 7 | def __init__(self,name,age): 8 | self.name = name 9 | self.age = age 10 | 11 | def __repr__(self): 12 | return 'Person Object name : %s , age : %d' % (self.name,self.age) 13 | 14 | 15 | def object2dict(obj): #convert Person to dict 16 | d = {} 17 | d['__class__'] = obj.__class__.__name__ 18 | d['__module__'] = obj.__module__ 19 | d.update(obj.__dict__) 20 | return d 21 | 22 | def dict2object(d): #convert dict ot Person 23 | if '__class__' in d: 24 | class_name = d.pop('__class__') 25 | module_name = d.pop('__module__') 26 | module = __import__(module_name) 27 | class_ = getattr(module, class_name) 28 | args = dict((key.encode('ascii'), value) for key,value in d.items()) #get args 29 | inst = class_(**args) #create new instance 30 | else: 31 | inst = d 32 | return inst 33 | 34 | 35 | if __name__ == '__main__': 36 | p = Person('Peter',40) 37 | print p 38 | d = object2dict(p) 39 | print d 40 | o = dict2object(d) 41 | print type(o), o 42 | 43 | dump = json.dumps(p, default=object2dict) 44 | print dump 45 | load = json.loads(dump, object_hook=dict2object) 46 | print load 47 | -------------------------------------------------------------------------------- /newcodes/answers/q45.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #coding:utf-8 3 | 4 | from __future__ import division 5 | import random 6 | 7 | 8 | def score(score_list, course_list, student_num): 9 | course_num = len(course_list) 10 | every_score = [[score_list[j][i] for j in range(course_num)] for i in range(student_num)] 11 | every_total = [sum(every_score[i]) for i in range(student_num)] 12 | ave_course = [sum(score_list[i])/len(score_list[i]) for i in range(len(score_list))] 13 | return (every_score, every_total, ave_course) 14 | 15 | if __name__=="__main__": 16 | 17 | course_list = ["C++","Java","Servlet","JSP","EJB"] 18 | student_num = 20 19 | 20 | score_list = [[random.randint(0,100) for i in range(student_num)] for j in range(len(course_list))] 21 | for i in range(len(course_list)): 22 | print("score of every one in {0}:".format(course_list[i])) 23 | print(score_list[i]) 24 | 25 | every_score, every_total, ave_one_course = score(score_list, course_list, student_num) 26 | print("\n") 27 | print("NEXT IS EVERY ONE SCORE IN EVERY COURSE:") 28 | for name in course_list: 29 | print(name, end=",") 30 | print("\t") 31 | print(every_score) 32 | print("\n") 33 | print("every one all score:\t{0}".format(every_total)) 34 | print("every course of average score:\t{0}".format(ave_one_course)) 35 | -------------------------------------------------------------------------------- /newcodes/answers/q76.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import urllib.request, json 5 | 6 | 7 | def weather(city): 8 | url = "http://apis.baidu.com/heweather/weather/free?city={}".format(city) 9 | 10 | req = urllib.request.Request(url) 11 | req.add_header("apikey", "3befccfb4dde4ef385a62a92e958a204") 12 | 13 | resp = urllib.request.urlopen(req) 14 | content = resp.read() 15 | if content: 16 | return content 17 | 18 | if __name__ == "__main__": 19 | print("Search the weather, Please input the city name.") 20 | while True: 21 | city_name = input("input your city:") 22 | r = weather(city_name) 23 | r_str = r.decode(encoding='utf-8', errors='strict') 24 | r_dict = json.loads(r_str) 25 | weather_values = r_dict["HeWeather data service 3.0"][0] 26 | basic_info = weather_values["basic"] 27 | city_name = basic_info['city'] 28 | daily_forecast = weather_values['daily_forecast'] 29 | #aqi = weather_values['aqi'] 30 | today_forecast = daily_forecast[0] 31 | tomorrow_forecast = daily_forecast[1] 32 | today_date = today_forecast['date'] 33 | tomorrow_date = tomorrow_forecast['date'] 34 | today_pop = today_forecast['pop'] 35 | tomorrow_pop = tomorrow_forecast['pop'] 36 | print("{0}{1}:降水概率{2}%".format(today_date, city_name, today_pop)) 37 | print("{0}{1}:降水概率{2}%".format(tomorrow_date, city_name, tomorrow_pop)) 38 | 39 | -------------------------------------------------------------------------------- /3code/web/handlers/index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | #import tornado.web 5 | import tornado.escape 6 | import methods.readdb as mrd 7 | from base import BaseHandler 8 | 9 | class IndexHandler(BaseHandler): 10 | def get(self): 11 | usernames = mrd.select_columns(table="users",column="username") 12 | one_user = usernames[0][0] 13 | self.render("index.html", user=one_user) 14 | 15 | def post(self): 16 | username = self.get_argument("username") 17 | password = self.get_argument("password") 18 | user_infos = mrd.select_table(table="users",column="*",condition="username",value=username) 19 | if user_infos: 20 | db_pwd = user_infos[0][2] 21 | if db_pwd == password: 22 | #self.set_secure_cookie('user', username) 23 | self.set_current_user(username) 24 | self.write(username) 25 | else: 26 | self.write("-1") 27 | else: 28 | self.write("-1") 29 | 30 | def set_current_user(self, user): 31 | if user: 32 | self.set_secure_cookie('user', tornado.escape.json_encode(user)) 33 | #self.set_secure_cookie('user', user) 34 | else: 35 | self.clear_cookie("user") 36 | 37 | class ErrorHandler(BaseHandler): 38 | def get(self): 39 | self.render("error.html") 40 | 41 | class RegisterHandler(BaseHandler): 42 | def get(self): 43 | self.render("register.html") 44 | 45 | def post(self): 46 | pass 47 | -------------------------------------------------------------------------------- /2code/20502.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | """ 4 | count the examine scores 5 | """ 6 | from __future__ import division 7 | 8 | def average_score(scores): 9 | """ 10 | count average score. 11 | """ 12 | score_values = scores.values() 13 | sum_scores = sum(score_values) 14 | average = sum_scores/len(score_values) 15 | return average 16 | 17 | def sorted_score(scores): 18 | """ 19 | count the list for max to min. 20 | """ 21 | score_lst = [(scores[k],k) for k in scores] 22 | sort_lst = sorted(score_lst, reverse=True) 23 | return [(i[1], i[0]) for i in sort_lst] 24 | 25 | def max_score(scores): 26 | """ 27 | the max scroe and the person's name. 28 | """ 29 | lst = sorted_score(scores) 30 | max_score = lst[0][1] 31 | return [(i[0],i[1]) for i in lst if i[1]==max_score] 32 | 33 | def min_score(scores): 34 | """ 35 | the min score and the person's name. 36 | """ 37 | lst = sorted_score(scores) 38 | min_score = lst[len(lst)-1][1] 39 | return [(i[0],i[1]) for i in lst if i[1]==min_score] 40 | 41 | if __name__ == "__main__": 42 | examine_scores = {"google":98, "facebook":99, "baidu":52, "alibaba":80, "yahoo":49, "IBM":70, "android":76, "apple":99, "amazon":99} 43 | 44 | ave = average_score(examine_scores) 45 | print "the average score is: ",ave 46 | 47 | sor = sorted_score(examine_scores) 48 | print "list of the scores: ",sor 49 | 50 | xueba = max_score(examine_scores) 51 | print "Xueba is: ",xueba 52 | 53 | xuezha = min_score(examine_scores) 54 | print "Xuzha is: ",xuezha 55 | 56 | -------------------------------------------------------------------------------- /2code/20502p3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | """ 4 | 统计考试成绩 5 | """ 6 | 7 | def average_score(scores): 8 | """ 9 | 统计平均分. 10 | """ 11 | score_values = scores.values() 12 | sum_scores = sum(score_values) 13 | average = round(sum_scores/len(score_values), 2) # round(a,2) 保留两位小数 14 | return average 15 | 16 | def sorted_score(scores): 17 | """ 18 | 对成绩从高到低排队. 19 | """ 20 | score_lst = [(scores[k],k) for k in scores] 21 | sort_lst = sorted(score_lst, reverse=True) 22 | return [(i[1], i[0]) for i in sort_lst] 23 | 24 | def max_score(scores): 25 | """ 26 | 成绩最高的姓名和分数. 27 | """ 28 | lst = sorted_score(scores) #引用分数排序的函数sorted_score 29 | max_score = lst[0][1] 30 | return [(i[0],i[1]) for i in lst if i[1]==max_score] 31 | 32 | def min_score(scores): 33 | """ 34 | 成绩最低的姓名和分数. 35 | """ 36 | lst = sorted_score(scores) 37 | min_score = lst[len(lst)-1][1] 38 | return [(i[0],i[1]) for i in lst if i[1]==min_score] 39 | 40 | if __name__ == "__main__": 41 | examine_scores = {"google":98, "facebook":99, "baidu":52, "alibaba":80, "yahoo":49, "IBM":70, "android":76, "apple":99, "amazon":99} 42 | 43 | ave = average_score(examine_scores) 44 | print("the average score is:{}".format(ave)) #平均分 45 | 46 | sor = sorted_score(examine_scores) 47 | print("list of the scores:{}".format(sor)) #成绩表 48 | 49 | xueba = max_score(examine_scores) 50 | print("Xueba is:{}".format(xueba)) #学霸们 51 | 52 | xuezha = min_score(examine_scores) 53 | print("Xuzha is:{}".format(xuezha)) #学渣们 54 | -------------------------------------------------------------------------------- /newcodes/answers/q73.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | import math 5 | 6 | class Measurement: 7 | def __init__(self, val, perc): 8 | self.val = val 9 | self.perc = perc 10 | self.abs = self.val * self.perc / 100 11 | 12 | def __repr__(self): 13 | return "Measurement({0}, {1})".format(self.val, self.perc) 14 | def __str__(self): 15 | return "{0}±{1}%".format(self.val, self.perc) 16 | 17 | def _addition_result(self, result, other_abs): 18 | new_perc = 100 * (math.hypot(self.abs, other_abs) / result) 19 | return Measurement(result, new_perc) 20 | def __add__(self, other): 21 | result = self.val + other.val 22 | return self._addition_result(result, other.abs) 23 | def __sub__(self, other): 24 | result = self.val - other.val 25 | return self._addition_result(result, other.abs) 26 | 27 | def _multiplication_result(self, result, other_perc): 28 | new_perc = math.hypot(self.perc, other_perc) 29 | return Measurement(result, new_perc) 30 | def __mul__(self, other): 31 | result = self.val * other.val 32 | return self._multiplication_result(result, other.perc) 33 | def __truediv__(self, other): 34 | result = self.val / other.val 35 | return self._multiplication_result(result, other.perc) 36 | 37 | if __name__ == "__main__": 38 | m1 = Measurement(110, 0.2) 39 | m2 = Measurement(134, 0.1) 40 | print("m1:{0}".format(m1)) 41 | print("m2:{0}".format(m2)) 42 | print("m1+m2={0}".format(m1+m2)) 43 | print("m1-m2={0}".format(m1-m2)) 44 | print("m1*m2={0}".format(m1*m2)) 45 | print("m1/m2={0}".format(m1/m2)) 46 | -------------------------------------------------------------------------------- /newcodes/answers/q72.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | from bisect import bisect_left, insort_left 5 | 6 | class Ratings(dict): 7 | def __init__(self, *args, **kwargs): 8 | dict.__init__(self, *args, **kwargs) 9 | self._rating = [(v, k) for k, v in dict.items(self)] 10 | self._rating.sort() 11 | print(self._rating) 12 | def copy(self): 13 | return Ratings(self) 14 | 15 | def __setitem__(self, k, v): 16 | if k in self: 17 | del self._rating[self.rating(k)] 18 | dict.__setitem__(self, k, v) 19 | insort_left(self._rating, (v, k)) 20 | 21 | def __delitem__(self, k): 22 | del self._rating[self.rating(k)] 23 | dict.__delitem__(self, k) 24 | 25 | __len__ = dict.__len__ 26 | __contains__ = dict.__contains__ 27 | 28 | def __iter__(self): 29 | for v,k in self._rating: 30 | yield k 31 | 32 | iterkeys = __iter__ 33 | 34 | def keys(self): 35 | return list(self) 36 | 37 | def rating(self, key): 38 | item = self[key], key 39 | i = bisect_left(self._rating, item) 40 | print(i) 41 | if item == self._rating[i]: 42 | return i 43 | raise LookupError("item not found in rating") 44 | 45 | def get_value_by_rating(self, rating): 46 | return self._rating[rating][0] 47 | 48 | def get_key_by_rating(self, rating): 49 | return self._rating[rating][1] 50 | 51 | if __name__ == "__main__": 52 | d = {"zhangsan":78, "lisi":98, "wangwu":76, "zhaoliu":82} 53 | print(d) 54 | r = Ratings(d) 55 | print(r.keys()) 56 | print(r.get_value_by_rating(0)) 57 | print(r.rating("zhangsan")) 58 | -------------------------------------------------------------------------------- /newcodes/answers/q50.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | import math 4 | 5 | def sorted_sides(sides_lst): 6 | sides = sorted(sides_lst) 7 | x, y, z = sides[0], sides[1], sides[2] 8 | return float(x), float(y), float(z) 9 | 10 | def is_triangle(sides_lst): 11 | x, y, z = sorted_sides(sides_lst) 12 | if x >=0: 13 | if (x + y > z): 14 | return True 15 | else: 16 | return False 17 | else: 18 | return False 19 | 20 | def side_triangle(sides_lst): 21 | x, y, z = sorted_sides(sides_lst) 22 | if x == y or y == z: 23 | return "isosceles" 24 | elif x == z: 25 | return "equilateral" 26 | else: 27 | return "scalene" 28 | 29 | def angle_triangle(sides_lst): 30 | x, y, z = sorted_sides(sides_lst) 31 | difference = z**2 - (x**2 + y**2) 32 | if difference == 0: 33 | return "right" 34 | elif difference > 0: 35 | return "obtuse" 36 | else: 37 | return "acute" 38 | 39 | def area_triangle(sides_lst): 40 | x, y, z = sorted_sides(sides_lst) 41 | s = (x + y + z)/2 42 | a = math.sqrt(s*(s-x)*(s-y)*(s-z)) 43 | return round(a, 3) 44 | 45 | if __name__ == "__main__": 46 | triangle_sides = input("please input three sides of triangle, and split them by space:") 47 | sides_lst = triangle_sides.split() 48 | if is_triangle(sides_lst): 49 | result_side = side_triangle(sides_lst) 50 | result_angle = angle_triangle(sides_lst) 51 | area = area_triangle(sides_lst) 52 | print("The triangle is {0} and {1}. Its area is {2}".format(result_side, result_angle, area)) 53 | else: 54 | print("Sorry, the sides cannot be the side of triangle.") 55 | -------------------------------------------------------------------------------- /newcodes/answers/q75.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | 4 | class Particle: 5 | def __init__(self, name="", position=(0.0, 0.0, 0.0), velocity=(0.0, 0.0, 0.0), spin=0.0): 6 | self.position = position 7 | self.velocity = velocity 8 | self.name = name 9 | self.spin = spin 10 | def __str__(self): 11 | pos = "({0:.2f}:{1:.2f}:{2:.2f})".format(self.position[0], self.position[1], self.position[2]) 12 | vel = "({0:.2f}:{1:.2f}:{2:.2f})".format(self.velocity[0], self.velocity[1], self.velocity[2]) 13 | the_str = "{0}\n at {1}\n with velocity {2}\n and spin {3}\n".format(self.name, pos, vel, self.spin) 14 | return the_str 15 | 16 | class MassParticle(Particle): 17 | def __init__(self, name="", position=(0.0, 0.0, 0.0), velocity=(0.0, 0.0, 0.0), spin=0.0, mass=0.0): 18 | super(MassParticle, self).__init__(name, position, velocity, spin) 19 | self.mass = mass 20 | def __str__(self): 21 | temp_str = super(MassParticle, self).__str__() 22 | temp_str = temp_str + " and mass {0}\n".format(self.mass) 23 | return temp_str 24 | 25 | class ChargeParticle(MassParticle): 26 | def __init__(self, name="", position=(0.0, 0.0, 0.0), velocity=(0.0, 0.0, 0.0), spin=0.0, mass=0.0, charge=0.0): 27 | super(ChargeParticle, self).__init__(name, position, velocity, spin, mass) 28 | self.charge = charge 29 | def __str__(self): 30 | temp_str = super(MassParticle, self).__str__() 31 | temp_str = temp_str + " and charge {0}".format(self.charge) 32 | return temp_str 33 | 34 | if __name__ == "__main__": 35 | photon = Particle(name="photon", spin=1.0) 36 | tau = ChargeParticle(name="tau", spin=0.5, charge=-1.0, mass=1.777) 37 | print(photon) 38 | print(tau) 39 | -------------------------------------------------------------------------------- /n001.md: -------------------------------------------------------------------------------- 1 | #如何成为Python高手 2 | 3 | 这篇文章是我收集的一些文章的摘要。因为已经有很多比我有才华的人写出了大量关于如何成为优秀Python程序员的好文章。 4 | 5 | 我的总结主要集中在四个基本题目上: 6 | 7 | - 函数式编程, 8 | - 性能, 9 | - 测试, 10 | - 编码规范。 11 | 12 | 如果一个程序员能将这四个方面的内容知识都吸收消化,那他/她不管怎样都会有巨大的收获。 13 | 14 | ##函数式编程 15 | 16 | 命令式的编程风格已经成为事实上的标准。命令式编程的程序是由一些描述状态转变的语句组成。虽然有时候这种编程方式十分的有效,但有时也不尽如此(比如复杂性) ―― 而且,相对于声明式编程方式,它可能会显得不是很直观。 17 | 18 | 如果你不明白我究竟是在说什么,这很正常。这里有一些文章能让你脑袋开窍。但你要注意,这些文章有点像《骇客帝国》里的红色药丸 ―― 一旦你尝试过了函数式编程,你就永远不会回头了。 19 | 20 | - http://www.amk.ca/python/writing/functional 21 | - http://www.secnetix.de/olli/Python/lambda_functions.hawk 22 | - http://docs.python.org/howto/functional.html 23 | 24 | ##性能 25 | 26 | 你会看到有如此多的讨论都在批评这些“脚本语言”(Python,Ruby)是如何的性能低下,可是你却经常的容易忽略这样的事实:是程序员使用的算法导致了程序这样拙劣的表现。 27 | 28 | 这里有一些非常好的文章,能让你知道Python的运行时性能表现的细节详情,你会发现,通过这些精炼而且有趣的语言,你也能写出高性能的应用程序。而且,当你的老板质疑Python的性能时,你别忘了告诉他,这世界上第二大的搜索引擎就是用Python写成的 ―― 它叫做Youtube(参考Python摘录) 29 | 30 | - http://jaynes.colorado.edu/PythonIdioms.html 31 | - http://wiki.python.org/moin/PythonSpeed/PerformanceTips 32 | 33 | ##测试 34 | 35 | 如今在计算机科学界,测试可能是一个最让人不知所措的主题了。有些程序员能真正的理解它,十分重视TDD(测试驱动开发)和它的后继者BDD(行为驱动开发)。而另外一些根本不接受,认为这是浪费时间。那么,我现在将告诉你:如果你不曾开始使用TDD/BDD,那你错过了很多最好的东西! 36 | 37 | 这并不只是说引入了一种技术,可以替换你的公司里那种通过愚蠢的手工点击测试应用程序的原始发布管理制度,更重要的是,它是一种能够让你深入理解你自己的业务领域的工具 ―― 真正的你需要的、你想要的攻克问题、处理问题的方式。如果你还没有这样做,请试一下。下面的这些文章将会给你一些提示: 38 | 39 | - http://www.oreillynet.com/lpt/a/5463 40 | - http://www.oreillynet.com/lpt/a/5584 41 | - http://wiki.cacr.caltech.edu/danse/index.php/Unit_testing_and_Integration_testing 42 | - http://docs.python.org/library/unittest.html 43 | 44 | ##编码规范 45 | 46 | 并非所有的代码生来平等。有些代码可以被另外的任何一个好的程序员读懂和修改。但有些却只能被读,而且只能被代码的原始作者修改 ―― 而且这也只是在他或她写出了这代码的几小时内可以。为什么会这样?因为没有经过代码测试(上面说的)和缺乏正确的编程规范。 47 | 48 | 下面的文章给你描述了一个最小的应该遵守的规范合集。如果按照这些指导原则,你将能编写出更简洁和漂亮的代码。作为附加效应,你的程序会变得可读性更好,更容易的被你和任何其他人修改。 49 | 50 | - http://www.python.org/dev/peps/pep-0008/ 51 | - http://www.fantascienza.net/leonardo/ar/python_best_practices.html 52 | 53 | 那就去传阅这这些资料吧。从坐在你身边的人开始。也许在下一次程序员沙龙或编程大会的时候,也已经成为一名Python编程高手了! 54 | 55 | 祝你学习旅途顺利。 56 | 57 | >本文来源:http://blogread.cn/it/article/3892?f=wb 58 | -------------------------------------------------------------------------------- /n004.md: -------------------------------------------------------------------------------- 1 | #机器学习编程语言之争,Python夺魁 2 | 3 | 来源:http://www.infoq.com/cn/news/2015/09/Python 4 | 5 | 随着科技的发展,拥有高容量、高速度和多样性的大数据已经成为当今时代的主题词。数据科学领域中所采用的机器学习编程语言大相径庭。究竟哪种语言最适合机器学习成为争论不休的话题。近日,密西根州立大学的博士生Sebastian Raschka再次发起了机器学习编程语言之争,分析了自己选择Python的原因。 6 | 7 | 目前,机器学习牵涉的编程语言十分多样,包括了MATLAB、Julia、R、Perl、Python、Ruby等等。首先,Raschka定义了语言好坏的原则:一门好的语言应该使得编写、调试和执行代码的总时间最短。然后,他花大篇幅讲述了一个简单的道理——没有一门语言是对所有情况、所有人都十分适合的。 8 | 9 | >Roberto Waltman:“在这种唯一正确的方式下,面向对象的Spaghetti code就是Lasagna code。” 10 | 11 | 针对具体的应用场景以及参与项目的人员,开发团队或个人要对任务需求进行评估,再结合人员对于各个语言的熟悉程度和语言生态环境的情况等等,作出选择。接下来,Raschka开始正式点评各个语言相对与Python在机器学习时的优缺点。 12 | 13 | ##表现平平的MATLAB 14 | 15 | 作为机器学习、模式识别等方面经常使用的工具,MATLAB被放在了第一个分析。Raschka认为,MATLAB在实现机器学习算法时要比Python或者NumPy更加自然。很多高校也在计算机科学相关的课程中教授MATLAB语言。然而,MATLAB也存在很多的缺点:价格昂贵、非开源、性能表现平平、语法不符合程序员的习惯等。例如,MATLAB中矩阵乘积运算操作为X.dot(Y),而Python为X@W,更加简洁、明了。 16 | 17 | ![](./0images/n00401.png) 18 | 19 | 各种语言相对于C的测试性能——C的性能为1.0,越小越好 20 | 从上图可以看出,MATLAB的性能比Python、Go、Java等语言要差很多。Raschka也提到,上图中Python的性能也表现不好。但是,现在性能强劲的GPU为Python提供了强大的后盾。在2010年的时候,Python中的[Theano库](https://theano.readthedocs.org/en/latest/)在CPU上运行时,其速度是NumPy的1.8倍。而Theano在GPU上运行时,其速度就是NumPy的11倍。因此,在目前更高性能的GPU的帮助下,Python性能已经有了更大的改进。 21 | 22 | ##貌似很强大的Julia 23 | 24 | 作为一门新型的语言,Julia在设计之处就充分借鉴了C/Ruby/Python等语言的经验,试图重新融合众家之长,为科学计算提供一个有力的工具。Raschka充分认可了该语言。然而,对于其未来Julia是否会流行,Raschka持保留态度。 25 | 26 | >Bjarne Stroustrup:世界上只有两种语言——大家一直在抱怨的和无人问津的。 27 | 28 | Raschka认为一个语言是否有用又很大程度上取决于其是否流行。只有被广大编程人员所熟知的编程语言,相关的库才会更多,遇到问题时也能够方便的找到答案,且易于团队合作和代码分享。语言本身也会随着社区的关注不断得以改善。在流行度上,Julia并没有什么优势。 29 | 30 | R语言本身无错 31 | 32 | 接下来,Raschka又提到了R语言。其实,Raschka之前使用过R语言,而且还专门撰写了一部有关R语言中Heat map的书。而且,他自己也不认为R语言存在任何令人不满意的地方。据Spectrum IEEE统计,在2015年排名前十的编程语言中,R语言是提升最快的。近期,微软对R语言表现出极大的兴趣。并且很快,微软的Azure便开始支持R语言了。 33 | 34 | >Alan J. Perlis:当某人说“我想要一门编程语言。它要能够根据我的目标自动生成代码”。让他拿根棒棒糖,一边玩去吧! 35 | 36 | Raschka总结R和Python之间的不同在于,R是统计学家开发的(数学)语言,而Python是计算领域科学家开发,可以应用到统计学的编程语言。这就是说,二者都可以很好的应用于数据科学或者机器学习,但Python的语法更容易被程序员所接受。 37 | 38 | ##Perl的没落 39 | 40 | Raschka简单分析了Perl语言。作为一门古老的语言,Perl已经不可避免的走向了没落。Raschka表示,Perl曾经是他学习的第一门语言。但是,Perl目前主要用于简单的脚本编写,已经很少应用在机器学习的算法编写方面。 41 | 42 | ##老而弥坚的Python 43 | 44 | 最后,Raschka夸赞了自己所喜爱的Python语言。尽管Python已经走过了20多年的风雨历程,Raschka认为它仍然可以继续流行下去。而且,Raschka还不遗余力的列出了自己最喜欢的Python工具——NumPy、Theano、scikit-learn、matplotlib等。 45 | 46 | 至于Ruby、Java、Scala、Lua等,Raschka没有亲身体验,暂未点评。 47 | 48 | 对于Raschka的言论,很多人表示赞同,也有不少人反对。有人表示,自己从R切换到Python,主要原因也是Python更方便与团队之外的人进行合作和沟通。也有人表示,作为一个新入门的程序员,利用R进行数据科学的编程可以利用很多现成的库,十分得心应手。更有与Python打过8年交道的资深程序员表示,Julia十分具有吸引力,愿意花时间去尝试该语言。亲爱的读者朋友,你眼中最好的机器学习编程语言又是哪个呢? -------------------------------------------------------------------------------- /n002.md: -------------------------------------------------------------------------------- 1 | #ASCII、Unicode、GBK和UTF-8字符编码的区别联系 2 | 3 | 2015-05-08 实验楼 4 | 5 | 很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物。他们看到8个开关状态是好的,于是他们把这称为“字节”。 6 | 7 | 再后来,他们又做了一些可以处理这些字节的机器,机器开动了,可以用字节来组合出很多状态,状态开始变来变去。他们看到这样是好的,于是它们就这机器称为“计算机”。 8 | 9 | 开始计算机只在美国用。八位的字节一共可以组合出256(2的8次方)种不同的状态。 他们把其中的编号从0开始的32种状态分别规定了特殊的用途,一但终端、打印机遇上约定好的这些字节被传过来时,就要做一些约定的动作,如: 10 | 11 | 遇上0×10, 终端就换行; 12 | 13 | 遇上0×07, 终端就向人们嘟嘟叫; 14 | 15 | 遇上0x1b, 打印机就打印反白的字,或者终端就用彩色显示字母。 16 | 17 | 他们看到这样很好,于是就把这些0×20以下的字节状态称为“控制码”。他们又把所有的空 格、标点符号、数字、大小写字母分别用连续的字节状态表示,一直编到了第127号,这样计算机就可以用不同字节来存储英语的文字了。 18 | 19 | 大家看到这样,都感觉很好,于是大家都把这个方案叫做 ANSI的“Ascii”编码(American Standard Code for Information Interchange,美国信息互换标准代码)。当时世界上所有的计算机都用同样的ASCII方案来保存英文文字。 20 | 21 | 后来,就像建造巴比伦塔一样,世界各地的都开始使用计算机,但是很多国家用的不是英文,他们的字母里有许多是ASCII里没有的,为了可以在计算机保存他们的文字,他们决定采用 127号之后的空位来表示这些新的字母、符号,还加入了很多画表格时需要用下到的横线、竖线、交叉等形状,一直把序号编到了最后一个状态255。 22 | 23 | 从128 到255这一页的字符集被称“扩展字符集”。从此之后,贪婪的人类再没有新的状态可以用了,美帝国主义可能没有想到还有第三世界国家的人们也希望可以用到计算机吧! 24 | 25 | 等中国人们得到计算机时,已经没有可以利用的字节状态来表示汉字,况且有6000多个常用汉字需要保存呢。 26 | 27 | 但是这难不倒智慧的中国人民,我们不客气地把那些127号之后的奇异符号们直接取消掉, 规定: 28 | 29 | 一个小于127的字符的意义与原来相同,但两个大于127的字符连在一起时,就表示一个汉字; 30 | 31 | 前面的一个字节(他称之为高字节)从0xA1用到 0xF7,后面一个字节(低字节)从0xA1到0xFE; 32 | 33 | 34 | 这样我们就可以组合出大约7000多个简体汉字了。 35 | 36 | 在这些编码里,我们还把数学符号、罗马希腊的字母、日文的假名们都编进去了,连在 ASCII 里本来就有的数字、标点、字母都统统重新编了两个字节长的编码,这就是常说的“全角”字符。 37 | 38 | 而原来在127号以下的那些就叫“半角”字符了。 39 | 40 | 中国人民看到这样很不错,于是就把这种汉字方案叫做 “GB2312”。GB2312 是对 ASCII 的中文扩展。 41 | 42 | 但是中国的汉字太多了,我们很快就就发现有许多人的人名没有办法在这里打出来,特别是某些很会麻烦别人的国家领导人。 43 | 44 | 于是我们不得不继续把 GB2312 没有用到的码位找出来老实不客气地用上。 45 | 46 | 后来还是不够用,于是干脆不再要求低字节一定是127号之后的内码,只要第一个字节是大于127就固定表示这是一个汉字的开始,不管后面跟的是不是扩展字符集里的内容。结果扩展之后的编码方案被称为 GBK 标准,GBK包括了GB2312 的所有内容,同时又增加了近20000个新的汉字(包括繁体字)和符号。 47 | 48 | 后来少数民族也要用电脑了,于是我们再扩展,又加了几千个新的少数民族的字,GBK扩成了 GB18030。从此之后,中华民族的文化就可以在计算机时代中传承了。 49 | 50 | 中国的程序员们看到这一系列汉字编码的标准是好的,于是通称他们叫做 “DBCS“(Double Byte Charecter Set 双字节字符集)。 51 | 52 | 在DBCS系列标准里,最大的特点是两字节长的汉字字符和一字节长的英文字符并存于同一套编码方案里,因此他们写的程序为了支持中文处理,必须要注意字串里的每一个字节的值,如果这个值是大于127的,那么就认为一个双字节字符集里的字符出现了。 53 | 54 | 那时候凡是受过加持,会编程的计算机僧侣们都要每天念下面这个咒语数百遍: “一个汉字算两个英文字符!一个汉字算两个英文字符……” 55 | 56 | 因为当时各个国家都像中国这样搞出一套自己的编码标准,结果互相之间谁也不懂谁的编码,谁也不支持别人的编码。 57 | 58 | 连大陆和台湾这样只相隔了150海里,使用着同一种语言的兄弟地区,也分别采用了不同的 DBCS 编码方案——当时的中国人想让电脑显示汉字,就必须装上一个“汉字系统”,专门用来处理汉字的显示、输入的问题,但是那个台湾的愚昧封建人士写的算命程序就必须加装另一套支持 BIG5 编码的什么“倚天汉字系统”才可以用,装错了字符系统,显示就会乱了套!这怎么办?而且世界民族之林中还有那些一时用不上电脑的穷苦人民,他们的文字又怎么办? 真是计算机的巴比伦塔命题啊! 59 | 60 | 正在这时,大天使加百列及时出现了——一个叫 ISO (国际标谁化组织)的国际组织决定着手解决这个问题。 61 | 62 | 他们采用的方法很简单: 63 | 64 | 废了所有的地区性编码方案,重新搞一个包括了地球上所有文化、所有字母和符号 的编码! 65 | 66 | 他们打算叫它”Universal Multiple-Octet Coded Character Set”,简称 UCS, 俗称 “unicode”。 67 | 68 | unicode开始制订时,计算机的存储器容量极大地发展了,空间再也不成为问题了。于是 ISO 就直接规定必须用两个字节,也就是16位来统一表示所有的字符,对于ASCII里的那些“半角”字符,unicode包持其原编码不变,只是将其长度由原来的8位扩展为16位,而其他文化和语言的字符则全部重新统一编码。由于“半角”英文符号只需要用到低8位,所以其高8位永远是0,因此这种大气的方案在保存英文文本时会多浪费一倍的空间。 69 | 70 | 这时候,从旧社会里走过来的程序员开始发现一个奇怪的现象:他们的strlen函数靠不住了,一个汉字不再是相当于两个字符了,而是一个!是的,从unicode开始,无论是半角的英文字母,还是全角的汉字,它们都是统一的“一个字符”!同时,也都是统一的“两个字节”,请注意“字符”和“字节”两个术语的不同: 71 | 72 | “字节”是一个8位的物理存贮单元, 73 | 74 | 而“字符”则是一个文化相关的符号。 75 | 76 | 在unicode中,一个字符就是两个字节。一个汉字算两个英文字符的时代已经快过去了。 77 | 78 | unicode同样也不完美,这里就有两个的问题, 79 | 80 | 一个是,如何才能区别unicode和ascii?计算机怎么知道三个字节表示一个符号,而不是分别表示三个符号呢? 81 | 82 | 第二个问题是,我们已经知道,英文字母只用一个字节表示就够了,如果unicode统一规定,每个符号用三个或四个字节表示,那么每个英文字母前都必然有二到三个字节是0,这对于存储空间来说是极大的浪费,文本文件的大小会因此大出二三倍,这是难以接受的。 83 | 84 | unicode在很长一段时间内无法推广,直到互联网的出现,为解决unicode如何在网络上传输的问题,于是面向传输的众多 UTF(UCS Transfer Format)标准出现了,顾名思义: 85 | 86 | UTF-8就是每次8个位传输数据, 87 | 88 | 而UTF-16就是每次16个位。 89 | 90 | UTF-8就是在互联网上使用最广的一种unicode的实现方式,这是为传输而设计的编码,并使编码无国界,这样就可以显示全世界上所有文化的字符了。 91 | 92 | UTF-8最大的一个特点,就是它是一种变长的编码方式。 93 | 94 | 它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度,当字符在ASCII码的范围时,就用一个字节表示,保留了ASCII字符一个字节的编码做为它的一部分,(注意的是unicode一个中文字符占2个字节,而UTF-8一个中文字符占3个字节)。 95 | 96 | 从unicode到uft-8并不是直接的对应,而是要过一些算法和规则来转换。 97 | 98 | Unicode符号范围 | UTF-8编码方式 99 | 100 | (十六进制) | (二进制) 101 | —————————————————————– 102 | 0000 0000-0000 007F | 0xxxxxxx 103 | 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 104 | 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 105 | 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 106 | 107 | 之前一直对字符编码很模糊,网查资料被忽悠地晕头转向,看完这篇风趣的文章,把之前模糊的知识点串联起来,并稍加总结,我和我的小伙伴们都明白了! 108 | 109 | via:http://toutiao.io/ 110 | 111 | 原文链接:http://dengo.org/archives/901 -------------------------------------------------------------------------------- /n003.md: -------------------------------------------------------------------------------- 1 | #大数据全栈式开发语言 – Python 2 | 3 | 来源:http://www.techug.com/full-stack-python 4 | 5 | 前段时间,ThoughtWorks 在深圳举办一次社区活动上,有一个演讲主题叫做“Fullstack JavaScript”,是关于用 JavaScript 进行前端、服务器端,甚至数据库(MongoDB)开发,一个 Web 应用开发人员,只需要学会一门语言,就可以实现整个应用。 6 | 7 | 受此启发,我发现 Python 可以称为大数据全栈式开发语言。因为 Python 在云基础设施,DevOps,大数据处理等领域都是炙手可热的语言。 8 | 9 | ![](./0images/n00201.png) 10 | 11 | 就像只要会 JavaScript 就可以写出完整的 Web 应用,只要会 Python,就可以实现一个完整的大数据处理平台。 12 | 13 | ##云基础设施 14 | 15 | 这年头,不支持云平台,不支持海量数据,不支持动态伸缩,根本不敢说自己是做大数据的,顶多也就敢跟人说是做商业智能(BI)。 16 | 17 | 云平台分为私有云和公有云。私有云平台如日中天的 OpenStack,就是 Python 写的。曾经的追赶者 CloudStack,在刚推出时大肆强调自己是 Java 写的,比 Python 有优势。结果,搬石砸脚,2015 年初,CloudStack 的发起人 Citrix 宣布加入 OpenStack 基金会,CloudStack 眼看着就要寿终正寝。 18 | 19 | 如果嫌麻烦不想自己搭建私有云,用公有云,不论是 AWS,GCE,Azure,还是阿里云,青云,在都提供了 Python SDK,其中 GCE 只提供 Python 和 JavaScript 的 SDK,而青云只提供 Python SDK。可见各家云平台对 Python 的重视。 20 | 21 | 提到基础设施搭建,不得不提 Hadoop,在今天,Hadoop 因为其 MapReduce 数据处理速度不够快,已经不再作为大数据处理的首选,但是 HDFS 和 Yarn——Hadoop 的两个组件——倒是越来越受欢迎。Hadoop 的开发语言是 Java,没有官方提供 Python 支持,不过有很多第三方库封装了 Hadoop 的 API 接口(pydoop,hadoopy 等等)。 22 | 23 | Hadoop MapReduce 的替代者,是号称快上 100 倍的 Spark,其开发语言是 Scala,但是提供了 Scala,Java,Python 的开发接口,想要讨好那么多用 Python 开发的数据科学家,不支持 Python,真是说不过去。HDFS 的替代品,比如 GlusterFS,Ceph 等,都是直接提供 Python 支持。Yarn 的替代者,Mesos 是 C++ 实现,除 C++ 外,提供了 Java 和 Python 的支持包。 24 | 25 | ##DevOps 26 | 27 | DevOps 有个中文名字,叫做开发自运维。互联网时代,只有能够快速试验新想法,并在第一时间,安全、可靠的交付业务价值,才能保持竞争力。DevOps 推崇的自动化构建/测试/部署,以及系统度量等技术实践,是互联网时代必不可少的。 28 | 29 | 自动化构建是因应用而易的,如果是 Python 应用,因为有 setuptools, pip, virtualenv, tox, flake8 等工具的存在,自动化构建非常简单。而且,因为几乎所有 Linux 系统都内置 Python 解释器,所以用 Python 做自动化,不需要系统预安装什么软件。 30 | 31 | 自动化测试方面,基于 Python 的 Robot Framework 企业级应用最喜欢的自动化测试框架,而且和语言无关。Cucumber 也有很多支持者,Python 对应的 Lettuce 可以做到完全一样的事情。Locust 在自动化性能测试方面也开始受到越来越多的关注。 32 | 33 | 自动化配置管理工具,老牌的如 Chef 和 Puppet,是 Ruby 开发,目前仍保持着强劲的势头。不过,新生代 Ansible 和 SaltStack——均为 Python 开发——因为较前两者设计更为轻量化,受到越来越多开发这的欢迎,已经开始给前辈们制造了不少的压力。 34 | 35 | 在系统监控与度量方面,传统的 Nagios 逐渐没落,新贵如 Sensu 大受好评,云服务形式的 New Relic 已经成为创业公司的标配,这些都不是直接通过 Python 实现的,不过 Python 要接入这些工具,并不困难。 36 | 37 | 除了上述这些工具,基于 Python,提供完整 DevOps 功能的 PaaS 平台,如 Cloudify 和 Deis,虽未成气候,但已经得到大量关注。 38 | 39 | ##网络爬虫 40 | 41 | 大数据的数据从哪里来?除了部分企业有能力自己产生大量的数据,大部分时候,是需要靠爬虫来抓取互联网数据来做分析。 42 | 43 | 网络爬虫是 Python 的传统强势领域,最流行的爬虫框架 Scrapy,HTTP 工具包 urlib2,HTML 解析工具 beautifulsoup,XML 解析器 lxml,等等,都是能够独当一面的类库。 44 | 45 | 不过,网络爬虫并不仅仅是打开网页,解析 HTML 这么简单。高效的爬虫要能够支持大量灵活的并发操作,常常要能够同时几千甚至上万个网页同时抓取,传统的线程池方式资源浪费比较大,线程数上千之后系统资源基本上就全浪费在线程调度上了。Python 由于能够很好的支持协程(Coroutine)操作,基于此发展起来很多并发库,如 Gevent,Eventlet,还有 Celery 之类的分布式任务框架。被认为是比 AMQP 更高效的 ZeroMQ 也是最早就提供了 Python 版本。有了对高并发的支持,网络爬虫才真正可以达到大数据规模。 46 | 47 | 抓取下来的数据,需要做分词处理,Python 在这方面也不逊色,著名的自然语言处理程序包 NLTK,还有专门做中文分词的 Jieba,都是做分词的利器。 48 | 49 | ##数据处理 50 | 51 | 万事俱备,只欠东风。这东风,就是数据处理算法。从统计理论,到数据挖掘,机器学习,再到最近几年提出来的深度学习理论,数据科学正处于百花齐放的时代。数据科学家们都用什么编程? 52 | 53 | 如果是在理论研究领域,R语言也许是最受数据科学家欢迎的,但是R语言的问题也很明显,因为是统计学家们创建了R语言,所以其语法略显怪异。而且R语言要想实现大规模分布式系统,还需要很长一段时间的工程之路要走。所以很多公司使用R语言做原型试验,算法确定之后,再翻译成工程语言。 54 | 55 | Python 也是数据科学家最喜欢的语言之一。和R语言不同,Python 本身就是一门工程性语言,数据科学家用 Python 实现的算法,可以直接用在产品中,这对于大数据初创公司节省成本是非常有帮助的。正式因为数据科学家对 Python 和R的热爱,Spark 为了讨好数据科学家,对这两种语言提供了非常好的支持。 56 | 57 | Python 的数据处理相关类库非常多。高性能的科学计算类库 NumPy 和 SciPy,给其他高级算法打了非常好的基础,matploglib 让 Python 画图变得像 Matlab 一样简单。Scikit-learn 和 Milk 实现了很多机器学习算法,基于这两个库实现的 Pylearn2,是深度学习领域的重要成员。Theano 利用 GPU 加速,实现了高性能数学符号计算和多维矩阵计算。当然,还有 Pandas,一个在工程领域已经广泛使用的大数据处理类库,其 DataFrame 的设计借鉴自R语言,后来又启发了 Spark 项目实现了类似机制。 58 | 59 | 对了,还有 iPython,这个工具如此有用,以至于我差点把他当成标准库而忘了介绍。iPython 是一个交互式 Python 运行环境,能够实时看到每一段 Python 代码的结果。默认情况下,iPython 运行在命令行,可以执行ipython notebook在网页中运行。用 matplotlib 绘制的图可以直接嵌入式的显示在 iPython Notebook 中。 60 | 61 | iPython Notebook 的笔记本文件可以共享给其他人,这样其他人就可以在自己的环境中重现你的工作成果;如果对方没有运行环境,还可以直接转换成 HTML 或者 PDF。 62 | 63 | ##为什么是 Python 64 | 65 | 正是因为应用开发工程师、运维工程师、数据科学家都喜欢 Python,才使得 Python 成为大数据系统的全栈式开发语言。 66 | 67 | **对于开发工程师而言,**Python 的优雅和简洁无疑是最大的吸引力,在 Python 交互式环境中,执行import this,读一读 Python 之禅,你就明白 Python 为什么如此吸引人。Python 社区一直非常有活力,和 NodeJS 社区软件包爆炸式增长不同,Python 的软件包增长速度一直比较稳定,同时软件包的质量也相对较高。有很多人诟病 Python 对于空格的要求过于苛刻,但正是因为这个要求,才使得 Python 在做大型项目时比其他语言有优势。OpenStack 项目总共超过 200 万行代码,证明了这一点。 68 | 69 | **对于运维工程师而言,**Python 的最大优势在于,几乎所有 Linux 发行版都内置了 Python 解释器。Shell 虽然功能强大,但毕竟语法不够优雅,写比较复杂的任务会很痛苦。用 Python 替代 Shell,做一些复杂的任务,对运维人员来说,是一次解放。 70 | 71 | **对于数据科学家而言,**Python 简单又不失强大。和C/C++相比,不用做很多的底层工作,可以快速进行模型验证;和 Java 相比,Python 语法简洁,表达能力强,同样的工作只需要1/3 代码;和 Matlab,Octave 相比,Python 的工程成熟度更高。不止一个编程大牛表达过,Python 是最适合作为大学计算机科学编程课程使用的语言——MIT 的计算机入门课程就是使用的 Python——因为 Python 能够让人学到编程最重要的东西——如何解决问题。 72 | 73 | 顺便提一句,微软参加 2015 年 PyCon,高调宣布提高 Python 在 Windows 上的编程体验,包括 Visual Studio 支持 Python,优化 Python 的C扩展在 Windows 上的编译等等。脑补下未来 Python 作为 Windows 默认组件的场景。 -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | #This is for everyone. 2 | 3 | >In the begning when God created the heavens and the earth. the earth was a formless void and darkness covered the face of the deep, while a wind from God swept over the face of the waters. Then God said,"Let there be light"; and there was light. And God saw that the light was good; and God separated the light from the darkness. (GENESIS 1:1-4) 4 | 5 | #《跟老齐学Python》(入门教程) 6 | 7 | From beginner to master. 8 | 9 | 针对零基础的学习者,试图实现从基础到精通,还要看自己的造化。 10 | 11 | 原名叫做《零基础学Python》,后来由于图书出版,更名为《跟老齐学Python》。 12 | 13 | 《跟老齐学Python》一书已经由电子工业出版社出版,于2016年3月1日起,陆续在亚马逊、京东、当当、淘宝等网站发售,请关注,并感谢支持。 14 | 15 | 此处的在线版与上述印刷的版本有所不同。在印刷出来之后,又发觉有一些地方需要修改,于是就对一部分进行了重写,并且在和朋友们交流后,也会吸收很多意见和建议,用之于修改在线版。其中改动最大的在于,本教程不再包括“实战”部分,而是专门叫做面向零基础的“入门教程”。对于实战部分,我会在适当时候专门撰写。 16 | 17 | #第壹季 基础 18 | 19 | ##第零章 预备 20 | 21 | 1. [关于python的故事](./01.md) 22 | 2. [从小工到专家](./02.md) 23 | 3. [安装python的开发环境](./03.md) 24 | 4. [集成开发环境](./101.md)==>集成开发环境;python的IDE 25 | 26 | ##第壹章 基本数据类型 27 | 28 | 1. [数和四则运算](./102.md)==>整数和浮点数;变量;整数溢出问题; 29 | 2. [除法](./103.md)==>整数、浮点数相除;`from __future__ import division`;余数;四舍五入; 30 | 3. [常用数学函数和运算优先级](./104.md)==>math模块,求绝对值,运算优先级 31 | 4. [写一个简单程序](./105.md)==>程序和语句,注释 32 | 5. [字符串(1)](./106.md)==>字符串定义,转义符,字符串拼接,str()与repr()区别 33 | 6. [字符串(2)](./107.md)==>raw_input,print,内建函数,原始字符串,再做一个小程序 34 | 7. [字符串(3)](./108.md)==>字符串和序列,索引,切片,基本操作 35 | 8. [字符串(4)](./109.md)==>字符串格式化,常用的字符串方法 36 | 9. [字符编码](./110.md)==>编码的基础知识,python中避免汉字乱码 37 | 10. [列表(1)](./111.md)==>列表定义,索引和切片,列表反转,元素追加,基本操作 38 | 11. [列表(2)](./112.md)==>列表append/extend/index/count方法,可迭代的和判断方法,列表原地修改 39 | 12. [列表(3)](./113.md)==>列表pop/remove/reverse/sort方法 40 | 13. [回顾列表和字符串](./114.md)==>比较列表和字符串的相同点和不同点 41 | 14. [元组](./115.md)==>元组定义和基本操作,使用意义 42 | 15. [字典(1)](./116.md)==>字典创建方法、基本操作(长度、读取值、删除值、判断键是否存在) 43 | 16. [字典(2)](./117.md)==>字典方法:copy/deepcopy/clear/get/setdefault/items/iteritems/keys/iterkeys/values/itervalues/pop/popitem/update/has_key 44 | 17. [集合(1)](./118.md)==>创建集合,集合方法:add/update,pop/remove/discard/clear,可哈希与不可哈希 45 | 18. [集合(2)](./119.md)==>不可变集合,集合关系 46 | 47 | ##第贰章 语句和文件 48 | 49 | 1. [运算符](./120.md)==>算数运算符,比较运算符,逻辑运算符/布尔类型 50 | 2. [语句(1)](./121.md)==>print, import, 赋值语句、增量赋值 51 | 3. [语句(2)](./122.md)==>if...elif...else语句,三元操作 52 | 4. [语句(3)](./123.md)==>for循环,range(),循环字典 53 | 5. [语句(4)](./124.md)==>并行迭代:zip(),enumerate(),list解析 54 | 6. [语句(5)](./125.md)==>while循环,while...else,for...else 55 | 7. [文件(1)](./126.md)==>文件打开,读取,写入 56 | 8. [文件(2)](./127.md)==>文件状态,read/readline/readlines,大文件读取,seek 57 | 9. [迭代](./128.md)==>迭代含义,iter() 58 | 10. [练习](./129.md)==>通过四个练习,综合运用以前所学 59 | 11. [自省](./130.md)==>自省概念,联机帮助,dir(),文档字符串,检查对象,文档 60 | 61 | ##第叁章 函数 62 | 63 | 1. [函数(1)](./201.md)==>定义函数方法,调用函数方法,命名方法,使用函数注意事项 64 | 2. [函数(2)](./202.md)==>函数返回值,函数文档,形参和实参 65 | 3. [函数(3)](./203.md)==>收集参数:`*`和`**`,及其逆过程,复习参数知识 66 | 4. [函数(4)](./204.md)==>递归、传递函数、嵌套函数和装饰器 67 | 5. [函数(5)](./242.md)==>闭包 68 | 6. [函数(6)](./237.md)==>filter、map、reduce、lambda、yield 69 | 7. [函数练习](./205.md)==>解一元二次方程,统计考试成绩,找素数 70 | 8. [zip()补充](./236.md)==>对zip()函数的用法进行补充说明 71 | 9. [命名空间](./241.md)==>全局变量和局部变量,作用域,命名空间 72 | 73 | #第贰季 进阶 74 | 75 | ##第肆章 类 76 | 77 | 1. [类(1)](./206.md)==>类的初步认识和基本概念理解:问题空间、对象、面向对象、类和实例化类 78 | 2. [类(2)](./207.md)==>新式类和旧式类,初步创建类和实例化 79 | 3. [类(3)](./208.md)==>类属性、创建实例、实例属性、self作用、类内外数据流转 80 | 4. [类(4)](./238.md)==>绑定方法和非绑定方法,类方法和静态方法 81 | 5. [类(5)](./209.md)==>继承,super,多重继承 82 | 6. [多态和封装](./211.md)==>多态,封装和私有化 83 | 7. [定制类](./239.md)==>类和类型,定制类 84 | 8. [黑魔法](./240.md)==>优化内存的`__slots__`,属性拦截 85 | 9. [迭代器](./214.md)==>迭代器方法`__iter__`,`netx()` 86 | 11. [生成器](./215.md)==>生成器定义,yield,生成器方法 87 | 12. [上下文管理器](./235.md)==>上下文管理器的基本概念,使用方法和contextlib模块 88 | 89 | ##第伍章 错误和异常 90 | 91 | 1. [错误和异常(1)](./216.md)==>什么是错误和异常,常见异常类型,处理异常(try...except...) 92 | 2. [错误和异常(2)](./217.md)==>处理多个异常,else子句,finally子句 93 | 3. [错误和异常(3)](./218.md)==>assert断言,异常小结 94 | 95 | ##第陆章 模块 96 | 97 | 1. [编写模块](./219.md)==>模块是程序,模块的位置 98 | 2. [标准库(1)](./220.md)==>引用模块的方式,dir()查看属性和方法,模块文档和帮助 99 | 3. [标准库(2)](./221.md)==>sys,copy 100 | 4. [标准库(3)](./222.md)==>os模块:操作文件、目录,查看修改属性,执行系统命令,打开网页 101 | 5. [标准库(4)](./223.md)==>堆的基本知识,heapq模块,deque模块 102 | 6. [标准库(5)](./224.md)==>calendar模块、time模块、datetime模块 103 | 7. [标准库(6)](./225.md)==>urllib模块、urllib2模块 104 | 8. [标准库(7)](./226.md)==>xml.etree.ElementTree模块:遍历查询、增删改查xml,应用实例 105 | 9. [标准库(8)](./227.md)==>json模块:dumps(),loads(),dump(),load(),自定义类型数据的json编码和解码 106 | 10. [第三方库](./228.md)==>第三方库的模块安装方法,以requests模块为例说明 107 | 108 | ##第柒章 保存数据 109 | 110 | 1. [将数据存入文件](./229.md)==>pickle模块,shelve模块 111 | 2. [MySQL数据库(1)](./230.md)==>MySQL概况,安装,python连接MySQL模块和方法 112 | 3. [MySQL数据库(2)](./231.md)==>连接对象方法,游标对象方法:数据库的增删改查基本操作 113 | 4. [MongoDB数据库](./232.md)==>mongodb的安装启动,pymongo模块:连接客户端,数据库的增删改查操作 114 | 5. [SQLite数据库](./233.md)==>通过sqlite3模块操作SQLite数据库:连接对象方法,游标对象方法,数据库增删改查 115 | 6. [电子表格](./234.md)==>python操作Excel文件的第三方库openpyxl使用方法,以及其它与Excel相关的第三方库 116 | 117 | ##附:网络文摘 118 | 119 | 1. [如何成为python高手](./n001.md) 120 | 2. [ASCII、Unicode、GBK和UTF-8字符编码的区别联系](./n002.md) 121 | 3. [大数据全栈式开发语言 – Python](./n003.md) 122 | 4. [机器学习编程语言之争,Python夺魁](./n004.md) 123 | 5. [Python 2.7.x 和 3.x 版本的重要区别](./n005.md) --------------------------------------------------------------------------------