QuickStart: 10 minutes to learn 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


Read. 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


They. 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 (<object>)! There are also some useful methods, DIR () will show all the methods of the object, and <object>.__doc__ will


Display its documents:


Python



>>> Help (5)

Help on Int object:

(etc etc)

>>> Dir (5)

[' __abs__ ', ' __add__ ', ...]

>>> abs.__doc__

' ABS (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 a multiline comment


Appears 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, and the package


Enclose the string. You can also use multiple variables on a single line. For example:


Python


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

>>> MyVar = 3

>>> MyVar + = 2

>>> MyVar

5

>>> MyVar-= 1

>>> MyVar

4

"" "This is a multiline comment.

The following lines concatenate the strings. "" "

>>> mystring = "Hello"

>>> mystring + = "world."

>>> Print mystring

Hello 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 names.

>>> 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 the list are similar to one-dimensional arrays (and of course you can create


Like a list of multidimensional arrays, a dictionary is an array of associative relationships (often called a hash table), whereas tuples are immutable one-dimensional arrays ("arrays" in Python can contain elements of any type, so you can use mixed elements such as integers, strings, or nested


Set contains a list, dictionary, or tuple). 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:


Python


>>> 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 the 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: 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:


Python



>>> 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" would have the Python step in

# N item increments, rather than 1.

# e.g., this would return the 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 three consecutive single quotes ("') or double quotes (


"") to be marked. 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. Use%s from left to right in the target string


Refer to the position of the variable or use a dictionary instead, as shown in the following example:


Python


1

2

3

4

5

6

7

8

9

10

11

12

13

14

>>>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 percent (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 (<number>) function. The following are the declarations


Examples of syntax:


Python


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.

Continue

Else

# the "Else" clause is optional and is

# executed only if the loop didn ' t "break".

Pass # do nothing

If rangelist[1] = = 2:

Print "The second item (lists was 0-based) is 2"

Elif rangelist[1] = = 3:

Print "The second item (lists was 0-based) is 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. function can return a tuple (using a tuple to split a package can 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 when the old object is discarded, the variable


To bind an object, the immutable type is replaced rather than 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:


Python


# 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 parameters, they have default values

# If you specify only one parameter when calling Passing_example, then an_int defaults to 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_int

10


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 arbitrary names to instances of classes


。 For example:


Python



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 are shared by all classes.

>>> Classinstance2 = MyClass ()

>>> Classinstance.common

10

>>> Classinstance2.common

10

# Note How we use the class name

# instead of the instance.

>>> Myclass.common = 30

>>> Classinstance.common

30

>>> Classinstance2.common

30

# This won't update the variable on the class,

# instead it'll bind a new object to the old

# variable name.

>>> Classinstance.common = 10

>>> Classinstance.common

10

>>> Classinstance2.common

30

>>> Myclass.common = 50

# changed, because "common" is

# now an instance variable.

>>> Classinstance.common

10

>>> Classinstance2.common

50

# 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 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 has a. Test member, but

# we can add one to the instance anyway. Note

# That's this would only be a member of Classinstance.

>>> Classinstance.test = 10

>>> Classinstance.test

10


Abnormal


Exceptions in Python are handled by try-except [Exceptionname] blocks, for example:


Python



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 is run

# and all exceptions has been handled, even

# If a new exception is raised while handling.

Print "We" re-do 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:


Python



Import Random

From time import clock

Randomint = Random.randint (1, 100)

>>> Print Randomint

64


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):


Python



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]


Other miscellaneous


Numeric judgments can be linked, for example 1<a<3 can determine whether a variable a is between 1 and 3.

You can use Del to delete a variable or to 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:



Python



>>> Lst1 = [1, 2, 3]

>>> Lst2 = [3, 4, 5]

>>> Print [x * y for x in Lst1-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 have a specific property.

# "Any" returns true if any item in the list is true.

>>> any ([I percent 3 for I in [3, 3, 4, 4, 3]])

True

# This is because 4% 3 = 1, and 1 are 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]

>>> 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 treat the variable according to the new local variable (note that if you do not notice


Easy to get into a pit). For example:

Python



Number = 5

Def myfunc ():

# This would print 5.

Print number

Def anotherfunc ():

# This raises an exception because the variable have not

# been bound before printing. Python knows that it 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'll correctly change the global.

Number = 3


This article is from the "Python Change the World" blog, so be sure to keep this source http://python88.blog.51cto.com/12933681/1931340

QuickStart: 10 minutes to learn Python

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.