The difference between a python and C
c--code compiled directly to get the machine code, machine code directly in the processor execution
python--code compiles the bytecode, the virtual machine executes the bytecode directly and translates it into machine code, and then executes on the processor again
Pros: Python class libraries are many and very concise
Cons: Slow Running
Two Python kinds:
1.cpython--python in C, Python into Python bytecode (most widely used)
2.jpython--python, which is implemented in Java, gets the python source code and compiles it into Java bytecode, then executes
3.Rubypython---python implemented in Ruby
4.PyPy---Python implemented using Python to process Python bytecode for faster execution.
Three-mount Python
1.windows Environment
1. Download package: https://www.python.org/downloads/
2. Installation, c:\python27/
3. Configuration of environment variables
2.Linux Environment
1.python internal execution process: load memory--lexical analysis--parsing---compiling--byte code
Quad-coded (assii, Unicode, UTF-8)
1.ASCII (American Standard Code for information interchange, US Standards Information Interchange Code)
is a computer coding system based on the Latin alphabet, mainly used to display modern English and other Western European languages, which can be represented at most 8 bits (one byte), that is: 2**8 = 256, so the ASCII code can only represent a maximum of 256 symbols.
2.Unicode (Unified code, universal code, single code)
is a character encoding that is used on a computer. Unicode is created to address the limitations of the traditional character encoding scheme, which sets a uniform and unique binary encoding for each character in each language, which specifies that characters and symbols are represented by at least 16 bits (2 bytes), that is: 2 **16 = 65536, at least 2 bytes 16 bits
Features: Can be expressed in Chinese, but can not read to the hard disk
3.utf-8,
is the compression and optimization of Unicode encoding, he no longer uses a minimum of 2 bytes, but instead all the characters and symbols are categorized: the contents of the ASCII code is saved with 1 bytes, the characters in Europe are saved with 2 bytes, the characters in East Asia are saved in 3 bytes ...
Features: Save the hard disk space, all the English using 1 bytes is 8 bits, the Chinese will use 3 bytes or 24 bits, to avoid the waste of space
Note: Here is a minimum of 2 bytes, possibly more
Five Python collective Practice
1.
#!/usr/bin/env python
Print "Hello, World"
Error: ASCII code cannot be expressed in Chinese
Correction: What should be shown tells the Python interpreter what code to use to execute the source code,
Comments:
1. Single-line Comment
#
2. Multi-line comments (with three quotation marks for multiple lines of comments)
"""
......
"""
Parameters
Module
1.sys Module (System built-in module)---SYS.ARGV captures the parameters passed into the Python script
eg
#vim hello.py#!/usr/bin/env python#-*-coding:utf-8-*-import sys #导入模块print SYS.ARGV #调用模块, capture and print the parameters followed by the interpreter
Perform:
[email protected] ~]# python test.py haha
[' test.py ', ' haha '] #两个参数, stored in a container and then printed out
BYTE code:
2. Custom Modules
#vim m.py
#!/usr/bin/env python
#-*-Coding:utf-8-*-
print "Hello"
#vim hello.py
.............. Import # Import Module Print # call the module, capture and print the arguments followed by the interpreter Import # Import m module, use the function inside M
After executing # python hello.py, the. PYc bytecode file (M.PYC) of M is generated, which is the file generated after compiling m.py
Variable: The fact is: point, reference, soft link-refers to the memory of an address to save the content, in fact, is a shortcut to the content within an address
1. Declaring variables, assigning values to variables
Variable name = "string"
2. Rules for variable naming:
1. Variable names can only be any combination of letters, numbers, or underscores
2. The first character of a variable name cannot be a number
3. The following keywords cannot be declared as variable names
[' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' F ' Rom ', ' Global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' WI Th ', ' yield ']
Eg: when two different variables name1, name2 point to the same memory address, modify a variable name1, another variable name2 does not change
>>> name1="hello">>> name2=name1 When you modify name1, the value of name2 does not change > >> name1="123">>> name1'123'> >> name2'hello'
Note: C does not have a string, only characters, so the C-language string is implemented by successive character arrays
The string in python is stored in the C language through a character array [' H ', ' e ', ' l ', ' l ', ' o '], and when the string is modified, Python will re-open and create a character array instead of adding it on the original basis.
such as: "Hello" + "world" + "OK", opened up 3 memory space:
1. "Hello"
2. "Hello World"
3. "Hello World OK"
The newly opened 3-segment memory will eventually be automatically reclaimed by Python's virtual machine garbage collector without causing a memory leak. C language to be released manually.
Python default buffer pool:-5-257,
Input and output:
1.raw_input (): Input function
eg
Raw_input ("Please enter content:")
eg: assigning values
Name=raw_input ("Please enter content:")
Module:
2.getpass module: Let the user enter the content is not visible (general write user login interface write password use)
eg
Import Getpass
Pwd=getpass.getpass (">>>")
Print pwd
Process Control:
1.if Else statement
Eg: single-condition Process Control
Name = Raw_input (" Please enter user name:")if"Alex"# values are compared to values, not memory address comparisons, with "= ="print"Log in Success"Else :print"log in failed"
Attention:
= = is the same as the value of the comparison two variables
is to compare two variables in memory with the same address
Eg: multi-condition Process Control
ifName = ="Eric" :Print "Normal"elifName = ="Tony" :Print "Super"elifName = ="Alex" :Print "Super God"Else:Print "*****"
eg
Import Getpassname= Raw_input ("Please enter user name") PWD= Getpass.getpass ("Please enter your password:")ifName = ="Alex"and PWD = ="123":p rint"Login Successful"Else:p rint"Logon Failure"
Data type:
1. Single value
Digital
Integer, Long integer, float, plural
String
PLACEHOLDER:%s,%d
eg:%s placeholder, call---% ' Alex '
>>> name= "I am%s"% ' Tanjie '
>>> Print Name
I am Tanjie
eg:%d placeholder, call---% ("Alex", 12)
2 formats for string formatting:
>>> message= "I am%s, age%d"% ("Tanjie", +) #只在内存里面分配1次, and + to allocate 2 times
>>> Print Message
I am Tanjie, age 21
Or
>>> name = "I am%s,age%d"
>>> Name% ("Alex", 21)
' I am alex,age 21 '
Or
>>> message = "I am {0},age {1}"
>>> Message.format ("Tanjie", 21)
' I am tanjie,age 21 '
Eg: Print multiple lines
Print "" "
A
B
C
D
"""
Eg: string slicing
Name = "Alex"
Print Name[0] #打印第一个字符
Print Name[0:2] #只打印小于第二个的字符 (included on left, not on right)
Print Name[0:] #打印到结尾的字符串
Print Name[-1] #打印最后一个字符
Print Name[:-1] #打印开头到倒数第二个字符 (included on left, not on right)
Eg: print the last character
Name = "Tanjie"
Print len (name) #返回name的长度
Print Name[len (name)-1] #打印最后一位的字符
Eg: remove spaces at both ends of a string
>>> name= "Tanjie"
>>> Name.strip () #去除两头的空格
' Tanjie '
>>> Name.lstrip () #去除左边的空格
' Tanjie '
>>> Name.rstrip () #去除右边的空格
' Tanjie '
Eg: string split and returned as a list
>>> name= "Tanjie,wangning"
>>> name.split (",")
[' Tanjie ', ' wangning '] #表示按 "," split the name string
To press the TAB key to split, use: Name.split (' \ t ');
To split by space, use: Name.split (");
Boolean value: True/false
Type of 1.type (type)
2.id (value) to view the address of value
2. Collection
List
To create a list:
>>> name_list=[' Tanjie ', ' wangning ', ' Lilin ']
Or
Name_list=list ([' Tanjie ', ' wangning ', ' Lilin '])
Call:
NAME_LIST[0]
NAME_LIST[1]
NAME_LIST[-1]
Append: Modify, append list element, list in memory address does not change
>>> name_list.append ("Tanqi")
Delete:
Del Name_list[0] #删除列表中的第一个元素
List length:
Len (name_list)
Converts the list to a string, separated by _, to return the changed string
"_". Join (Name_list)
eg
>>> "". Join (Name_list)
' Tanjie wangning Lilin '
>>> "". Join (Name_list)
' Tanjiewangninglilin '
>>> "-". Join (Name_list)
' Tanjie-wangning-lilin '
Determines whether an element is inside the list, returns a Boolean value
"Tanjie" in Name_list
eg
>>> "Tanjie" in Name_list
True
Tuple---Tuples cannot be modified, list can be modified
Creating tuples
Tuple= ("Tanjie", "Lilin")
If there is a tuple in the list:
[
"Lilin", ("Tanjie", "Tanqi")
]
You can delete "Lilin" and ("Tanjie", "Tanqi") directly, but you cannot modify the tuple ("Tanjie", "Tanqi").
A dictionary---also known as a key-value pair
Create a dictionary
eg
>>> person={
... "Name": ' Tanjie ',
... "Age": 21,
... "Gender": ' Man '
... }
Find the elements inside the dictionary:
eg
person["Name"]
In-Dictionary loops:
1.
eg
for inch Person : Print # the printed ele is just the key in the dictionary
The use of 2.person.items ()----gets all the elements
eg
For k,v in Person.items (): #将字典里面的键赋值给key, value assigned to Vprint kprint vprint "======"
3.person.keys ()--Get all the keys in the dictionary, wrap them in a list
Use the same person.items ()
4.person.values ()---gets all the value in the dictionary, using the list encapsulation
Use the same person.items ()
STR, list, tuple
Common:
1. Both can be sliced
2. All indexed (Special:-1)
3. All lengths: Len ()
4. Cycle
1.for Cycle
Eg:. All the elements in the list are printed
Name_list = ["Alex","seven","Eric" ] for in name_list:print ele
Use of Eg:break
Name_list = ["Alex","Seven","Eric"] forEleinchname_list:ifEle = ="Alex":Print "%s is here"%(ele) Break #find and jump out of the loopElse:Pass #Pass indicates: Skip, do not execute
Use of Eg:continue
Name_list = ["Alex","Seven","Eric"] forEleinchname_list:ifEle = ="Alex":Print "%s is here"%(ele)Continue #skip this loop, do not execute the following code, go to the next loopif Else=="Eric"Print "%s is here"%(ele)Else:Pass #Pass indicates: Skip, do not execute
2.while Cycle
While condition: #若条件为真执行 ...
....
While True: #死循环
....
While 1==1: #死循环
....
eg
Different points:
After STR is modified, STR will re-open up space in memory, memory address changes
The memory address does not change after the list has been modified, and the tuple cannot modify
Operation:
>>> 5/2
2
>>> 5%2
1
>>> 2**10
1024
>>> 5.0/2
2.5
Text manipulation (read, write):
Process: Find File---Open file---file operation--close file
1. Locate the file:
2. Open the file:
File (parameter 1, parameter 2) Parameter 1: path to files; parameter 2: Mode
Modes are:
1.R, open in read-only mode
2.W, open the file for writing only. Eg: ' r+ ': readable and writable;
3.a, opens a file that is used to append
eg
file_obj = file (filename path, ' r+ ')
File_obj.read () #将所有内容读入内存
File_obj.readlines () #得到以行为值的列表
File_obj.xreadlines ()
eg
For line in File_obj.xreadlines ():
Print Line
Or
For file_obj: #每次循环只读一行, avoid all-in-one read memory
Print Line
File_obj.write ()
File_obj.writeline ()
3. File Operation:
4. File Close
File_obj.closed ()
Python Basics 1