1.0.
installation
1.1.1. Download
Official website: https://www.python.org/downloads/release/python-352/
1.1.2. Configuring Environment Variables
Because we chose to add Python to environment variable when we installed it, so it is installed by default, and no can be changed manually.
environment variable, add path to path, pay attention to the seal number
1.1.3. Python 2 vs 3
1. Default support for Chinese
2. Incompatible 2.x
3. Core grammar adjustment, easier to learn
4. The new feature is only available on 3.x
2.x = default encoding =assic = Not supported
3.x = default encoding =unicode = Default Support Chinese
There are only 2 data types in Py2: str Unicode [where str holds bytes, Unicode is stored in Unicode]
There are only 2 types of data in Py3: str bytes
int and long int type int in Py3 merge Py2
1.1.4. number of system bits
32bit = maximum addressable space for memory is 2**32, 4GB
64bit, =2**64 but actually does not support this great memory, 2**4x, the largest memory currently supported by the motherboard is more than 100 GB
Will 4GB ==64 system be faster than 32-bit systems? = the same
1.1.5. HDD:
5400 rpm = per minute = Cycling
7200 rpm = per minute = Electric bike Ride
10000 RPM = per minute = Ride Fast electric car
15000 rpm = per minute = Motorcycle Mechanical HDD Fastest
SSD = Tesla
1.1.
the way to execute the PY program is:
1. Interaction, the disadvantage of the program can not be permanently saved, mainly with simple grammar test related
2. File Execution
1.2.
python features
1. The language of the idea of simplicity, pseudocode is the greatest advantage, allowing you to focus on solving problems rather than the code itself
2. Direct source code operation, no interpreter required, similar to Java
3. Support for process-oriented and object-oriented programming
4. Use Python programming, no need to consider the underlying, because the underlying has automated memory management
5. Extensibility and embeddable, you can write some programs in C or C + +, in Python, in the same vein you can call Python in C
6. Open source, free, portable, rich library
1.3.
python variables
As in Java, the instructions for changing the address
1.4.
variables
/Constants
the naming rules
variable : is to store some intermediate results during program operation, in order to facilitate later invocation
1. To have descriptive
2. Variable name can only _, number, letter composition, can not be a space or special characters (#?<.,¥$*!~)
3. Cannot use Chinese as variable name
4. Cannot start with a number
5. Reserved characters cannot be used
6. The naming of variables should make sense
constant : Unchanged amount of pie = 3.141592653 ....
All variables in the PY are mutable, so the variable names are all capitalized to represent the secondary variables as constants.
1.5.
when memory is released
1. Auto-release: Python has its own PVM mechanism that periodically cleans up memory
2. Manual release: Del name (Empty the Stack direct guide, the variable cannot find the index), PVM will automatically reclaim the memory
1.6.
character encoding
ASCII: Translates binary into a character we can read, a total of 255 symbols, all characters occupying 8 bits 1 bytes
The first table that supports Chinese is called GB2312.
Unicode universal code supports all country and region codes and backwards compatible gb2312, GBK
2**16 = 65535 = A single character is used to occupy 2 bytes uniformly
UTF-8 = Extended set of Unicode, variable-length character encoding set
Assic-->gb2312->gbk1.0-->gb18030
Assic-->unicode-->utf-8 (supports all national languages, supports Chinese)/utf-16
There are only 2 data types in the Py3: Str[unicode encoding] bytes[hexadecimal encoding], 2 can be converted to each other, and the other transitions need to be transferred between
Bytes-->int: int (str (bytes (' 123 ', ' utf-8 '), ' Utf-8 ')) # Encoded
int and long int type int in Py3 merge Py2
1.7.
annotations and simple user input and output
Chinese code: #coding: Utf-8
Single-line comment: Use #
# print ("Hello World")
Multiline Comment: three single or double quotes (single and double quotes are the same), when there are variables, can be used as input to multiple rows
"Print (" Hello World ")
Note: The single and double quotes effect is the same, but in order to sometimes English needs, such as my= ' It's me ' inside the abbreviation, the program will be considered a variable to terminate, so it is best to use double quotes my= "It's Me"
User input:
All the data that Input/raw_input accepts is a string, and even if you enter a number, it will still be treated as a string.
Int (age): Converts a string to an integer type
STR (age): Converts an integer to a string type
Death_age = 80max_age=90name = Raw_input ("Your Name:") Age = raw_input (' Your Age: ') #print (type (age)), print ("Your name is : ", name" Print ("Your:", age) print ("Your grandpa are older than you:", Max_age-int (age))
Use of print:
has a comma (",") and is processed in 2 separate character sets
&NB Sp Need to work together, you need "+" to do the concatenation of strings, different types need to transform
3 single/double quotes can also be used for multiple lines of input
Print is a function, so print and parentheses do not need a space directly;
Print ("Sorry, ~_~") print "Hello" + "world" print "Hello" + "World" print ("Hello", end= "___") #end Default is line-wrapping print () #等价于换行, end defaults to line msg= "" "helloworld2017" "" "Print (MSG)
1.8.
If statement implementation guess age
Python is an implementation of syntax by indentation, and the indentation level must be the same, or it will be an error
If...else is a whole and does not necessarily need to be present at the same time, but there is else must have if
# if int (guess_age) = = Max_age: note Space on equal 2 sides
True of the while face must be uppercase
Break can exit the loop, exit (0) can also quit the loop, or you can set the flag bit to end the loop
Max_age = 90#flag=true#true must be uppercase ha #while flagwhile True: guess_age = raw_input ("Input the Age of you guess>>:") if int (guess_age) = = Max_age: print ("congratulation ^_^") break ; # Terminate Loop #exit (0) #flag =false elif int (guess_age) > Max_age: print ("Please try small") elif Int (guess_age) < max_age: print ("Please try bigger") else: Print ("Sorry, ~_~") print "END"
1.9.
Arithmetic Operators
Division calculation
Print (5/2) # 2.5print (5//2) # 2
Python's special judgment: Continuous size judgments
A=100b=90c=200if b<a<c: print "OK" # OK
Determine the maximum value in three numbers
A=int (raw_input ("Input the first num:")) B=int (raw_input ("Input the first num:")) C=int (raw_input ("Input the first num:") ) Max =aif Max < b: max = b; If Max < c: max = c; Print Max else: print max
PY built-in math functions
# ABS (x) returns the absolute value of the number, such as ABS (-10) return 10# ceil (x) returns the number of the integer, such as Math.ceil (4.1) returns the AA CMP (x, y) if x < y returns-1 if x = = y returns 0 if x > y returns # exp (x) returns the X-Power of E (ex), such as MATH.EXP (1) returns 2.718281828459045# fabs (x) returns the absolute value of the number, such as Math.fabs (-10) Returns the 10.0# floor (x) returns the number of the lower-rounding integer, such as Math.floor (4.9) returned 4# log (x) as Math.log (MATH.E) back 1.0,math.log (100,10) return 2.0# LOG10 (x) returns the logarithm of x with a base of 10, as MATH.LOG10 (100) returns 2.0# max (x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence. # min (x1, x2,...) Returns the minimum value for a given parameter, which can be a sequence. # MODF (x) returns the integer part of x with the fractional portion, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type. # POW (x, y) the value after the x**y operation. # round (x [, n]) returns the rounding value of the floating-point number x, given the n value, which represents the digits rounded to the decimal point. # sqrt (x) returns the square root of the number x, the number can be negative, the return type is real, such as MATH.SQRT (4) returns 2+0J
Special Assignment operators:
num + = 1 is equivalent to num = num + 1num = 1 equivalent to num = num-1num *= 2 equivalent to num = num * 2num/= 2 equivalent to num = Num/2nu M//= 2 equivalent to num = num//2num%= 2 equivalent to num = num% 2num **= 2
Short Circuit principle : Similar to &&,| in Java |
For and if the first condition in front is false, then the expression of the two conditions of the and before and after will be calculated as false, and the second condition will not be computed
For or if the first condition in front is true, then the result of an expression consisting of or before or after two conditions must be true, and the second condition will not be computed
Not is true or false and not true ==> (not true) or (False and (not true))--"true"
1.10.
break/continue
Break: Exit this cycle
Continue: Exiting the current loop
Note: Python's while statement can also be used by the ELSE syntax
Num=1while num<=9: num + = 1 if num = = 3: continue print (num) Else: print "while also have else synde X
1.11.
Coding Specifications
"More References" http://blog.csdn.net/robinzhou/article/details/6991078
Constants : uppercase and underlined User_constant For global variables that do not change, use uppercase and underline. Private variables : lowercase and a leading underscore _private_value There is no private variable in Python if you encounter a variable that needs to be protected, use lowercase and a leading underscore. But this is only a convention between programmers, to warn that this is a private variable, the external class does not go to access it. But in fact, the external class can still access this variable. built-in variables : lowercase, two leading underscores, and two post-underline __class__ A two leading underscore causes the variable to be renamed during interpretation. This is to avoid conflicts between built-in variables and other variables. User-defined variables should be strictly avoided in this style. So as not to cause confusion. 2 Functions and methods In general, lowercase and underscore should be used. But some older libraries use mixed case, that is, the first word is lowercase, then the first letter of each word is capitalized, and the rest is lowercase. But now, lowercase and underscores have become specifications. Private method : lowercase and a leading underscore def _secrete (self): Print "Don t test me." As with private variables, this is not really a private access right. It is also important to note that the generic function does not use two leading underscores (Python's name adaptation feature will work when two leading underscores are encountered). Special functions are mentioned later. Special methods : Lowercase and two leading underscores, two post-underline def __add__ (self, Other): Return int.__add__ (Other) This style applies only to special functions, such as operator overloading. function Parameters : Lowercase and underscore, default equals no spaces on both sides def connect (self, user=none): Self._user = user Class 3 Class is always named with the hump format, that is, all words are capitalized with the remaining lowercase letters. The class name should be concise, precise, and sufficient to understand the work done by the class. One common method is to use a suffix that represents its type or attribute, for example: SQLEngine Mimetypes For base classes, you can use a base or Abstract prefix Basecookie Abstractgroup Class UserProfile (object): def __init__ (self, Profile): return self._profile = Profile
def profile (self): Return Self._profile 4 Modules and Packages In addition to the special module __init__, the module name uses lowercase letters that are not underlined. If they implement a protocol, LIB is usually used as a suffix, for example: Import Smtplib Import OS Import Sys 5 About parameters 5.1 Do not use assertions to implement static type detection Assertions can be used to examine parameters, but should not only be static type detection. Python is a dynamic type language, and static type detection violates its design idea. Assertions should be used to avoid calls to functions that are not meaningless. 5.2 Do not abuse *args and **kwargs The *args and **kwargs parameters can break the robustness of the function. They blur signatures, and code often begins to build small parametric parsers where they shouldn't be. 6 other
6.1 Naming a Boolean element with a has or is prefix Is_connect = True Has_member = False 6.2 Naming sequences in plural form Members = [' user_1 ', ' user_2 '] 6.3 Naming a dictionary with an explicit name person_address = {' user_1 ': ' Ten Road WD ', ' user_2 ': ' Street Huafu '} 6.4 Avoiding generic names Names such as list, dict, sequence, or element should be avoided. 6.5 Avoid existing names Names such as OS, SYS, which already exist, should be avoided. 7 some numbers Number of rows: PEP 8 is set to 79 columns , which is a bit harsh. Depending on your situation, for example, do not exceed the number of display columns of the editor when full screen. This makes it easy to view the code without moving the horizontal cursor. A function: Do not exceed 30 lines of code to display in a screen class, you can see the entire function without using a vertical cursor. A class: Do not exceed 200 lines of code, and do not have more than 10 methods. Do not exceed 500 lines for a module. |
1.12. Printing Right triangle
#coding: Utf-8#python 3.5.2lines = int (input ("Please input the Lines:")) while lines > 0: tmp = lines while TMP > 0: print ("*", end= "") #不换行 tmp-= 1 print () lines-= 1
1.13Print 9*9
#Python 3.5.2first = 9while First > 0: sec = 1 while sec <= First: print (str (SEC) + "*" +str (first) + "=" +str (First * sec), end= "\ T") #不换行 sec + = 1 print () first- = 1
Python Learning---python Installation and basics 1205