Python Learning notes (i)

Source: Internet
Author: User

Directory:

First, variable and constant

Second, character encoding

Third, user interaction program

Iv. if Else statement

V. Circulation

Vi. initial knowledge of the module

Vii. What is PYC?

Viii. data types and data operations

Ix. bytes Data Types

10 or three-dollar operation

XI. hexadecimal notation

12. The difference between a byte packet and a string

13, the use of the list

14, Ganso

XV, String Common operations

16. Use of dictionaries

First, constant and variable

Constants: Python does not have a constant concept, usually we capitalize the constant name to indicate that it cannot be modified

Variable:

1. Variable definition rules:

A. Variable names can be any combination of letters, numbers, or underscores.

B. The first character of a variable cannot be a number

C. The following keywords cannot be declared as variable names:

[' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ',

' For ', ' from ', ' global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' Try '

, ' while ', ' with ', ' yield ']

2. Issues to note when assigning variables:

Name ="redleafage Zhang"     #name points to Redleafage Zhangname2 = Name#name2 points to redleafage Zhang instead of namePrint("My name is", name,name2)#Print Result: My name is Redleafage Zhang Redleafage Zhangname="Paoche Ge" #name points to Paoche Ge, but name2 still points to redleafage ZhangPrint(name,name2)#Print Result: Paoche Ge redleafage Zhang

When you assign another variable with one variable, the other variable points to the value that the previous variable points to, not the variable pointer. Therefore, after modifying the value of the original variable, the value of the newly assigned variable will not change.

Second, character encoding

1. Coding history:

    

ASCII (American Standard Code for Information interchange, United States Standards Information Interchange Code) is a Latin alphabet based computer coding system, mainly used to display modern English and other Western European languages, which can be represented at most 8 bits ( A byte), that is: 2**8 = 256-1, so the ASCII code can only represent 255 symbols.

    

To deal with Chinese characters, programmers designed GB2312 for Simplified Chinese and big5 for traditional Chinese.

GB2312 (1980) contains a total of 7,445 characters, including 6,763 Kanji and 682 other symbols. The inner code range of the Chinese character area is high byte from B0-f7, low byte from A1-fe, occupy code bit is 72*94=6768.

5 of these seats are d7fa-d7fe.

    

GB2312 supports too few Chinese characters. The 1995 Chinese character extension specification GBK1.0 contains 21,886 symbols, which are divided into Chinese characters and graphic symbol areas. The Chinese character area consists of 21,003 characters. The 2000 GB18030 is the official national standard for replacing GBK1.0

Quasi -. The standard contains 27,484 Chinese characters, as well as Tibetan, Mongolian, Uyghur and other major minority characters. Now the PC platform must support GB18030, the embedded products are not required. So mobile phones, MP3 generally only support

GB2312.

From ASCII, GB2312, GBK to GB18030, these coding methods are backwards compatible, meaning that the same character always has the same encoding in these scenarios, and the latter standard supports more characters. In these codes, English and Chinese can be unified in

Acting The method of distinguishing Chinese encoding is that the highest bit of high byte is not 0. According to the programmer, GB2312, GBK, and GB18030 belong to the double-byte character set (DBCS).

Some Chinese Windows default internal code or GBK, you can upgrade to GB18030 through the GB18030 upgrade package. But GB18030 relative GBK increases the character, the ordinary person is difficult to use, usually we still use the GBK to refer to the Chinese Windows inside code.

It is clear that the ASCII code cannot represent all the words and symbols in the world, so it is necessary to create a new encoding that can represent all the characters and symbols, namely: Unicode

Unicode (Uniform Code, universal Code, single code) is a character encoding used on a computer. Unicode is created to address the limitations of traditional character encoding schemes, which set a uniform and unique binary for each character in each language.

encoding, which specifies that characters and symbols are represented by at least 16 bits (2 bytes), that is: 2 **16 = 65536,
Note: Here is a minimum of 2 bytes, possibly more

UTF-8, which is compression and optimization of Unicode encoding, does not use a minimum of 2 bytes, but instead classifies all characters and symbols: the contents of the ASCII code are saved with 1 bytes, the characters in Europe are saved in 2 bytes, and the word trailing characters 3 in East Asia.

Bytes saved ...

Therefore, when the Python interpreter loads the code in the. py file, the content is encoded (default Ascill)

Third, user interaction program

1. Enter: input

Note: The value entered by input defaults to the STR type, and if other types are required, you want to cast

2. Formatted output:

Method One:

      

 name = input ( " name:  "  ) Age  = Int (input ( "  age:   "  )  print   = input ( Span style= "COLOR: #800000" > " job:  "  ) Salary  = input ( " salary:  "  ) info1  = Span style= "COLOR: #800000" > ""  --------info of {_name}-----name:%sage:%sjob:% ssalary:%s  % (name,name,age,job,salary) 

Method Two:

    

" " --------info of {_name}-----name:{_name}age:{_age}job:{_job}salary:{_salary} " . Format (_name = name,            = Age ,            = job,            = salary)

Method Three:

Info3 =  "--------info of {0}-----name:{0}age:{1}job:{2}salary:{3}" . Format (name,age,job,salary)

3. Hide Password

If you need to enter a password, you can use the Getpass module (Pycharm can not be used, can only be run in the shell)

    

Import= input ("Username:"= Getpass.getpass ("  Password:")print(Username,password)

Iv. if Else statement

  

Age_of_oldboy = 56Count=0 whileCount <3: Guess_age= Int (Input ("Guess Age:"))    ifGuess_age = =Age_of_oldboy:Print("yes,you got it!")         Break    elifGuess_age >Age_of_oldboy:Print("think smaller ....")    Else:        Print("think bigger ...") Count+ = 1ifCount = = 3: Continue_confirm= Input ("Do you want to keep guessing ...?")        ifContinue_confirm! ='N': Count= 0

V. Circulation:

1.while Cycle

    

#author:redleafage ZhangAge_of_oldboy = 56Count=0 whileCount <3: Guess_age= Int (Input ("Guess Age:"))    ifGuess_age = =Age_of_oldboy:Print("yes,you got it!")         Break    elifGuess_age >Age_of_oldboy:Print("think smaller ....")    Else:        Print("think bigger ...") Count+ = 1Else:#while can also add else, which means that if the loop condition is not met, the else content is executed    Print("You have tried too many times...fuck off")

2.for Cycle

    

1Age_of_oldboy = 562  forIinchRange (3):3guess_age = Int (input ("Guess Age:"))4     ifGuess_age = =Age_of_oldboy:5         Print("Yes,you got it.")6          Break7     elifGuess_age >Age_of_oldboy:8         Print("think smaller ...")9     Else:Ten          Print("Think bigger!") One Else:#for loop can use else, same as while A     Print("You have tried too many times. Fuck off")

3.range

Format: Range (start, end, number of steps)

    

 for  in range (0,10,2)    print (i)  # This code only prints 0,2,4,6,8

4.countinue

Jump out of this loop and perform the Next loop

    

 for  in range (0,10):    If i < 3:        print("loop " , i)     Else :         Continue    Print ("hehe")

Vi. initial knowledge of the module

1.sys Module

Sys.path: Print Environment variables

Site-package generally for the third-party inventory placement, standard library in the previous menu Lib, the general standard library in print (Sys.path) printed out of these paths

        

SYS.ARGV: Prints the current file relative path, which can be appended with parameters. Pycharm can invoke an absolute path.

# author:redleafage Zhang Import SYS Print (SYS.ARGV) Print (Sys.argv[2])

2.os Module

Os.system (' dir '): Print current directory under Win system

Os.mkdir (' New_dir '): Creating a new module

3. Import the module:

Import Module Name

Note: Because the Python search module is automatically searched under the directory in the environment variable, the import module needs to add a pathname or save it under Site-package, or add a new environment variable (UDR) when it is not under the same path

Vii. What is PYC?

Before we say this question, let's start with two concepts, pycodeobject and PYC files.

The PYC we see on the hard drive naturally doesn't have to say much, and pycodeobject is actually the result of a Python compiler actually compiling it. Let's just get to the bottom of it and keep looking down.

When the Python program runs, the result of the compilation is saved in the Pycodeobject in memory, and when the Python program finishes running, the Python interpreter writes Pycodeobject back to the PYc file.

When the Python program runs for the second time, the program will first look for the PYc file on the hard disk, and if it is found, load it directly or repeat the process.

So we should be able to locate Pycodeobject and pyc files, we say that PYc file is actually a kind of persistent saving way of pycodeobject.

PYC: Pre-compiled bytecode file, not machine code, is a semi-finished product.

Process: Run--Look for compilation results--some words run directly, no words are compiled, and saved in PYc.

Viii. data types and data operations

Data type

1. Digital

Long integers are just larger integers.

3.23 and 52.3E-4 are examples of floating-point numbers. The e tag represents a power of 10. Here, 52.3E-4 means 52.3 * 10-4.
( -5+4j) and (2.3-4.6j) are examples of complex numbers, where -5,4 is a real number, j is an imaginary number, and what is the plural in mathematics?

int (integral type)

On a 32-bit machine, the number of integers is 32 bits and the value range is -2**31~2**31-1, which is -2147483648~2147483647
On a 64-bit system, the number of integers is 64 bits and the value range is -2**63~2**63-1, which is -9223372036854775808~9223372036854775807 long (Long Integer)
Unlike the C language, Python's long integers do not refer to the positioning width, that is, Python does not limit the size of long integer values, but in fact, because of limited machine memory, we use a long integer value can not be infinite.
Note that, since Python2.2, Python automatically converts integer data to long integers if an integer overflows, so it does not cause any serious consequences if you do not add the letter L after long integer data.
Float (float type)First Literacy http://www.cnblogs.com/alex3714/articles/5895848.html
A floating-point number is used to process real numbers, which are numbers with decimals. Similar to the double type in C, accounting for 8 bytes (64 bits), where 52 bits represent the bottom, 11 bits represent the exponent, and the remaining one represents the symbol.
Complex (plural)
The complex number consists of real and imaginary parts, the general form is X+yj, where x is the real part of the complex, and Y is the imaginary part of the complex, where x and y are real numbers. Note: Small number pools exist in Python:-5 ~ 257 2, Boolean true or False 1 or 0 3, string
"Hello World"
The evil string concatenation: The string in Python is embodied in the C language as a character array, each time you create a string, you need to open a contiguous space in memory, and once you need to modify the string, you need to open up again, the evil + sign every occurrence will re-open a space within     。 Binary operations: a=60,b=13

Python Learning notes (i)

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.