Python Learning Notes

Source: Internet
Author: User
Tags exit in set set

2016-05-03

In recent days read a book on the basics of Python-Algorithms and Programming Basics (Python version), extract the basic knowledge and better programming methods for everyone to learn, while convenient for later memories.

1 , basic syntax

The basic types in Python are integer int, float float, boolean bool, string str, tuple tuple (), list list[], set set{}, dictionary type dict{}, and so on. Python also supports complex type complex, real + imag (j/j suffix).

A = 3= 5.4>>>type (True)>>><class ' bool ' >>>>acomplex = 4.23 + 8.5j>>> acomplex>>> (4.23000000000004 + 8.5j)

When you perform an equality operation on floating-point data, you cannot directly use the equals = = operation, the floating-point type can represent a large number, and can perform high-precision calculations, but because floating-point numbers are represented in a fixed-length binary in a computer, some numbers may not be calculated accurately, and calculations can cause errors.

>>>2.1–2.0>>>0.1000000000000009

The results obtained in this example are slightly larger than normal, and we can see that it is not possible to use = = To determine whether the difference between the two floating-point numbers is small enough to be equal.

Numeric Object Operation table

Operator

Describe

X+y, X-y

Add, Subtract

x*y,x/y, x//y, X%y, X**y

Multiply, divide, divide, balance, seek, and seek to be a exponentiation.

<, <=,, >=, = =,! =

Comparison operation

Or, and, not

logical operators

=,+=,-=, *=,/=, **=

Assignment, compound operation

In addition, the python is allowed to be cascaded compared:

>>>a, B, C = ten, 30>>>a <=b <= c>>>true

Manipulation of text data

Regular expressions are used more in character matching and lookup.

Create a new string variable directly s = "Hello", you can also slice and index, directly with a string * number to represent the repeating string (this is very useful (* ̄︶ ̄) y)

>>> "HI" * 3>>>' hihihi '>>> "Student" [5]>>>' n '> >>s = "School">>>s[1:4>>> ' cho '# slices, very practical.

About the index and slice of the string:

H

E

L

L

O

P

Y

T

H

0

1

2

3

4

5

6

7

8

9

-10

-9

-8

-7

-6

-5

-4

-3

-2

-1

Bulk data representations and operations: tuple tuples, list lists, set set and dictionary Dict

Meta-group

>>>T1 = 1, 2, 3>>>t2 = ' sound ', ' easy ', ' western ', ' North '>>>t3 = T1, T2& gt;>>T3>>> ((1, 2, 3), (' Sound ', ' easy ', ' western ', ' North '))>>>t4 = TUPL E ("python")>>>T4>>> (' P ', ' y ', ' t ', ' h ', ' o ', ' n ')

List

>>>L1 = list ("Python")>>>L1>>>[' P ', ' y ', ' t ', ' h ', ' o ', ' n '] >>>L2 = List (("Hello", "Well", "Python"))>>>L2>>>[' hello ', ' well ', ' Python ']

Tuples and lists can all be indexed by subscript elements

>>>l2[1][1]>>> ' e '

Usually use the conversion between list and string, read the file, parse the input string, etc., the split () function can convert a string to a list data type, in syntax is commonly used in string lookups and traversal, and used with a for loop.

Collections and dictionaries

The set has a de-weight function, which is more suitable for intersection and set, so it is convenient to compare the same elements and different elements of two sets, there are many methods: Union (), Difference (), intersection (), add (), remove (), new collection S1 = {1 , 55, 6, 90, 34} ...

The dictionary uses key values to find information, between the key value and the index value reflects a correlation between data, and the Java map is a bit like, is a mapping data type, and set, unordered storage, cannot be indexed. Dictionary creation, D1 = {1: "Mon", 2: "Tue", 3: "Wed",......}, with constructor dict,monthdays = dict (Jan = +, Feb = 28, ...)

>>>d1 = {(3,1): 3, (3,2): 6, (3,5): ...} >>>d1[(3, 1)]>>>3

2 , control structure

If condition 1:

Condition 1 established ...

Elif Condition 2:

Condition 2 established ...

else:

Otherwise...

Python There is no switch statement in the, only if ... Elif ... Elif ... else ...

For iteration variable in string, sequence, or iterator:

Loop body

Else

An expression

Normal exit in the loop, the else block is executed (but it seems less common)

where the range () function is often used in the For Loop, range (start, end, step = 1), where the list element K,start <=k <end (the index in Python is so, half open and half closed).

While loop condition:

Loop body

As in Java, there are also break, continue,pass statements, which are often used in judgments and loops.

Input and output of data

In the Windows System file directory using the backslash ' \ ', and in Linux '/', about the table of contents I also have some problems not clear, need to continue to study.

Terminal input output, input (' Hint text string ') and print (Value,...,sep = ', end = ' \ n ', file = sys.stdout, flush = False), where ... Indicates that multiple objects can be output, separated by ', ', Sep represents the delimiter when multiple output objects are displayed, the default is a space, end represents the end symbol of the print statement, and the default value is a newline character, which means that the print default output wraps after the line.

Insert a ditty: In the Practice encountered repr (), str () and eval () function problems, to search the Internet a lot, Python really magical Shcha (???) Shcha

Format Control Symbols

Format symbols

Representation type

Format symbols

Representation type

%f%f

Floating point number

%o

Eight-binary integers

%d%i

Decimal integer

%x%x

hexadecimal integer

%s

String

%e%e

Technology

%u

Decimal integer

%%

Output

Input/Output redirection <, >

Operation of the file:

Open (File,mode = "R", ...)

F.read (size) returns a string, F.readline () reads a row and returns a string, F.readlines () returns a list of string elements for each row

Write () function,< file Object >.write (string) when data is written

F.read () After the file pointer to the end of the file, if again, read will be empty content, if you want to go again, you need to use the Seek () function, F.seek (offset, from_what), specific usage in practice to learn it.

< file object >.close ()

Exception Handling Try: ... Except: ... Else: ... , manually throwing an exception raise statement, inheriting the exception class

3 , object-oriented building program

The system generally provides some functions for users to call directly, in order to enhance the processing capacity of the system, user-friendly, these functions become system functions, system functions are divided into built-in functions and standard function library, the built-in functions are part of the language, can be used directly, such as ABS (), in addition to the system can import external functions.

define functions;

def function name (parameter table):

Function Statement block

[Return value]

Attention:

    • The function name should be a valid Python identifier, and the parentheses immediately following the
    • parameter is optional, multiple time with "," separated, default value is placed in the last
    • After defining the function, you need to follow the words ":", downward indent
    • In the function, returns the value of the function through the return statement, or without a return statement, so that the function returns a null value in None-python (equivalent to NULL in Java)

Functions in the program can be called multiple times, called functions in the form of a function name (the actual parameter table), in a module, the definition of functions to the executable program, about local variables and global variables, if the function defines a local variable with the same name as a global variable, the local variable mask the global variable, You can call global variables in a function with the global keyword, and you can use a variable without initialization in Python, which I'm not used to, but has its benefits.

The actual arguments provided when the function is called are merely supplying values to the function, and the changes within the function do not affect the original value, except for the list , if the list object is used as a parameter to the function, the reference address of the list is passed to the function.

A file is a module, the module can have classes, functions, variables, etc., the class can also have, put multiple files in a folder is a package (just their own understanding, do not know right)

Import the library using the import package name. module name, the package name when accessing the function. Module name. function ()

There are algorithms and so on not much to say, data structure, complexity analysis, find sorting problems and so on, recursion is also very important oh (* ̄︶ ̄) y

Python and Java have a lot of ideas of the same point, continue to discuss it, today is here, bye (⌒▽⌒)

4 , Summary

There are many standard libraries, such as time, calendar and so on, need to continue to learn, the overall feeling of Python is very convenient, very powerful, it is easy to achieve a function, of course, the graphical interface I have not learned, I believe there will be a lot of surprises.

Because it is a beginner, so the text will inevitably appear wrong, please correct me, forgive me, the text of many excerpts are in this book (will not infringe intellectual property rights and so on ...) ), first write, not very good, believe that will be getting better, (⌒▽⌒)

Computer knowledge is really a bottomless pit, as a layman, can only learn and cherish ...

Python Learning Notes

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.