The first Python knowledge points learned by Xiaobai

Python video tutorial column introduces basic Python knowledge points
1. Basic concepts
1.1 Four types
There are four types of numbers in python: integers, long integers, floating-point numbers and complex numbers.

Integers, such as 1
long integers are relatively large integers.
Floating-point numbers such as 1.23, 3E-2
complex numbers such as 1 + 2j, 1.1 + 2.2j
1.2 String
String (sequence of characters)

The use of single quotes and double quotes in python is exactly the same.
Use triple quotation marks ("' or """) to specify a multi-line string. The
escape character ``
natural string, by adding r or R before the string. For example, r"this is a line with \n" Then \n will be displayed, not a newline.
Python allows processing unicode strings, prefixed with u or U, such as u "this is an unicode string".
Strings are immutable . Strings are
concatenated literally, such as " this ""is" "string" will be automatically converted to this is string.
1.3 The naming of
identifiers The naming of identifiers

The first character must be a letter in the alphabet or an underscore'_'.
The other parts of the identifier consist of letters, numbers and underscores.
Identifiers are case sensitive.
1.4 Object
 Any "thing" used in a python program becomes an "object".

1.5 Logical line and physical line
Physical line: is the line where the code written by the programmer is located.
Logical line: refers to the line where the source code is pre-compiled.
Python assumes that every physical row corresponds to a logical row. For example: print("Hello World") is a physical line. Python expects only one statement per line, because it looks more readable.

If you want to use more than one logical line in a physical line, then you need to use a semicolon (;) to specifically indicate this usage. The semicolon indicates the end of a logical line/statement.

E.g:

count = 5print ( "count" )复制代码

It is equivalent to the following statement:

count = 5;print ( "count" );复制代码

Of course, it can also be written as follows:

count = 5 ; print ( "count" );复制代码

It can even be written like this:

count = 5 ; print ( "count" )复制代码

We use the line break of \

print \

("Runsen")复制代码

1.6 Indentation
White space is very important in python, the white space at the beginning of the line is the most important, also known as indentation. The whitespace at the beginning of the line (spaces and tabs) is used to determine the indentation level of the logical line and thus determine the statement.

2. Operators and expressions
2.1 Operators and their usage
Examples of operator names

  • Addition of two objects, such as 3 + 5 to get 8, and characters can also be added to'a' +'b' to get'ab'
  • Subtract one number from another number 5-2 to get 3
  • Multiply two numbers or return a string that is repeated several times. 2 * 3 gets 6, and'a' * 3 gets'aaa'
    ** power returns x to the power of y 3 ** 4 gets 81 (that is, 3 * 3 * 3 * 3)
    / Divide x by y 4/3 to get 1 (division of integers gives integer results). 4.0/3 or 4/3.0 gives 1.3333
    //
    Divide the whole number and return the integer part of the quotient 4 // 3.0 gives 1. % Take the modulus and return the remainder of the division 8% 3 gives 2. -25.5% 2.25 gets 1.5
    << left shift, shifts the binary of a number to the left by a certain amount, that is, how many 0s are added to the right, such as 2 << 2 to get 8, and binary 10 becomes 1000

Shift right shifts the bits of a number to the right by a certain number, that is, delete the digit 10>>2 on the right to get 2, and the binary 1010 becomes 10, directly delete the second 2 digits
& the bitwise and 9 & 13 of the bitwise and number Get 9, binary 1001&1101, become 1001, and the corresponding positions of the two values ​​are 1, then the result is 1, otherwise it is 0
| bitwise or 5 | 3 to get 7. Binary 101&11 becomes 111. If one of the corresponding positions of the two values ​​is 1, then the result is 1, that is, if both are 0, the result is 0, 101 and 11 are not both 0, so 111
^ bitwise The bitwise XOR of the XOR number 5^3 gets 6, and the binary 101&11 becomes 110. If the corresponding positions of the two values ​​are the same, the result is 0, that is, if both are 0 or both are 1, the result is 0 , 101 and 11, the first one is 1, so 110
~ bitwise flip of x is -(x+1) ~5 to get 6
<less than returns whether x is less than y. All comparison operators return 1 for true and 0 for false. 5 <3 returns 0 (ie False) and 3 <5 returns 1 (ie True). It can also be connected arbitrarily: 3 <5 <7 returns True.
Greater than returns whether x is greater than y 5> 3 returns True. If both operands need to be numbers
<= less than or equal to return whether x is less than or equal to yx = 3; y = 6; x <= y returns True
= greater than or equal to return whether x is greater than or equal to yx = 4; y = 3; x> = y returns True
== equal to whether the comparison object is equal x = 2; y = 2; x == y returns True
!= not equal to compare whether two objects are not equal x = 2; y = 3; x != y returns True .
not Boolean "not" If x is True, return False x = True; not y returns False.
or Boolean "or" If x is True, it returns True, otherwise it returns the calculated value of y. x = True; y = False; x or y returns True
2.2 Operator precedence
. Operator precedence (from low to high)

Operator description
lambda Lambda expression
or Boolean "or"
and Boolean "and"
not x Boolean "not"
in, not in Membership test
is, is not Identity test
<,<=,>,>=,!=,= = Comparison

^ Bitwise XOR

& Bitwise AND
<<, >> Shift
+,-Addition and subtraction
*, /,% Multiplication, division and remainder
+ x, -x sign
~ x bit flip
** Index
~x Bit flip
x.attribute attribute reference
x[index] subscript
x[index:index] addressing section
f(arguments…) function call
(experession,…) binding or tuple display
[expression,…] list Display
{key:datum,…} dictionary
display'expression,…' string
2.3 output
python console output use print

print ("abc"  )  #打印abc并换行print ("abc%s" % "d"  )  #打印abcdprint ("abc%sef%s" % ("d", "g")  )  #打印abcdefg复制代码

3. Control flow
3.1 if statement

i = 10n = int(input("enter a number:"))if n == i:

    print( "equal")elif n < i:

    print( "lower")else:    print ("higher")复制代码

3.2 while statement

while True:    passelse:    pass#else语句可选,当while为False时,else语句被执行。 pass是空语句。复制代码

for 循环 for…in

for i in range(0, 5):    print (i)else:    pass# 打印04复制代码

Note: when the for loop is over, execute the else statement; range(a, b) returns a sequence from a to b, but not including b. The default step size of range is 1, and you can specify the step size, range(0,10 ,2);

3.3 The break statement
terminates the loop statement. If it is terminated from for or while, any else in the corresponding loop will not be executed.

3.4 continue statement The
continue statement is used to adjust the remaining statements of the current loop, and then continue to the next loop.

Here are the main differences between break and continue:

break: jump out of the entire loop
continue: jump out of this loop and continue to execute the next loop.
I hope everyone will keep in mind.

4. Function
Function is defined by def. The def keyword is followed by the identifier name of the function, followed by a pair of parentheses, which can contain some variable names, and the line ends with a colon; next is a block of statements, the function body.

def sumOf(a, b):

    return a + b复制代码

4.1 Function
parameter The name of the parameter in the function is'formal parameter', and the value passed when calling the function is'actual parameter'

4.2 Local Variables The variables
defined in the function have no relationship with other variables with the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable.

The global statement is used when assigning values ​​to variables defined outside the function.

def func():

    global x

    print( "x is ", x)

    x = 1x = 3func()

print(x)#3#1 复制代码

4.3 Default parameters
Some parameters of the function can be made'optional' by using default parameters.

def say(msg, times =  1):

    print(msg * times)

 

say("Runsen")

say("Runsen", 3)复制代码

Note: Only those parameters at the end of the formal parameter list can have default parameter values, that is, when declaring function parameters, first declare the parameters with default values ​​and then declare the parameters without default values, just because they are assigned to the parameters The value of is assigned based on the position.

4.4 Key parameters
If a function has many parameters and you only want to specify some of them, you can assign values ​​to these parameters by naming them (called'key parameters'). Advantages: No need to worry about the order of parameters, making the function simpler; assuming that other parameters have default values, you can assign values ​​to only those parameters we want.

def func(a, b=2, c=3):

    print ("a is %s, b is %s, c is %s") % (a, b, c)

 

func(1) #a is 1, b is 2, c is 3func(1, 5) #a is 1, b is 5, c is 3func(1, c = 10) #a is 1, b is 2, c is 10func(c = 20, a = 30) #a is 30, b is 2, c is 20复制代码

4.5 The return statement The
 return statement is used to return from a function, that is, to jump out of the function. A value can be returned from the function. A return statement without a return value is equivalent to return None. None represents a special type with nothing.

4.5 Document string
doc (document string)

def func():

    '''This is self-defined function

    Do nothing

    '''

    passprint(func.__doc__)#This is self-defined function##Do nothing复制代码

5. Module A
module is a file that contains all the functions and variables you define. The module must have a .py extension. Modules can be'imported' from other programs to take advantage of its functions.

Use'import' to import other modules in the python program, the imported module must be in the directory listed in sys.path, because the first string of sys.path is an empty string, which is the current directory, so the program can be imported The modules of the current directory.

5.1 Byte-compiled .pyc files
Importing modules is time-consuming, and python is optimized to make importing modules faster. One way is to create byte-compiled files, these files have a .pyc extension.

Pyc is a binary file, a byte code generated after the py file is compiled, and it is a cross-platform (platform-independent) byte code, which is executed by the python virtual machine, similar to

The concept of java or .net virtual machine. The content of pyc is related to the version of python. The compiled pyc files of different versions are different.

5.2 from… import
If you want to directly use the variables of other modules or others without adding the prefix of'module name+.', you can use from… import.

For example, if you want to use sys' argv directly, from sys import argv or from sys import *

5.3 Module __name__
Each module has a name. The module name corresponding to the py file is the py file name by default. You can also assign a value to __name__ in the py file; if it is __name__, it means that this module is used by the user

(4) dir() function

dir(sys) returns a list of names of the sys module; if no parameter is provided, that is, dir(), it returns a list of names defined in the current module.
(5) del

del -> delete a variable/name, after del, the variable can no longer be used.

6. Data structure
Python has three built-in data structures: list, tuple and dictionary.

6.1 List
   List is a data structure that deals with a group of ordered items, and a list is a variable data structure. The items of the list are enclosed in square brackets [],

eg: [1, 2, 3], empty list []. To determine whether there is an item in the list, you can use in,

For example, l = [1, 2, 3]; print 1 in l; #True;

Support index and slicing operations; if the index exceeds the range, IndexError;

Use the function len() to view the length; use del to delete items in the list, eg: del l[0] # If the range is exceeded, the IndexError     
list function is as follows:

append(value)  ---向列表尾添加项value

l = [1, 2, 2]

l.append(3) #[1, 2, 2, 3]count(value)  ---返回列表中值为value的项的个数

l = [1, 2, 2]

print( l.count(2)) # 2extend(list2)  ---向列表尾添加列表list2

l = [1, 2, 2]

l1 = [10, 20]

l.extend(l1)print (l )  #[1, 2, 2, 10, 20]index(value, [start, [stop]])  ---返回列表中第一个出现的值为value的索引,如果没有,则异常 ValueError

 

l = [1, 2, 2]

a = 4try:

    print( l.index(a))except ValueError, ve:

    print( "there is no %d in list" % a

    insert(i, value))  ---向列表i位置插入项vlaue,如果没有i,则添加到列表尾部

 

l = [1, 2, 2]

 

l.insert(1, 100)print l #[1, 100, 2, 2]l.insert(100, 1000)print l #[1, 100, 2, 2, 1000]pop([i])  ---返回i位置项,并从列表中删除;如果不提供参数,则删除最后一个项;如果提供,但是i超出索引范围,则异常IndexError

 

l = [0, 1, 2, 3, 4, 5]

 

print( l.pop()) # 5print( l) #[0, 1, 2, 3, 4]print( l.pop(1)) #1print( l) #[0, 2, 3, 4]try:

    l.pop(100)except IndexError, ie:

    print( "index out of range")

 

remove(value)  ---删除列表中第一次出现的value,如果列表中没有vlaue,则异常ValueError

 

l = [1, 2, 3, 1, 2, 3]

 

l.remove(2)print (l )#[1, 3, 1, 2, 3]try:

    l.remove(10)except ValueError, ve:    print ("there is no 10 in list")

 

reverse()  ---列表反转

 

l = [1, 2, 3]

l.reverse()print (l) #[3, 2, 1]sort(cmp=None, key=None, reverse=False)  ---列表排序

 

l5 = [10, 5, 20, 1, 30]

l5.sort()

print( l5) #[1, 5, 10, 20, 30]l6 = ["bcd", "abc", "cde", "bbb"]

l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1]))

print( l6) #['abc', 'bbb', 'bcd', 'cde']l7 = ["bcd", "abc", "cde", "bbb", "faf"]

l7.sort(key = lambda s: s[1])print (l7) #['faf', 'abc', 'bbb', 'bcd', 'cde']复制代码

This article comes from the php Chinese website python video tutorial column: https://www.php.cn/course/list/30.html

Guess you like

Origin blog.csdn.net/Anna_xuan/article/details/109648039