A minimalist guide to getting started with Python

Source: Internet
Author: User
Preliminary Sledgehammer

Let's say you want to learn the Python language, but you can't find a short, comprehensive introductory tutorial. Then this tutorial will take you 10 minutes to get you into the Python gate. The content of this article is between the tutorials (toturial) and the Quick Reference Manual (Cheatsheet), so it will only contain some basic concepts. Obviously, if you want to really learn a language, you still need to do it yourself. Here, I'll assume that you have a certain programming foundation, so I'll skip most of the non-Python language content. This article highlights important keywords so that you can easily see them. It is also important to note that due to the limited length of the tutorial, there is a lot of content that I will use directly to illustrate a little comment.
Language features of Python

Python is a programming language with a strong type (that is, variable types are mandatory), dynamic, implicit types (which do not need to be variable-declared), Case-sensitive (Var and var represent different variables), and object-oriented (everything is objects).


Get help

You can easily get help from the Python interpreter. If you want to know how an object works, all you need to do is call Help ()! There are also some useful ways that Dir () shows all the methods of the object, as well asThe. __doc__ will display 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

There is no mandatory statement-terminating character in Python, and the code block is indicated by indentation. Indentation represents the beginning of a block of code, and the inverse indentation represents the end of a block of code. The declaration ends with a colon (:) character, and an indentation level is turned on. A single-line comment begins with a pound sign (#), and multiple lines of comment appear as a multiline string. The assignment (in fact binds the object to the name) is implemented by an equal sign ("="), and the Double equals sign ("= =") is used for equality, and "+ =" and "=" are used to increase/decrease the operation (the value determined by the value to the right of the symbol is increased/decreased). This applies to many data types, including strings. You can also use multiple variables on a single line. For example:

>>> MyVar = 3>>> MyVar + = 2>>> myvar5>>> MyVar-= 1>>> MYVAR4 "" "This is a mul Tiline comment. The following lines concatenate the strings. "" " >>> mystring = "Hello" >>> mystring + + "world." >>> Print Mystringhello world.# This swaps the variables on one line (!). # It doesn ' t violate strong typing because values aren ' t# actually being assigned, but new objects is bound to# the old n Ames.>>> myvar, mystring = mystring, MyVar


Data type

Python has three basic data structures (list), tuple (tuple), and dictionary (dictionaries), and the collection (sets) is included in the collection library (but formally as a python built-in type from the Python2.5 version). The features of a list are similar to a one-dimensional array (you can also create a "list of lists" like multidimensional arrays), a dictionary is an array with associative relationships (often called a hash table), and tuples are immutable one-dimensional arrays ("arrays" in Python can contain any type of element, so you can use mixed elements , such as integers, strings, or nested include lists, dictionaries, or tuples. The first element in the array has an index value (subscript) of 0, and a negative index value enables the array element to be accessed from the back forward, and 1 represents the last element. Array elements can also point to functions. Consider the following usage:

>>> sample = [1, ["Another", "List"], ("A", "tuple")]>>> mylist = ["list item 1", 2, 3.14]>>> m Ylist[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 was how to change dict Ionary values.>>> mytuple = (1, 2, 3) >>> myfunction = len>>> print MyFunction (mylist) 3

You can use the: operator to access a paragraph in an array, if: null on the left means starting with the first element, and the same: null on the right indicates the end of the last element. A negative index indicates the position from the backward forward number (-1 is the last item), for example:

>>> mylist = ["list item 1", 2, 3.14]>>> print mylist[:][' list item 1 ', 2, 3.1400000000000001]>>&G T 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" would have the Python step in# N item increments, rather than 1.# e.g., this would return th  E first item, then go to the third and# return this (so, items 0 and 2 in 0-indexing) .>>> print mylist[::2][' List Item 1 ', 3.14]


String

The string in Python is marked with a single quotation mark (') or double quotation mark ("), and you can also use a different identifier (such as" He said ' Hello ') in one of the indicated strings. A multiline string can be marked with three consecutive single quotes ("') or double quotation marks (" "). Python can use Unicode strings through the syntax of the U "This is a Unicode string". If you want to populate a string with a variable, you can use the modulus operator (%) and a tuple. The usage is to use%s from left to right in the target string to refer to the position of the variable or use a dictionary instead, as in the following example:

>>>print "Name:%s\number:%s\string:%s"% (Myclass.name, 3, 3 * "-") Name:poromenosnumber:3string:---StrStri ng = "" This isa multilinestring. "" # 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

In Python, you can use if, for, and while to implement process control. Python does not have a select, and instead uses the if to implement. 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 are examples of syntax for these declarations:

Rangelist = Range (Ten) >>> print rangelist[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist:  # Check if num BER is one of the # 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 was  # executed only if the loop didn ' t ' break '.  Pass # do nothing if rangelist[1] = = 2:  print "The second item (lists is 0-based) is 2" elif rangelist[1] = = 3:  Print "The second item (lists is 0-based) was 3" Else:  print "Dunno" while rangelist[1] = = 1:  Pass


Function

The function is declared with the "def" keyword. Optional parameters appear in the function declaration as a collection followed by the required parameters, and optional parameters can be assigned a default value in the function declaration. A named parameter needs to be assigned a value. Functions can return a tuple (a tuple can be used to effectively return multiple values). A lambda function is a special function consisting of a single statement that is passed by reference, but cannot be changed for non-mutable types such as tuples, integers, strings, and so on. This is because only the memory address of the variable is passed, and the variable can bind an object only after discarding the old object, so the immutable type is replaced instead of changed (translator Note: Although the form of the parameter that Python passes is essentially a reference pass, it produces the effect of a value pass). For example:

# function equivalent to Def funcvar (x): return x + 1funcvar = lambda x:x + 1>>> print Funcvar (1) 2 # An_int and a_string are optional parameters, they have a default Value # If you specify only one parameter when calling Passing_example, then the an_int default is 2, and a_string defaults to a default string. If you specify the first two parameters when calling Passing_example, A_string still defaults to a default string. # a_list is a required parameter because it does not specify a default value. 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 number of multiple inheritance forms. Private variables and methods can be declared by adding at least two leading underscores and a maximum of one underscore (such as "__spam", which is just a convention, not a mandatory requirement for Python). Of course, we can also give an arbitrary name to an instance of the class. For example:

Class MyClass (object): Common = Ten def __init__ (self): self.myvariable = 3 def myfunction (self, arg1, arg2): Retu RN Self.myvariable # This is the class instantiation>>> classinstance = MyClass () >>> CLASSINSTANCE.MYF Unction (1, 2) 3# this variable are shared by all classes.>>> Classinstance2 = MyClass () >>> classinstance.c Ommon10>>> classinstance2.common10# Note How we use the class name# instead of the instance.>>> MyClass. Common = 30>>> classinstance.common30>>> classinstance2.common30# This won't update the variable on t He class,# instead it would bind a new object to the old# variable name.>>> classinstance.common = 10>>> classinstance.common10>>> classinstance2.common30>>> Myclass.common = 50# This have 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" and 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 can set # instance variables as above, but from inside the CLA  Ss. def __init__ (self, arg1): self.myvariable = 3 print arg1 >>> classinstance = otherclass ("Hello") HELLO>&G T;> classinstance.myfunction (1, 2) 3# This class doesn ' t has a. Test member, but# we can add one to the instance anyway . note# that this is only being a member of classinstance.>>> classinstance.test = 10>>> classinstance.test 10


Abnormal

Exceptions in Python are handled by try-except [Exceptionname] blocks, 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:    # executed after the code block    was run # and all exceptions has 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.


Import

External libraries can be imported using the import [libname] keyword. You can also import the required functions using from [libname] import [funcname]. For example:

Import randomfrom time Import Clock randomint = Random.randint (1) >>> print Randomint64


File I/O

Python's handling of files has many built-in library functions to invoke. For example, here's how to serialize a file (using the Pickle library to convert the data structure to a string):

Import picklemylist = ["This", "was", 4, 13327]# Open the file C:\\binary.dat for writing. The letter R before the# filename string was 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 () # Op En the file for reading.myfile = open (r "C:\\binary.dat") Loadedlist = Pickle.load (myfile) myfile.close () >>> Print loadedlist[' This ', ' is ', 4, 13327]


Other miscellaneous

Numeric judgments can be linked using, for example 1 you can use Del to delete a variable or delete an element in an array.
List comprehension provides a powerful tool for creating and manipulating lists. The list derivation consists of an expression and a For statement immediately following the expression, and the For statement can also be followed by 0 or more if or for statements, as follows:

>>> Lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x ' lst1 for y in Lst2][3, 4, 5, 6, 8, 9, 15]>>> Print [x for x in Lst1 if 4 > x >, 3]# Check If an item has a specific Propert y.# "Any" returns true if any of the item in the list was true.>>> any ([I% 3 for i in [3, 3, 4, 4, 3]]) true# This is Bec Ause 4% 3 = 1, and 1 is true, so any () # returns TRUE. # Check How many items has this property.>>> sum (1 for I in [3, 3, 4, 4, 3] if i = = 4) 2>>> del lst1[0]& gt;>> print lst1[2, 3]>>> del lst1

Global variables are declared outside of a function and can be read without any special declaration, but if you want to modify the value of a global variable, you must declare it with the Global keyword at the beginning of the function, or Python will handle the variable according to the new local variable (note that it is easy to get caught if you are not careful). For example:

  Number = 5     def myfunc ():    # This would print 5.    Print number     def anotherfunc ():    # raises an exception because the variable have not    # been bound before PR Inting. Python knows that it's an    # object would be bound to it later and creates a new, local    # object instead of accessing The global one.    Print number Number    = 3     def yetanotherfunc ():    Global Number    # This would correctly change the global.< C14/>number = 3


Summary

This tutorial does not cover the full contents of the Python language (even a small number of them are not known). Python has a lot of libraries and many features that need to be learned, so to learn python you have to do something else outside this tutorial, such as reading dive into Python. I hope this tutorial will give you a good guide to getting started. If you think there's anything else in this article that you'd like to improve or add, or if you want to know something about Python, please leave a message.

This tutorial is suitable for a short ebook. The following additional python best practices from the ebook are available in a separate e-book, and interested students can purchase them at Https://leanpub.com/learn-python. Updates are available for free after purchase.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.