Minimalist Python Introductory Guide _python

Source: Internet
Author: User
Tags abs data structures inheritance

A sledgehammer.

Suppose you want to learn the language of Python, but you can't find a short and 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 tutorial (toturial) and the Quick Search manual (Cheatsheet), so it will only contain some basic concepts. Obviously, if you want to really learn a language well, you still need to practice it yourself. Here, I'll assume that you already have a certain programming base, so I'll skip over most of the non-Python language related content. This article will highlight important keywords so that you can easily see them. It's also important to note that because of the limited length of this tutorial, there's a lot of content that I'll use directly to illustrate a little comment.
The language features of Python

Python is a strong type (that is, variable type is mandatory), dynamic, implicit type (do not need to do variable declaration), case sensitive (Var and var represent different variables) and object-oriented (all objects) and other characteristics of the programming language.


Get help

You can easily get help through the Python interpreter. If you want to know how an object works, all you have to do is call Help (<object>)! There are also useful ways in which dir () displays all the methods of the object, and <object>.__doc__ displays its documents:

>>> 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 are no mandatory statement-terminating characters in Python, and code blocks are indicated by indentation. Indentation represents the beginning of a block of code, and the inverse indent represents the end of a block of code. The declaration ends with a colon (:) character and opens an indentation level. A single-line comment begins with a well sign character (#), and a multiline comment appears as a multiple-line string. An assignment (in fact, binding an object to a name) is implemented by an equal sign ("="), and a double equal sign ("= =") is used for equality judgments, and "+ =" and "=" are used to increase/decrease operations (the value of the value on the right side of the This applies to many data types, including strings. You can also use multiple variables on a single line. For example:

>>> myvar = 3
>>> myvar = 2
>>> myvar
5
>>> MyVar-= 1
>> > MyVar
4
"" "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 ># the old names.
>>> myvar, mystring = mystring, MyVar


Data Type

Python has three basic data structures for lists (list), tuples (tuple), and dictionaries (dictionaries), while collections (sets) are included in the collection library (but are formally python-built types from the Python2.5 version). The characteristics of a list are similar to one-dimensional arrays (you can also create lists of "lists" of multidimensional arrays), a dictionary is an array (usually called a hash table) with an associative relationship, and a tuple is an immutable one-dimensional array (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 index value of the first element in the array (subscript) is 0, and using a negative index value allows the array element to be accessed from the back forward,-1 for the last element. Array elements can also point to functions. Look at 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 are how to change Dictionary values.
>>> mytuple = (1, 2, 3)
>>> myfunction = Len
>>> print myfunction (mylist)
3

You can use the operator to access a paragraph in an array, if: Left blank means start with the first element, and the same: empty on the right indicates the end of the last element. A negative index represents 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]
>>> print Mylist[0:2]
[' List item 1 ', 2]
>>> print mylist[-3:-1]
[' List item 1 ', 2]
>>> print mylist[1:]
[2, 3.14]
# Adding a th IRD parameter, "step" would have Python step
in # N item increments, rather than 1.
# e.g., this'll return the ' the ' the ' the ' the ' the ' the ' then go ' to ' third ' and ' return
' that (so, items 0 and 2 in 0-indexing). 
   >>> print Mylist[::2]
[' List item 1 ', 3.14]


string

The strings in Python are marked with single quotes (') or double quotes ("), and you can also use a different identifier (such as" he said ' Hello ') in a string of one type. " Multiple-line strings can be marked with three consecutive single quotes ("') or double quotes (" "). Python can use Unicode strings using syntax such as U "This is a Unicode string". If you want to fill a string with a variable, you can use the modulo operator (%) and a tuple. The use is to use%s from left to right in the target string to refer to the position of the variable, or to use a dictionary instead, as shown in the following example:

>>>print "Name:%s\ number
:%s\
String:%s"% (Myclass.name, 3, 3 * "-")
Name:poromenos number
: 3
string:---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 '} ' is
a test.


Process Control

You can use if, for, and while in Python to implement process control. There is no select in Python, and use if to implement it instead. Use for to enumerate the elements in the list. If you want to generate a list of numbers, you can use the range (<number>) function. The following are examples of syntax for these declarations:

Rangelist = range
>>> 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.
    Continue
Else:
  # the ' Else ' clause is optional and are
  # executed only if the loop didn ' t ' break '.
  Pass # does nothing
 
if 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

The

function is declared through the "def" keyword. Optional arguments appear in the function declaration as a collection and follow the required arguments, and optional parameters can be assigned a default value in the function declaration. A named parameter needs to be assigned a value. A function can return a tuple, which can be used to effectively return multiple values by using a tuple split. A lambda function is a special function consisting of a single statement, which is passed by reference, but cannot be changed for mutable types such as tuples, integers, strings, and so on. This is because only the memory address of the variable is passed. And only if the old object is discarded, the variable can bind to an object, so the immutable type is replaced instead of changed (note: Although the Parameter form passed by Python is essentially a reference pass, it produces the effect of a value pass). For example,

# function equivalent to Def funcvar (x): return x + 1
funcvar = lambda x:x + 1
>>> print Funcvar (1)
2
 
# An_int and A_string are optional, they have a default value
# If you specify only one argument when you call Passing_example, the An_int defaults to 2, and a_string defaults to a default string. If the preceding two arguments are specified when passing_example is invoked, a_string still defaults to a default string.
# a_list is a prerequisite 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 = ten
>>&G T 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_int
10


class

Python supports a limited number of inheritance forms. Private variables and methods can be declared by adding at least two leading underscores and trailing an underscore (such as "__spam", which is just convention, not Python's mandatory requirements). Of course, we can also give arbitrary names to instances of the class. For example:

Class MyClass (object): Common = Ten def __init__ (self): self.myvariable = 3 def myfunction (self, arg1, arg2): Return Self.myvariable # It is the class instantiation >>> classinstance = MyClass () >>> Classin
Stance.myfunction (1, 2) 3 # This variable are shared by all classes.  >>> Classinstance2 = MyClass () >>> Classinstance.common >>> Classinstance2.common # Note
How do we use the class name # instead of the instance. >>> Myclass.common = >>> Classinstance.common >>> Classinstance2.common # This'll no
T update the variable on the class, # instead it'll bind a new object to the old # variable name. >>> Classinstance.common = ten >>> Classinstance.common classinstance2.common >>> >&
gt;> Myclass.common = # This has not changed, because ' common ' is # now ' instance variable.
>>> Classinstance.common >>> Classinstance2.common# 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 ' class instance, so you can set # instance variables as AB
  Ove, 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-but # we can add one to the Instan Ce anyway.
Note # So this is only being a member of Classinstance.

 >>> classinstance.test = ten >>> classinstance.test 10


Exception

Exceptions in Python are handled by the Try-except [Exceptionname] block, for example:

Def some_function ():
  try:
    # Division by zero raises a exception 10/0 except Zerodivisionerror
  :
    Print "Oops, invalid."
  else:
    # Exception didn ' t occur, we ' re good.
    Pass
  finally:
    #
    The ' is ' executed after the ' code block ' 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.


Import

External libraries can be imported using the import [libname] keyword. At the same time, you can use from [libname] import [funcname] to import the required functions. For example:

Import random
from time import clock
 
randomint = random.randint (1)
>>> print Randomint
64


file I/O

Python has a lot of built-in function libraries to call for file processing. For example, here is a demonstration of how to serialize a file (using the Pickle library to convert a data structure 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 are 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 are a sample string '
myfile.close ()
 
# Open the file for Readin G.
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<a<3 to determine whether a variable a is between 1 and 3.
You can use Del to delete a variable or delete an element from an array.
List comprehension provides a powerful tool for creating and manipulating lists. A list derivation consists of an expression and a For statement that follows the expression, and the For statement can also be followed by 0 or more if or for statements to see the following example:

>>> Lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in Lst1 to Y in Lst2]
[3, 4, 5, 6, 8, 9,]
>>> 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-[3, 3, 4, 4, 3]])
True
# This is because 4% 3 = 1, and 1 are True, so any () 
   
    # returns TRUE.
 
# Check How many the 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 are declared outside of functions and can be read without any special declaration. But if you want to modify the value of a global variable, you must declare it at the beginning of the function with the global keyword, otherwise python will treat the variable as a new local variable (note that it's easy to get caught if you don't notice). For example:

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


Summary

This tutorial does not cover the entire contents of the Python language (not even a small number of them). Python has a lot of libraries and lots of features to learn, so to learn python well you have to do something else outside of this tutorial, such as reading dive into Python. I hope this tutorial will give you a good introductory guide. Please leave a message if you feel that there is something worth improving or adding to this article, or that you would like to know what is in Python.

This tutorial is suitable for a short ebook. The various Python best practices offered by E-books are in a separate ebook, and interested students can go to Https://leanpub.com/learn-python to buy them. You can get updates 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.