Life is short I use python python how quick start?

This article will teach you how to quick start python, a brief but comprehensive introductory tutorial walks you through the door Python, with some reference value, small partners who are interested can refer to
assume you want to learn the language Python, but could not find a brief but comprehensive introductory tutorial. Then this tutorial will take ten minutes to take you into the door Python. Between the content of this article is between tutorial (Toturial) and Quick Reference Guide (CheatSheet), and therefore only contains some basic concepts. Obviously, if you want to really learn a language, you still need hands-on practice. Here, I'll assume that you already have some programming basics, so I'll skip most of the non-relevant content Python language. This article will highlight the important keywords so that you can easily see them. Also note that, due to the limited space of this tutorial, I will have a lot of content for direct use code Minga with little comment.

Python language features

Python is a strong type (i.e., variable type is mandatory), dynamic, implicit type (do not need to declare variables), case sensitive (var and VAR represent different variables) and object-oriented (all are object) and other characteristics of the programming language.

Getting Help

You can easily get help through the Python interpreter. If you want to know how an object (object) is working, then you need to do is call help ()! All methods There are also some useful methods, dir () will display the object, there .__ doc__ displays its documentation:

>>> help(5)
Help on int object:
(etc etc)>>> dir(5)
['__abs__', '__add__', ...]>>> abs.__doc__'abs(number) -> number
 
Return the absolute value of the argument.'

grammar

Python is not mandatory statement termination character, and the code blocks are indicated by the indentation. Indent indicates the start of a block, inverse indentation indicates the end of a code block. Statement colon (:) character ends and the open indentation level. Single-line comments (#) beginning with the hash character, multi-line comment multi-line places a string appears. Assignment (in fact bind to the name of the object) is achieved by an equal sign ( "="), double equal sign ( "=") is determined for the equal "= +" and "- =" is used to increase / decrease calculating (determined by the value of the right sign to increase the value of the reduction /). This applies to many types of data, including strings. You can also use multiple variables on one line. E.g:

>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4"""This is a multiline comment.
The following lines concatenate the two strings.""">>> mystring = "Hello">>> mystring += " world.">>> print mystring
Hello world.# This swaps the variables in one line(!).# It doesn't violate strong typing because values aren't# actually being assigned, but new objects are bound to# the old names.>>> myvar, mystring = mystring, myvar

type of data

Python has a list (list), tuple (tuple) and dictionary (dictionaries) three basic data structures and collections (sets) are included in the collection of the library (but Python2.5 version officially become the Python built-in types) . Features list with a similar one-dimensional array (of course, you can also create multidimensional arrays of similar "list of lists"), the dictionary is an array with affiliated (often called a hash table), and tuples are immutable one-dimensional array (Python the "array" may comprise any type of element, so you can use mixing elements such as integer, string or contains nested lists, dictionaries or tuples). The first element of the array index (subscript) is 0, the index values ​​can use a negative access array elements from back to front, -1 is the last element. Array element can point to function. Consider the following usage:

>>> sample = [1, ["another", "list"], ("a", "tuple")]>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.>>> mytuple = (1, 2, 3)>>> myfunction = len>>> print myfunction(mylist)3

You can use the: operator to access an array of a certain period, if: on the left is empty it means starting from the first element, empathy: the right is empty it means to the end of the last element. A negative index indicates the number of forward from a position (-1 is the last item), for example:

>>> mylist = ["List item 1", 2, 3.14]>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]>>> print mylist[0:2]
['List item 1', 2]>>> print mylist[-3:-1]
['List item 1', 2]>>> print mylist[1:]
[2, 3.14]# Adding a third parameter, "step" will have Python step in# N item increments, rather than 1.# E.g., this will return the first item, then go to the third and# return that (so, items 0 and 2 in 0-indexing).>>> print mylist[::2]
['List item 1', 3.14]

String

Python strings single quotation marks ( ') or double quotes ( ") to be marked, and you can also use another identifier (e.g., character string designated by a certain kind of" He said' hello ' . "), while the multi-line character string by three successive single quotation marks ( '') or double quotes (" ' "to mark .Python) by u" using the syntax Unicode this is a unicode string " string. If you want to be filled by a string variable, you can use the modulo operator (%) and a tuple.% s use is to use the target string from left to right to refer to the position of generation of variable, or instead of using a dictionary, for example:

>>>print "Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3String: ---
 
strString = """This is
a multiline
string."""# WARNING: Watch out for the trailing s in "%(key)s".>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.

Process Control

Python may be used if, for, and while flow control is achieved. Python and did not select, if used instead to achieve. Use for to enumerate the elements in the list. If you want to generate a list of numbers, you can use the range () function. The following is an example of the syntax of these statements:

rangelist = range(10)>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist: # Check if number is one of
 # the numbers in the tuple.
 if number in (3, 4, 7, 9):  # "Break" terminates a for without
  # executing the "else" clause.
  break
 else:  # "Continue" starts the next iteration
  # of the loop. It's rather useless here,
  # as it's the last statement of the loop.
  continueelse: # The "else" clause is optional and is
 # executed only if the loop didn't "break".
 pass # Do nothingif rangelist[1] == 2: print "The second item (lists are 0-based) is 2"elif rangelist[1] == 3: print "The second item (lists are 0-based) is 3"else: print "Dunno"while rangelist[1] == 1: pass

function

Function declared with "def" keyword. Optional parameters appear in the manner set of function declaration and is followed by a mandatory parameter, optional parameters can be assigned a default value in a function declaration. Named parameters required assignment. Function returns a tuple (a tuple unpacking can effectively return multiple values). Lambda is a special function by a function of the composition of a single statement, the parameters passed by reference, but for immutable type (e.g. a tuple, integer, string, etc.) will not be changed. This is because only pass the memory address of the variable, and only after discarding old objects, variables can bind an object, so immutable type is to be replaced rather than changing (Translator's Note: Although Python transfer parameters in the form of nature on passed by reference, but has an effect of transmitting values). E.g:

# 作用等同于 def funcvar(x): return x + 1funcvar = lambda x: x + 1>>> print funcvar(1)2# an_int 和 a_string 是可选参数,它们有默认值# 如果调用 passing_example 时只指定一个参数,那么 an_int 缺省为 2 ,a_string 缺省为 A default string。如果调用 passing_example 时指定了前面两个参数,a_string 仍缺省为 A default string。# a_list 是必备参数,因为它没有指定缺省值。def passing_example(a_list, an_int=2, a_string="A default string"):
 a_list.append("A new item")
 an_int = 4
 return a_list, an_int, a_string>>> my_list = [1, 2, 3]>>> my_int = 10>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")>>> my_list
[1, 2, 3, 'A new item']>>> my_int10

class

Python supports a limited form of multiple inheritance. Private variables and methods can be two leading underscores and at most one trailing underscore in the form of a statement by adding at least (such as "__spam", this is only the rule rather than the mandatory Python). Of course, we can take any given instance of the class name. E.g:

class MyClass(object):
 common = 10
 def __init__(self):
  self.myvariable = 3
 def myfunction(self, arg1, arg2):
  return self.myvariable # This is the class instantiation>>> classinstance = MyClass()>>> classinstance.myfunction(1, 2)3# This variable is shared by all classes.>>> classinstance2 = MyClass()>>> classinstance.common10>>> classinstance2.common10# Note how we use the class name# instead of the instance.>>> MyClass.common = 30>>> classinstance.common30>>> classinstance2.common30# This will not update the variable on the class,# instead it will bind a new object to the old# variable name.>>> classinstance.common = 10>>> classinstance.common10>>> classinstance2.common30>>> MyClass.common = 50# This has not changed, because "common" is# now an instance variable.>>> classinstance.common10>>> classinstance2.common50# This class inherits from MyClass. The example# class above inherits from "object", which makes# it what's called a "new-style class".# Multiple inheritance is declared as:# class OtherClass(MyClass1, MyClass2, MyClassN)class OtherClass(MyClass):
 # The "self" argument is passed automatically
 # and refers to the class instance, so you can set
 # instance variables as above, but from inside the class.
 def __init__(self, arg1):
  self.myvariable = 3
  print arg1>>> classinstance = OtherClass("hello")
hello>>> classinstance.myfunction(1, 2)3# This class doesn't have a .test member, but# we can add one to the instance anyway. Note# that this will only be a member of classinstance.>>> classinstance.test = 10>>> classinstance.test10

abnormal

Python abnormality by the try-except [exceptionname] processing block, for example:

def some_function():
 try:  # Division by zero raises an exception
  10 / 0
 except ZeroDivisionError:  print "Oops, invalid."
 else:  # Exception didn't occur, we're good.
  pass
 finally:  # This is executed after the code block is run
  # and all exceptions have been handled, even
  # if a new exception is raised while handling.
  print "We're done with that.">>> some_function()
Oops, invalid.
We're done with that.

Importing

External libraries can use the import [libname] keyword import. At the same time, you can import [funcname] be introduced with the required function from [libname]. E.g:

import randomfrom time import clock
randomint = random.randint(1, 100)>>> print randomint64

File I / O

Python for the processing of documents have a lot of built-in libraries can be called. For example, this document shows how the sequence of (using the pickle library to convert the data structures to a string):

import pickle
mylist = ["This", "is", 4, 13327]# Open the file C:\\binary.dat for writing. The letter r before the# filename string is used to prevent backslash escaping.myfile = open(r"C:\\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
 
myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
 
myfile = open(r"C:\\text.txt")>>> print myfile.read()'This is a sample string'myfile.close()# Open the file for reading.myfile = open(r"C:\\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()>>> print loadedlist
['This', 'is', 4, 13327]

Miscellaneous

Numerical determination can be linked, for example, 1 <a <3 it can be determined whether a variable between 1 and 3.
You can use del to delete variables or delete elements in the array.
List comprehensions (List Comprehension) provides a powerful tool to create and manipulate lists. Deriving a list of the formula followed by expression and the expression for syntactically, for statement can be followed by zero or more, or if for statement, look at the following example:

>>> lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]# Check if an item has a specific property.# "any" returns true if any item in the list is true.>>> any([i % 3 for i in [3, 3, 4, 4, 3]])True# This is because 4 % 3 = 1, and 1 is true, so any()# returns True.# Check how many items have this property.>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)2>>> del lst1[0]>>> print lst1
[2, 3]>>> del lst1

Global variables outside the function declaration and may not require any special statement that can be read, but if you want to modify the values ​​of global variables must be declared with the global keyword at the beginning of the function, otherwise Python will this variable according to the new local variable processing (Note that if you do not pay attention could easily be pit). E.g:

number = 5def myfunc():
 # This will print 5.
 print numberdef anotherfunc():
 # This raises an exception because the variable has not
 # been bound before printing. Python knows that it an
 # object will be bound to it later and creates a new, local
 # object instead of accessing the global one.
 print number
 number = 3def yetanotherfunc():
 global number # This will correctly change the global.
 number = 3

Thank you very much to read
in college chose the self-python, found that eating a working computer basic bad loss, education is not no way to do this, can only be acquired to make up, then opened his own counter-attack outside the coding road, constantly learning python core knowledge, in-depth knowledge of basic computer learning, organized, I put our learning Python buckle qun: 774711191, if you are unwilling to mediocrity, it is with me outside of coding, constantly grow it!

In fact, there is not only technical, more technical stuff than those, for example, how to make a fine programmer, rather than "Cock wire", the programmer itself is a noble presence, ah, is not it? [Click to join] want you want to be a noble person, come on!
@ This article comes from public number: csdn2299, like the number of programmers can focus on public institutions

Published 56 original articles · won praise 19 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun02/article/details/105280898