差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
后一修订版
前一修订版
public:it:python [2014/12/03 16:49] oakfirepublic:it:python [2024/01/15 15:33] (当前版本) – [Tips] oakfire
行 1: 行 1:
 ====== Python ====== ====== Python ======
   * [[https://www.python.org | Officail site: python.org]]   * [[https://www.python.org | Officail site: python.org]]
 +  * [[http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/key_differences_between_python_2_and_3.ipynb | Key differences between python2 and 3]]
 ===== Tips ===== ===== Tips =====
   * 快速开一个静态http服务: 进入文件夹, 然后 ''python -m SimpleHTTPServer 80''   * 快速开一个静态http服务: 进入文件夹, 然后 ''python -m SimpleHTTPServer 80''
   * In Terminal, type ''pydoc raw_input'' Read what it says about "raw_input". If you're on Windows try ''python -m pydoc raw_input'' instead. Get out of pydoc by typing ''q'' to quit.   * In Terminal, type ''pydoc raw_input'' Read what it says about "raw_input". If you're on Windows try ''python -m pydoc raw_input'' instead. Get out of pydoc by typing ''q'' to quit.
-  * python为动态语言,与js类似, list,dict等object的''=''赋值在默认为引用.  拷贝list用''list2 = list1[:]''之后list2的改动与list1无关.+  * python为动态语言,与js类似, list,dict等object的''=''赋值在默认为引用. 如果不需要引用, 那么拷贝list用''list2 = list1[:]'',之后list2的改动便与list1无关. 
 +  * python 变快的 9 个技巧:[[https://medium.com/techtofreedom/9-subtle-tricks-to-make-your-python-code-much-faster-50be6dd69a30|9-subtle-tricks-to-make-your-python-code-much-faster]] 
 +    * 拼接字符串的速度, 直接 ''+'' 快于  ''join()'' 快于 ''+='' 一项项加. 
 +    * Faster List Creation: Use “[]” Over “list()” 用 ''[]''来初始化列表 
 +    * Faster Membership Testing: Use a Set Over a List 
 +    * Faster Data Generation: Use Comprehensions Over For Loops  用内包代替循环 
 +    * Faster Loops: Prioritize Local Variables 优先使用局部变量 
 +    * Faster Execution: Prioritize Built-In Modules and Libraries 优先用内置模块和库 
 +    * Faster Function Calls: Leverage Cache Decorator for Easy Memoization   
 +    * Faster Infinite Loop: Prefer “while 1” Over “while True” 但是现代解释器基本都优化过, ''while TRUE'' 还更有可读性 
 +    * Faster Start-Up: Import Python Modules Smartly 
 ===== 从零开始 ===== ===== 从零开始 =====
-  * [[http://learnpythonthehardway.org/book/ | learn python the hard way]] +  * [[http://learnpythonthehardway.org/book/ | learn python the hard way]] python2. 
-  * <code python> +  * Learning more: 
-ex1: Print -------------------------------------------------------------------------+      * [[http://learnrubythehardway.org/|Learn Ruby The Hard Way]] You will learn even more about programming as you learn more programming languages, so try learning Ruby too. 
 +      * [[https://docs.djangoproject.com/en/1.4/intro/tutorial01/|The Django Tutorial]] and try to build a web application with the [[https://www.djangoproject.com/|Django Web Framewor]]. 
 +      * [[http://www.scipy.org/|SciPy]] if you're into science, math, and engineering and also [[http://dexy.it|Dexy]] for when you want to write awesome papers that incorporate SciPy or any code really. 
 +      * [[http://www.pygame.org/news.html|PyGame]] and see if you can make a game with graphics and sound. 
 +      * [[http://pandas.pydata.org/|Pandas]] for doing data manipulation and analysis. 
 +      * [[http://nltk.org/|Natural Language Tool Kit]] for analyzing written text and writing things like spam filters and chat bots. 
 +      * [[http://docs.python-requests.org/en/latest/index.html|Requests]] to learn the client side of HTTP and the web. 
 +      * [[http://simplecv.org/|SimpleCV]] to play with making your computer see things in the real world. 
 +      * [[http://scrapy.org/|ScraPy]] and try scraping some web sites to get information off them. 
 +      * [[https://www.panda3d.org/|Panda3D]] for doing 3D graphic and games. 
 +      * [[http://kivy.org/|Kivy]] for doing user interfaces on desktops and mobile platforms. 
 +      * [[http://scikit-learn.org/stable/|SciKit-Learn]] for machine learning applications. 
 +      * [[http://renpy.org/|Ren'Py]] for doing interactive fiction games, similar to what you've built in this book but with pictures. 
 +  * Notes:<code python> 
 +# ------------------------------------------------------------------------- 
 +# ex1: Print
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
 print "I'd much rather you 'not'." print "I'd much rather you 'not'."
行 16: 行 42:
 python ex1.py python ex1.py
  
-ex2: Common  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex2: Common
 # This is a common # This is a common
 print "common" #This is a common too. print "common" #This is a common too.
  
-ex3: Numbers and Math  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex3: Numbers and Math
 # + - / * % < > <= >= # + - / * % < > <= >=
 # more: ** # more: **
 print "Result is ", 2*2-3/1, "+", 7%6,"=", 2, "is", 2>1, 2**8 print "Result is ", 2*2-3/1, "+", 7%6,"=", 2, "is", 2>1, 2**8
  
-ex4: Variables And Names  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex4: Variables And Names
 cars = 100 cars = 100
 space_in_a_car = 4.0 space_in_a_car = 4.0
  
-ex5: More Variables and Printing  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex5: More Variables and Printing
 my_name = 'lucy' my_name = 'lucy'
 my_age = 16 my_age = 16
行 35: 行 65:
 print "My name is %s, i am %d old." % ( my_name, my_age ) print "My name is %s, i am %d old." % ( my_name, my_age )
  
-ex6: Strings and Text  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex6: Strings and Text
 print "My name is: %r" % "lucy"  # Print "My name is:'lucy'". print "My name is: %r" % "lucy"  # Print "My name is:'lucy'".
 print "My name is: '%s'" % "lucy"  # Print the same. print "My name is: '%s'" % "lucy"  # Print the same.
行 41: 行 72:
 print my_name % 'lucy' # Print the same. print my_name % 'lucy' # Print the same.
  
-ex7: More Printing  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex7: More Printing
 print "a" + "b" + "c" * 5 # Print "abccccc" print "a" + "b" + "c" * 5 # Print "abccccc"
  
-ex8: Printing, Printing  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex8: Printing, Printing
 formatter = "%r %r %r %r" formatter = "%r %r %r %r"
 print formatter % (1, 2, 3, 4) print formatter % (1, 2, 3, 4)
行 51: 行 84:
 print formatter % (formatter, formatter, formatter, formatter) print formatter % (formatter, formatter, formatter, formatter)
  
-ex9: Printing, Printing, Printing  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex9: Printing, Printing, Printing
 # Here's some new strange stuff, remember type it exactly. # Here's some new strange stuff, remember type it exactly.
 days = "Mon Tue Wed Thu Fri Sat Sun" days = "Mon Tue Wed Thu Fri Sat Sun"
行 63: 行 97:
 Even 4 lines if we want, or 5, or 6. Even 4 lines if we want, or 5, or 6.
 """ """
-ex10  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex10
 print "\t \\ \" '\"' " print "\t \\ \" '\"' "
  
-ex11: Asking Questions  ------------------------------------------------------------------------- +# ------------------------------------------------------------------------- 
-print "How old are you?", # We put a "," (comma) at the end of each print line. This is so print doesn't end the line with a newline character and go to the next line.+# ex11: Asking Questions 
 +print "How old are you?", # We put a "," (comma) at the end of each print line. This is  
 +#so print doesn't end the line with a newline character and go to the next line.
 age = raw_input() age = raw_input()
 print "So, you're %r old" % age print "So, you're %r old" % age
  
-ex12: Prompting People  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex12: Prompting People
 age = raw_input("How old are you ?") age = raw_input("How old are you ?")
  
-ex13: Parameters, Unpacking, Variables  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex13: Parameters, Unpacking, Variables
 from sys import argv from sys import argv
 script, first, second, third = argv script, first, second, third = argv
行 82: 行 121:
 print "Your third variable is:", third print "Your third variable is:", third
  
-# ex14: Prompting and Passing  -------------------------------------------------------------------------+# ex14: Prompting and Passing
 # Nothing impresses me. # Nothing impresses me.
  
-ex15: Reading Files  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex15: Reading Files
 print "Type the filename :" print "Type the filename :"
 filename= raw_input("> ") filename= raw_input("> ")
行 91: 行 131:
 print txt_again.read() print txt_again.read()
  
-ex16: Reading and Writing Files  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex16: Reading and Writing Files
 # class file's function: # class file's function:
 # close : like save # close : like save
行 103: 行 144:
 my_file.write('first line \n') my_file.write('first line \n')
  
-# ex17: More files  -------------------------------------------------------------------------+# ex17: More files
 # Nothing impresses me. # Nothing impresses me.
  
-ex18: Names, Variables, Code, Functions  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex18: Names, Variables, Code, Functions
 # create a function by using the word 'def' # create a function by using the word 'def'
 def my_function(*args): def my_function(*args):
行 115: 行 157:
     print "arg1: %r, arg2: %r" % (arg1, arg2)     print "arg1: %r, arg2: %r" % (arg1, arg2)
  
-# ex19: Functions and Variables   -------------------------------------------------------------------------+# ex19: Functions and Variables 
 # ex20: Functions and Files # ex20: Functions and Files
 # ex21: Functions Can Return Something by "return" # ex21: Functions Can Return Something by "return"
行 123: 行 165:
 # Nothing impresses me. # Nothing impresses me.
  
-ex25: Even More Practice  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex25: Even More Practice
 # in ex25.py file: # in ex25.py file:
 def break_words(stuff): def break_words(stuff):
行 134: 行 177:
 help(ex25) # show help info about ex25.py help(ex25) # show help info about ex25.py
 help(ex25.break_words) # show help info about function break_words in module ex25 help(ex25.break_words) # show help info about function break_words in module ex25
-# Typing 'ex25' is annoying. A shortcut is to do your import like this: 'from ex25 import * ' which is like saying, "Import everything from ex25."+# Typing 'ex25' is annoying. A shortcut is to  
 +do your import like this: 'from ex25 import * ' which is like saying, "Import everything from ex25."
 from ex25 import * from ex25 import *
 break_words("Hello world") break_words("Hello world")
  
-# ex26: Congratulations, Take a Test!  -------------------------------------------------------------------------+# ex26: Congratulations, Take a Test!
 # Nothing. # Nothing.
  
-ex27: Memorizing Logic  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex27: Memorizing Logic
 # terms: # terms:
 and, or, not, !=, ==, >=, <=, True, False and, or, not, !=, ==, >=, <=, True, False
行 148: 行 193:
 # Nothing impresses me. # Nothing impresses me.
  
 +# -------------------------------------------------------------------------
 # ex29: What If # ex29: What If
 # ex30: Else and If # ex30: Else and If
-# ex31: Making Decisions  -------------------------------------------------------------------------+# ex31: Making Decisions
 people = 20 people = 20
 cats = 30 cats = 30
行 160: 行 206:
     print "We can't decide."     print "We can't decide."
  
-ex32: Loops and Lists  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex32: Loops and Lists
 the_count = [1, 2, 3, 4, 5] the_count = [1, 2, 3, 4, 5]
 fruits = ['apples', 'oranges', 'pears', 'apricots'] fruits = ['apples', 'oranges', 'pears', 'apricots']
行 183: 行 230:
     print "Element was: %d" % i     print "Element was: %d" % i
  
-ex33: While Loops  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex33: While Loops
 i = 0 i = 0
 numbers = [] numbers = []
行 195: 行 243:
 # Nothing impresses me. # Nothing impresses me.
  
-ex35: Branches and Functions  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex35: Branches and Functions
 from sys import exit from sys import exit
 def gold_room(): def gold_room():
行 215: 行 264:
     exit(0)     exit(0)
  
-# ex36: Designing and Debugging  +# ------------------------------------------------------------------------- 
 +# ex36: Designing and Debugging
 # ex37: Symbol Review # ex37: Symbol Review
-# ex38: Doing Things to Lists  -------------------------------------------------------------------------+# ex38: Doing Things to Lists
 ten_things = "Apples Oranges Crows Telephone Light Sugar" ten_things = "Apples Oranges Crows Telephone Light Sugar"
 print "Wait there are not 10 things in that list. Let's fix that." print "Wait there are not 10 things in that list. Let's fix that."
行 235: 行 285:
 print '#'.join(stuff[3:5]) # super stellar! print '#'.join(stuff[3:5]) # super stellar!
  
-ex39: Dictionaries, Oh Lovely Dictionaries  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex39: Dictionaries, Oh Lovely Dictionaries
 >>> stuff = {'name': 'lucy', 'age': 16} >>> stuff = {'name': 'lucy', 'age': 16}
 >>> print stuff['name'] >>> print stuff['name']
行 249: 行 300:
     print "%r : %r" % (key, value)     print "%r : %r" % (key, value)
  
-ex40: Modules, Classes, and Objects  -------------------------------------------------------------------------+# ------------------------------------------------------------------------- 
 +# ex40: Modules, Classes, and Objects
 # Modules Are Like Dictionaries # Modules Are Like Dictionaries
 # Classes Are Like Modules # Classes Are Like Modules
行 285: 行 337:
 super super
  
 +# -------------------------------------------------------------------------
 # ex43: Basic Object-Oriented Analysis and Design # ex43: Basic Object-Oriented Analysis and Design
-# ex44: Inheritance Versus Composition  -------------------------------------------------------------------------+# ex44: Inheritance Versus Composition
 class Parent(object): class Parent(object):
     def override(self):     def override(self):
行 320: 行 373:
         super(Child, self).__init__()         super(Child, self).__init__()
                  
-# ex45: You Make a Game         +# ex45: You Make a Game   
-        +# Nothing impresses me.    
 + 
 +# ------------------------------------------------------------------------- 
 +# ex46: A Project Skeleton    
 +try: 
 +    from setuptools import setup 
 +except ImportError: 
 +    from distutils.core import setup 
 + 
 +# ------------------------------------------------------------------------- 
 +# ex47: Automated Testing   
 +nosetests  
 +from nose.tools import * 
 +assert_equal 
 +# Test files go in "tests/" and are named "BLAH_tests.py" otherwise "nosetests" won't run them.    
 + 
 + 
 +# ------------------------------------------------------------------------- 
 +# ex48: Advanced User Input    
 +# A tuple is nothing more than a list that you can't modify.  
 +# It's created by putting data inside two "("")" with a comma, like a list: 
 +first_word = ('verb', 'go'
 +# Exceptions and Numbers 
 +def convert_number(s): 
 +    try: 
 +        return int(s) 
 +    except ValueError: 
 +        return None 
 + 
 +# ------------------------------------------------------------------------- 
 +# ex49: Making Sentences 
 +# ex50: Your First Website 
 +# ex51: Getting Input from a Browser 
 +# ex52: The Start Of Your Web Game 
 +# Nothing impresses me. 
 + 
 </code> </code>
  
  
  
  • public/it/python.1417596560.txt.gz
  • 最后更改: 2014/12/03 16:49
  • oakfire