Reading notes for a concise Python tutorial

Source: Internet
Author: User
Tags function definition natural string uppercase letter

Python programming is a pleasant thing to do!!!

First, the characteristics of Python:

It focuses on how to solve the problem rather than the syntax and structure of the programming language.

When you write a program in the Python language, you don't have to think about how to manage the memory that your program uses.

The bottom-level details.

Portability

Supports object-oriented and process-oriented programming

Embeddable: You can embed C or C + + in Python code

A rich library

Second, the Python code execution process:

Source code .py-> byte code. PYC-byte code executed in PVM (Python virtual machine)

Second, the Python IDE:

http://www.pydev.org/

Third, the basic concept of Python:

    • Explanatory language: The source code is not translated directly into the machine language, but translated into intermediate code, and then interpreted by the interpreter to run the intermediate code.

    • Compiled language: Before execution requires a specialized compilation process, the program is compiled into machine language files, the runtime does not need to re-translate, directly using the results of the compilation.

    • Number: There are 4 types of numbers in Python: integers, long integers, floating-point numbers, complex numbers

    • String: Typically single, double, and triple quotes

    • Back slash

    • Natural string: A natural string is specified by prefixing the string with R or R. For example R "Newlines is indicated

by \ n ".

    • Unicode string:-You only need to prefix the string with u or U,

Remember to use Unicode strings when you are working with text files, especially if you know that this file contains useful

Text written in a non-English language.

    • If you put two strings next to each other literally, they will be automatically connected by Python. For example, ' what\ '

' Your name? ' will be automatically converted to "What's your name?".

    • There is no dedicated char data type in Python.

    • Remember, single and double quote strings are exactly the same.

    • Be sure to use a natural string to process the regular expression. Otherwise, you will need to use a lot of back slashes. For example, a forward reference can

Written as ' \\1 ' or R ' \1 '.

What is the back reference backreference:\n slash plus number indicates the contents of the preceding parenthesis. For example: \b (\d+) \b\s+\1\b this will match such as: 123 123 Repeating number string

Metacharacters

Name

Matching objects

.

Point number (dot)

Single arbitrary character

\ n

Line Break (newline)

Line break

\ r

Enter (return)

Enter

\ t

tab (TAB)

Tabs

[...]

Character group (Character Class)

Any of the listed characters

[^...]

Excluded character groups (negated Character Class)

Any characters that are not listed

\d

Number (digit)

Digital

\d

Non-digital

\w

Word (Word)

Word characters (letters or numbers)

\w

Non-word characters

\s

White space character (whitespace)

White space characters

\s

Non-whitespace characters

^

De-char (caret)

Start position of line

$

Dollar symbol (DOLLAR)

End position of the line

\<

Start position of the word

\>

The end position of the word

\b

Boundary (boundary)

Word boundaries

\b

Non-word boundary

(?=...)

Affirmative-order surround (Positive Lookahead)

Success if the right can match

(?! ...)

Negative order surround (negative Lookahead)

Success if the right can't match

(? <= ...)

Affirmative reverse look (Positive lookbehind)

Success if the left can match

(?<!...)

Negative reverse look (negative lookbehind)

Success if the left does not match

?

The previous character may not appear, or it can appear only once

+

The characters before it can appear countless times, but at least once

*

The characters before it can appear countless times, or they may not appear

N

Its previous characters match exactly n times

{N,}

Its previous characters can appear countless times, but at least n times

{N,m}

The character before it must appear at least n times, at most times m

(...)

Parentheses (Parenthese)

Grouping sub-expressions and recording the contents of the words it contains to match the expression

(?:...)

Grouping sub-expressions

\1-\9

Back to reference

|

Vertical bar (BAR)

Match any expression on either side of the split

    • Variables: Variables are just a portion of your computer's memory that stores information. You only need to assign a value to a variable when you use it. You do not need to declare or define a data type.

    • Designator Command rules:

The first character must be a letter in the alphabet (uppercase or lowercase) or an underscore;

Other parts can be set by letter (uppercase or lowercase), underscore (' _ '), or number (0-9)

Into

Case sensitive;

    • Data type: Variables can handle different types of values, called data types.

    • Object:

    • The semicolon represents the end of a logical line/statement, as follows:

To use more than one logical line in a physical line, you need to use a semicolon (;) to specifically indicate this

The use of.

i = 5

Print I

can be written

i = 5;

Print I;

can also be written

i = 5; Print I;

    • Indentation: Indentation determines the grouping of statements. Do not use tabs and spaces to indent, as this does not work when crossing different platforms. It is strongly recommended that you use a single tab at each indentation level.

    • Object:

    • Class:

    • Methods: Classes also have methods that define only the ground function for a class. You can use these features only when you have an object of that class. For example, Python provides the Append method for the list class, which lets you add an item at the end of the list. A class also has a field, which is a variable that is defined only for a class.

Iv. python format Note:

Python is case-sensitive

The beginning of each line match either no spaces or tabs

V. Reasonable use of help information:

Help (STR)-This will show the Str class

Help

Help you need to use often

VI. Python Control Flow:

If/while/for/break/continue

#!/usr/bin/python

A=12

B=int (raw_input ("pls input a int:"))

If B==a:

Print "Congratudations"

Elif B<a:

Print "Your guess lower than it"

Else

print "Done"

#!/usr/bin/python

A=20

Flag=true

#这个地方需要注意首字母大写

While flag:

Guess=int (raw_input ("pls input a int:"))

If Guess==a:

Print "Good"

Flag=false

Elif Guess<a:

Print "should bigger"

Else

Print "Should lower"

print "Done"

#!/usr/bin/python

# Filename:for.py

For I in range (1, 5):

Print I

Else

print ' The For loop was over '

The Else section is optional. If an else is included, it is always executed once after the For loop ends.

#!/usr/bin/python

b= "ABC"

While True:

A=raw_input ("pls input:")

If a==b:

Break

Else

Print "The length is", Len (a)

print "Done"

Vii. Python module:

    • Module definition: A module is basically a file that contains all of the functions and variables that you define.

Standard library module: SYS module

#!/usr/bin/python

# Filename:using_sys.py

Import Sys

print ' The command line arguments is: '

For I in SYS.ARGV:

Print I

print ' \n\nthe PYTHONPATH is ', Sys.path, ' \ n '

    • Bytes compiled files: These files are in. pyc as the extension

    • From import statement:

    • __name__ of the module:

If we only want to run the main block when the program itself is being used, it does not run the main block when it is entered by another module. Each Python module has its __name__, if it is ' __main__ ', which means that the module is run by the user alone.

    • To create your own module:

Remember that this module should be placed in the same directory as the program we entered it, or in the directory listed in Sys.path

One.

#!/usr/bin/env python

Def say ():

If __name__== ' __main__ ':

print ' This program was being run by itself '

Else

print ' This module is being imported from another module '

Version= ' 0.1 '

#!/usr/lib/env python

Import Name #调用name模块

Name.say ()

print ' Version ', name.version

    • Use from. Import

#!/usr/bin/python

# Filename:mymodule_demo2.py

From MyModule import say, version

# Alternative:

Say ()

print ' Version ', version

    • Dir () function:

You can use the built-in Dir function to list the identifier for a module definition. Identifiers have functions, classes, and variables.

For example, the module name.py defined above:

>>> Import Name

>>> Dir (name)

[' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' say ', ' version ']

Note that if the DIR () parameter is empty:

>>> Import Name

>>> Dir (name)

[' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' say ', ' version ']

>>> dir ()

[' __builtins__ ', ' __doc__ ', ' __name__ ', ' __package__ ', ' name ']

#这里import模块名称是列表的一部分

Eight, the Python standard library:

A set of modules consists of a standard library.

IX. Python exception

X. Data structure of Python

Three built-in data structures: arrays, dictionaries, tuples

    • List: Separate each item with a comma. Items in the list should be included in square brackets [].

The list is a mutable data type.

Example: Manually adding item to the list and deleting it:

#!/usr/bin/env python

def buy ():

mylist=[' potato ', ' chilli ', ' banana ', ' apple ']

print ' I has ', Len (mylist), ' to buy\n '

print ' The items are: '

For I in MyList:

Print I,

Flag=true

While flag:

Judge=raw_input (' You can input yes or no: ')

If judge== ' yes ':

Goods=raw_input (' Maybe you need-buy more goods: ')

Mylist.append (Goods)

Else

Flag=false

For I in MyList:

Print I,

print ' My shop list was now: ', mylist

Mylist.sort ()

print ' The sorted shop list is ', mylist

Flag2=true

While Flag2:

Judge2=raw_input (' If you want to delte?yes or no: ')

If judge2== ' yes ':

print ' which itme want to Delte ', mylist

print ' can choose the item from 0 to ', Len (mylist)-1

A=int (Raw_input (' The item is: '))

Del Mylist[a]

Else

Flag2=false

print ' The remained shop list is: ', mylist

Buy ()

A comma is used at the end of the print statement to eliminate the line break that is automatically printed for each print statement.

    • Meta-group:

Tuples and strings are immutable, i.e. you cannot modify tuples. Tuples are defined by a comma-separated list of items in parentheses.

An empty tuple consists of a pair of empty parentheses, such as Myempty = ().

You must follow the first (only) item followed by a comma so that python can differentiate between tuples and a Parenthesized object in an expression.

The most common use of tuples is in print statements.

Examples of using tuples:

!/usr/lib/env python

Def zoo ():

zoo= (' Lion ', ' tiger ', ' Rabbit ', ' dragon ', ' Snake ')

print ' The number of the zoo is ', Len (Zoo)

For I in range (len):

Print Zoo[i],

zoo_new= (' dog ', ' monkey ', zoo)

print ' The animal number is ', Len (zoo_new)

print ' The Sencond animal is ', zoo_new[1]

print ' The animals brought from old Zoo is: ', zoo_new[2]

print ' All animals: ', zoo_new

A= (123)

Print a

A= (123,)

Print a

Zoo ()

Input Result:

The number of the zoo is 5

Lion Tiger Rabbit Dragon Snake The animal number is 3

The Sencond animal is monkey

The animals brought from old Zoo is: (' lion ', ' tiger ', ' Rabbit ', ' dragon ', ' Snake ')

All animals: (' dog ', ' monkey ', (' Lion ', ' tiger ', ' Rabbit ', ' dragon ', ' Snake ')

123

(123,)

Example 2:

Tuples are used for printing:

#!/usr/bin/python

# Filename:print_tuple.py

Age = 22

name = ' Swaroop '

Print '%s is%d years old '% (name, age)

Print ' Why are%s playing with that python? '% name

    • Dictionary:

The dictionary is similar to the Address book where you find the address and contact details by contact name, i.e. we associate the key (name and value (details) together. Note that the key must be unique.

Xi. python functions

    • function definition: A function is a program block that can be reused.

    • Call Function: Use this name anywhere in your program to run this block of statements any number of times.

Example:

#!/usr/bin/python

# Filename:function1.py

Def SayHello ():

print ' Hello world! ' # block belonging to the function

SayHello () # Call the function

    • Formal parameters and arguments for a function:

Parameters are specified internally within the parentheses of the function definition, separated by commas.

    • Local variables: Declare variables within function definitions.

    • Use the global statement: You can specify multiple global variables using the same global statement. For example, Global x, Y, Z.

#!/usr/bin/python

# Filename:func_global.py

def func ():

Global X

print ' x is ', X

x = 2

print ' Changed local x to ', X

x = 50

Func ()

print ' Value of x is ', X

    • Default parameters: Assign the assignment operator (=) and the default value after the parameter name of the function definition to specify the default parameter values for the parameters. Only those arguments at the end of the formal parameter list can have default parameter values.

#!/usr/bin/python

# Filename:func_default.py

DEF say (message, times = 1):

Print message * times

Say (' Hello ')

Say (' World ', 5)

    • Key parameters: Assign values to these parameters by naming them.

    • Return statement:

#!/usr/bin/python

# Filename:func_return.py

def maximum (x, y):

If x > Y:

return x

Else

Return y

Print Maximum (2, 3)

    • Docstrings Document string: Docstrings is an important tool because it helps to make your program documentation easier to understand.

#!/usr/bin/python

# Filename:func_doc.py

def printmax (x, y):

"' Prints the maximum of the numbers.

The values must be integers. "

x = Int (x) # Convert to integers, if possible

y = Int (y)

If x > Y:

Print x, ' is maximum '

Else

Print Y, ' is maximum '

Printmax (3, 5)

Print printmax.__doc__

The string of the first logical line of the function is the document string for this function

The Convention for a document string is a multiline string whose first line begins with an uppercase letter and ends with a period. The second line is a blank line,

Starting with the third line is a detailed description.

。 Keep in mind that Python takes everything as an object, including this function. This sentence is very important, through the above example from the following line of code can be withdrawal.

12. Python variables

13. Python Operators and expressions:

650) this.width=650; "title=" clip_image001 "style=" border-top:0px;border-right:0px;background-image:none; border-bottom:0px;padding-top:0px;padding-left:0px;border-left:0px;padding-right:0px, "alt=" clip_image001 "src=" Http://s3.51cto.com/wyfs02/M00/8A/9D/wKiom1g1NtyxxI_hAAFcZOAj09I254.png "border=" 0 "height=" "/>

The plus sign can do arithmetic operations, or you can concatenate 2 strings.

* * Power

650) this.width=650; "title=" clip_image002 "style=" border-top:0px;border-right:0px;background-image:none; border-bottom:0px;padding-top:0px;padding-left:0px;border-left:0px;padding-right:0px, "alt=" clip_image002 "src=" Http://s3.51cto.com/wyfs02/M01/8A/9D/wKiom1g1Nt6i3URTAAHE1UhFxlg510.png "border=" 0 "height=" 317 "/>

650) this.width=650; "title=" clip_image003 "style=" border-top:0px;border-right:0px;background-image:none; border-bottom:0px;padding-top:0px;padding-left:0px;border-left:0px;padding-right:0px, "alt=" clip_image003 "src=" Http://s3.51cto.com/wyfs02/M01/8A/99/wKioL1g1Nt_igqifAAGm2J3EvAw220.png "border=" 0 "height=" 289 "/>

    • Operator Precedence:

I recommend that you use parentheses to group operators and operands so that you can clearly indicate the order of operations.

650) this.width=650; "title=" clip_image004 "style=" border-top:0px;border-right:0px;background-image:none; border-bottom:0px;padding-top:0px;padding-left:0px;border-left:0px;padding-right:0px, "alt=" clip_image004 "src=" Http://s3.51cto.com/wyfs02/M02/8A/9D/wKiom1g1NuDCd2keAACsAvF37CM869.png "border=" 0 "height=" 373 "/>

650) this.width=650; "title=" clip_image005 "style=" border-top:0px;border-right:0px;background-image:none; border-bottom:0px;padding-top:0px;padding-left:0px;border-left:0px;padding-right:0px, "alt=" clip_image005 "src=" Http://s3.51cto.com/wyfs02/M02/8A/99/wKioL1g1NuGAsBc2AAEIyLt-5z8373.png "border=" 0 "height=" 430 "/>

This article is from the "Victor's Struggle" blog, please be sure to keep this source http://victor2016.blog.51cto.com/6768693/1875786

Reading notes for a concise Python tutorial

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.