Python Concise Tutorial Notes

Source: Internet
Author: User

1,python Features

Python focuses on how to solve problems, rather than simple, efficient and extensible syntax and structure

2, install Python

PYTHON-V detects if installing pythonctrl+d quits Python prompt python is case-sensitive
Any number behind the # is a comment.
Special forms of Annotation #! , called an organization row, which is intended to tell the system which interpreter to run when executing a program
Comments in the first line cannot be in Chinese
The interpreter runs Python
Exit: Linux Ctrl + D window CTRL + Z and enter enter

Assistance: Help (STR), in Linux, set the PYTHONDOCS environment variable through env, you can use the Assist command

3, Basic concept

String, constant, variable
4 Types of numbers: integers, long integers, floating-point numbers, and complex numbers
Single quotes display strings, all spaces, tabs are displayed
Triple quotes display multiple lines of string, with the freedom to use single and double quotation marks in three quotation marks
Single quotes, double quotes, three quotation marks
In a string, the end of a single backslash \ Indicates that the string continues on the next line
Natural string R "" or r ", indicating certain strings that do not require special handling such as escape characters
Python allows Unicode text to be processed, just precede the string with U "Chinese"
The string is immutable
Automatically connect literally, for example ' This is a ' good? ' will connect as a sentence
Python does not have a char data type, and single and double quotes mean the same thing,
You can use natural strings to handle regular expressions, so you don't need a lot of backslashes


4, Basic concept
Variables can store anything, and variables are part of the memory that stores information in your computer
The python variable identifier consists of an alphanumeric underscore, and the first letter must be an underscore or a letter
Variables can handle different types of values, called data types
Python identifiers are case-sensitive

Python is completely object-oriented and can be an object for numbers, strings, and functions, and Python refers to everything that is used in the program as objects
When you use variables, you only need to assign values, and you don't need to declare variables or data types

Logical lines and physical lines ===== physical lines are what you see when you write your program, the logical line is a single statement that Python sees

The default Python expects only one statement per line
It is strongly recommended that each physical line have only one logical line
If you want to display multiple logical lines in a physical line, you can use semicolons; , a semicolon indicates the end of a logical line
If the logical line is too long, you can use a clear row connection using a backslash \
Python program with a. py extension
Running in the interpreter: Python program.py

The whitespace of the first line in Python is the most important to determine the level of indentation in the logical layer, thus determining the grouping of statements
Statements of the same level must have the same indentation, and each set of such statements is called a block
When you are able to use the new block, in detail in the control flow
Choose an indent style to use, and then use it consistently

5, operators and operands
operator + 、-、, an expression can be decomposed into operators and operands
Http://www.kuqin.com/abyteofpython_cn/ch05s02.html

The assignment operator is a right-to-left operation

Control flow
Three control flow statements in Python if, for, and While,python do not have a switch statement
Raw_input the built-in function, submits a string, waits for user input, and gives hints
If elif Else

While
The while statement has an optional ELSE clause
Python strictly focuses on indentation and capitalization, even if the first letter of true and false must be size, otherwise it is wrong
Range generates the first number of sequences before the second number, and the third parameter is the step size
For I in range (1,5) equals for i in [1,2,3,4]

For i in [sequence]
For In loop statement, using each item in the queue individually

Len function, gets the length of the string len (str)
Break Terminate Loop
If terminated in the loop, the else block will not execute
Continue jumps out of the current loop and continues the next loop, which is used in the loop
int converts a string to an integer, in fact an int is a class

6, Function
Def SayHello (): Defining functions
def keyword defines a function,
The variables defined inside the function are local,
There is a default parameter value that must be declared after no default parameter value, otherwise it is not valid, that is, first declare no default value parameters, and then declare the parameter with the default value
Global variables are declared globally, and multiple global variables can be declared at the same time
If a function has many parameters, you can add an argument by naming it as a function, that is, the specified value passes the parameter

Return with no value returned, equivalent to return none
Pass represents an empty block of statements in Python

Docstrings Document String
"Convention for document Strings" is a multiline string whose first line begins with an uppercase letter, the second line is a blank line, and the end of the detailed description period starts at the third line.
Print func.__doc__ Printed document string
The second line is a blank line, and starting from the third line is a description
Suggest that you write the function to write the document string

7, module
A module is a file that contains functions and variables that you define, and in order to reuse modules in other programs, the file name of the module must be in the. py extension
Learn to use the standard library module
Byte-compiled. pyc file to make the input module a bit faster

Import module name, tell Python that we are going to use this module
SYS.ARGV contains a list of command-line arguments, the first parameter of the list is always the name of the script
From.. Import
Use the argv variable directly into your program, from sys import argv
Avoid using from. Import, and use the import statement because it makes your program easier to read

__name__ of the module
Let's say we just want to execute while the program itself is running, and not run when it is entered by another module.
Each Python module has a __name__, if it is ' __main__ ', it means that the module is run separately

Make your own modules----Each Python program is also a module

The built-in Dir function
Use the built-in Dir function to list module-defined identifiers with functions, classes, and variables
Dir () provides a module name that returns a list of names defined in the current module when the module name is supplied, when the name list of the module definition is not supplied.
Del Delete a variable

8, data structure
Data structure refers to the process can be processed by the information and structure
Python has three types of built-in data structures: lists, tuples, dictionaries

Lists--data structures for working with a set of ordered items
list = [' Apple ', ' banner ']
The Append method adds an item to the end of the list, the Sort method, Del deletes an element from the list, specifies the list, and the first few elements

Tuples are also a sequence, and tuples are immutable like strings.
Tuples are defined by a comma-separated list of items in parentheses
Tuple with 0 Item Intent empty = ()
Contains 1 items the tuple Myone = (2,) must be followed by a comma after the item
The most common use of tuples is to use the----%s table in a print statement
For example zoo = (' Apple ', ' people ')


A dictionary, consisting of a sequence of keys and values, with a colon in the middle, commonly called a JSON
D = {Key1:value1,key2:value2}
A dictionary is an instance/object of the Dict class
The items () method of the dictionary, for in loop
For name,address in Ab.items (): Printing keys and values
A in AB: detects if a key value exists

Sequence
Lists, tuples, and strings are sequences, and the sequence is characterized by index operators and slicing operators.
An index is a particular item that is crawled from a sequence.
The slice operator allows us to get a slice of the sequence, which is part of the sequence
Variable name specifies the memory of the object that is stored in the computer, which is called the name-to-object binding
"The Magic of sequences: you can access tuples, lists, and strings in the same way"

Gets the value in the sequence according to the index, can be a negative number, 1 is the last element
The slice operator is a sequence name followed by a square bracket, with a pair of optional digits in the square brackets, the number is optional, and the colon is required
The number before the colon indicates where the slice begins, the number after the colon indicates where it ends, the start position is included in the sequence slice, and the end position is included outside the sequence slice
[:] Returns a copy of the entire sequence
The assignment statement for the list does not create a copy, you must use the slice operator list[:] To create a copy of the sequence
[:] This is a copy of the current object, the assignment is a reference


Strings are also objects, strings used in programs are objects of the Str class
StartsWith () tests whether the string starts with the given string Name.startwith ("war")
In is used to verify that the given string is part of a second string, a in name
Find finds the position of the given string in another string, and returns-1 means the substring is not found
Join () The string delimiter that is used to stitch the sequence with a delimiter. Join (Sequence)


Python Backup program
Using the OS module, TIME module
Time.strftime () Custom Time%y%m%d%h%m%s
Zip-q table is the zip command quiet work-R represents the work of the zip command on directory recursion
Os.path.exists Check if there is a directory with the current date as the name
Os.mkdir Creating a Directory
OS.SEP variable usage gives directory separators based on operating system, window \ \ linux/, portability
Os.system () Run command command runs successfully, returns 0
The ideal way to create a backup is to use ZipFile and Tarfile

Software Development Process
1, What (analysis)
2, how to (design)
3, write (implement)
4, testing (testing and commissioning)
5, use (implementation or development)
6, Maintenance (optimization)


9, Object-oriented
A variable that belongs to an object or class is called a domain.
Fields and methods are called properties of a class
Classes are created using class, and the fields and methods of the classes are listed in an indent block
Object itself self
The method of the class must have an additional first parameter name of self
If a class is MyClass and an instance of this class MyObject
Python Call object Method Myobject.method (ARG1,ARG2)
will be automatically converted from Python to Myclass.method (MyObject, Arg1, arg2),


__init__ method, object initialization operation, class object is built, run immediately
__del__ method, the object dies when it is run
def __init__ (self)
def __del__ (self)
Methods for classes and objects
Two types of domains: variables for classes and variables for objects
The variables of a class are shared by all objects of a class
The variables of the object are owned by each instance of the class

__privatevar Private variables
You only want to use a single underscore prefix in a class or object


Inheritance---Improve the reusability of code through inheritance
Class Children (parent): Inherit parent class
Python does not automatically inherit the base class constructor, which refers to __init__
__base__



Input/Output
Open a file with an object of the file class, file ("Open.txt", "W")
' R ' read mode, ' W ' write mode, ' a ' Append mode
Write () method writes to the file
Close file, ReadLine () method to read each line of the file


Storage = = Storage and storage
Python's improved standard module, called Pickle, can be used to store objects in a durable, flawless
There is another module called Cpickle, which, like the pickle function, is 1000 times times faster than pickle
Import Cpickle as P uses a shorter module name
P.dump (FILELIST,F)
The dump function of the storage module is used to store the object in an open file, which is called a storage
P.load (f)
Use the return of the load function of the Pickle module to retrieve the object, a process known as fetching storage


Exception
Error is the work done by the wrong processor
Handling Exceptions
Try: Except
Put the statement that could throw the error into the try
Put the error handling statement into the except
Except can handle a single error and exception
If the name of the error or exception is not given, it will handle all errors and exceptions

To throw an exception:
Throw an exception using the Raise statement, Error or exception class
Try: Finally
Under a try block, you can use both the EXCEPT clause and the finally block


Python standard library
The Python standard library is installed with Python and contains a large number of its useful modules

SYS module contains system-corresponding functions
OS module contains common operating system features



Os.name Show the platform you are using
The Os.system function is used to run shell commands
The Os.path.split function returns the directory and file name of a path, returning the tuple
Os.path.isfile () verifies whether the given path is a file
Os.path.isdir () verifies whether the given path is a directory
Os.path.exists () The real existence given by the test


Http://www.ruanyifeng.com/blog/2009/10/5_ways_to_search_for_files_using_the_terminal.html

Python Concise Tutorial Notes

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.