Python study notes (3) Python basics

(2) Python foundation

python basics

  1. Natural language is different from programming language. Natural language can have different meanings or interpretations in different situations, but this is absolutely forbidden by programming languages.
  2. The performance requirements that programming languages ​​should have are: consistency, unambiguousness, simplicity, locality, and linearity.
  3. The python language is no exception.
  4. The syntax of python is relatively simple and indented. Such as:

    a=100;
    if a>=0:
        print(a)
    else:
        print(-a)
    1. 以#开头的是注释
    2. 每一行都是一个语句
    2. 当语句以:结尾时 , 缩进的语句视为一整个代码块(缩进有利有弊 
        1.  好处是强迫你写出格式化美观的代码 , 但是在python中并没有规定缩进是几个空格还是tab , 一般约定俗成坚持使用四个空格的缩进 。
        2.  强迫你缩进更少的代码 , 这样你回吧倾向于更长的代码拆分为若干个函数 ,提高代码复用性
        3.  坏处就是 , 当你粘贴代码的时候必须要重新检查缩进是否正确 , 此时IDE也很难像格式化java代码一样格式化Python代码 )
    4.  Python程序时大小写敏感的语言
    

First, data types and variables, constants

  1. Basic data types:
    1. Integer:
      1. In python, you can process integers of any size, including negative numbers, and the representation in the python language is exactly the same as the mathematical way of writing
    2. floating point number
      1. Floating-point numbers are decimals. The reason why they are called floating-point numbers is that when using scientific notation to represent a decimal, the position of the decimal point is not fixed, but floating. In Python, large or small floating-point numbers are best represented by scientific notation. .
      2. Integers and floating-point numbers are stored differently in computers. Integers are always stored exactly in a computer, while floating-point numbers are only rarely stored exactly.
    3. string
      1. A string is any text enclosed in single or double quotes
    4. Boolean value
      1. A boolean value has only two values, True and False. In python, you can directly use True and False to represent the boolean value (note the capitalization), or you can calculate it through Boolean operations.
      2. Boolean values ​​can also be operated with and , not , or
    5. null
      1. A null value is a special value in Python, represented by None, Nono cannot be understood as 0, because 0 is meaningful, and None is a special null value.
  2. variable:
    1. Variable names can only consist of letters, numbers, and underscores, and cannot start with numbers
    2. In Python = is a copy statement, which can copy any data type to a variable, the same variable can be copied repeatedly, and it can make variables of different types. (The language in which the variable type itself is uncertain is called a dynamic language)
    3. When executing a='abc', the Python interpreter does two things:
      1. created a string of 'abc' in memory
      2. Created a variable named a in memory and pointed it to 'abc'
  3. constant:
    1. Constants are variables that cannot be changed. Generally speaking, constants are all represented by uppercase variable names. For example, the mathematical constant π is represented by PI in Python.
    2. But in fact the constant is still a variable, Python has no mechanism at all to guarantee that PI will not be changed

2. Strings and Encodings

  1. code slightly
  2. string

    1. For the encoding of a single character, Python provides the ord() function to obtain the integer representation of the character, and the chr() function to convert the encoding to the corresponding character
    2. Python's string type is str, which is represented by Unicode in memory. One character corresponds to several bytes. If you want to transmit it on the network or save it on disk, you need to save str as bytes in bytes. .
    3. Data of type bytes in python is represented by single or double quotes with the b prefix

      x=b'abc'
      
    4. Pay attention to the data of bytes type and str type. Although b'abc' and 'abc' have the same content, the data of bytes only occupies one byte per character. :
    5. encode() : You can use the encode() method to convert the string of type str to the specified encoding. An error will be reported when the specified encoding cannot represent the corresponding character.
    6. decode() : When python code reads data from disk, it reads a byte stream. If you want to get Chinese data, you need to use decode() to decode the byte stream. When you need to ignore the wrong bytes in the byte stream, you can add the parameter errors='ignore'
    7. len(str): See how many characters the string contains. Note that it is not bytes but characters
    8. len(bytes): Get the number of bytes in the string
    9. If you need to convert between Chinese and bytes during development, you should stick to utf-8. The py source code itself is also a text file. When the source code is packaged in Chinese, the python source code should be encoded as utf-8 (default under windows). gbk, the default utf-8 under linux). In order for the interpreter to interpret correctly when the python source code is executed, # - - coding:utf-8 - - should be added at the beginning of the file to tell the interpreter to use utf-8 encoding when interpreting the code.
    10. Formatting string: How to output a string like "Dear xxx, your xx monthly bill is xxxx!" The content of xxx changes according to variables, so python provides a convenient way to format characters. Place a placeholder where a variable is required, and automatically call the corresponding content in the parameter when there is a parameter. Common placeholders:

      Placeholder replace content
      %d integer
      %f floating point number
      %s string
      %x hexadecimal number

      Formatting integers and floating-point expressions can also specify whether to add 0 and the number of integers and decimals

    11. When the string contains %, the % needs to be escaped, use %% to represent %.
    12. format() : Another method of formatting strings, which will replace the placeholders in the string with the incoming string in turn

3. List and tuple

  1. list: The list list is a built-in data type of python. A list is an ordered collection from which elements can be added and removed at any time.

    1. Elements in a list can be accessed by index. When the index is a positive integer, the index starts from 0. When the index is a negative integer, the index starts at -1. When the index exceeds the length of the list, an error will be reported that the index is out of bounds.
    2. list is a mutable ordered list
      1. add element to the end
      2. add element to specified position
      3. Get and remove the last element
      4. Get and delete the element at the specified position
    3. The data types of the elements in the list can be different
  2. tuple: Another type of sequence list is called a tuple. A tuple is very similar to a list. But tuple cannot be modified once initialized. Only the elements in it can be retrieved and cannot be deleted or modified.

    1. Because tuples are immutable, the code is more secure, try to use tuples when you can. But tuple is immutable, so when defining tuple, all elements in it should be determined
    2. A list is represented by [], and a tuple is represented by (). Even if there is only one element in the tuple, a comma must be added to avoid confusion with () during calculation.

4. Conditional judgment

  1. The reason why it can do many automated tasks is because it can automatically make conditional judgments based on the situation.
  2. According to python's indentation rules, the same continuous indentation is regarded as the same code block.

    # -*- coding:utf-8 -*-
    # 使用input获取到的内容都为Str类型  需要转换后才能使用运算符运算  
    age =int(input("请输入你的年龄:"))
    if age>18 :
        print("你是成年人!")
    elif age>15 :
        print("你是青少年!") 
    else:    
        print("你是儿童!")
    
    input("输入任意字符退出!")
    
  3. In python, the if judgment of Tianjian can also be abbreviated to directly judge and automatically infer the data type, and then automatically judge whether the integer or floating-point number is 0, whether the string is empty, and whether the list is empty. The result of the operation is True if it is, False otherwise.

5. Cycle

  1. Two kinds of loops are provided in python: for-in and while loops.

  2. for loop:

    #  -*- conding : utf-8 -*-  
    #python中循环
    
    #循环输出名字
    names = ['韩梅梅' , '李雷雷' , '小明明']
    for name in names :
        print(name)
    
    
    #循环输出有序数字
    list = [1,2,3,4,5,6,7,8,9]
    for l in list :
        print(l)    
    
    # 但是如果想要输出1~10000的有序数字 , 难道需要提前定义1~10000的list么
    
    list2=range(10001) # range()函数用于生成0到指定数字的有序list
    for l in list2:
        print(l)     
    
  3. while loop:

    #while 循环
    # 求0到100的和
    
    sum = 0
    n = 100
    while n>0 :
        sum =sum +n
        n = n - 1 
    print("0到100的整数和为:" ,sum)
    
  4. break 与 continue
    1. In the loop, you can use break to end the loop in advance, and generally need to be used with if.
    2. In the loop, you can use continue to end the current cycle, and then continue to the next cycle.

Six, dict and set

  1. dict: Python has built-in dict support, dict is a full dictionary, also called map in other languages, uses key-value pair storage, and has extremely fast search speed. (Reason: dict has its own index table, which will not cause the query speed to slow down as the number of elements increases)
    1. A key in the dict can only correspond to one value. If the key is the same, the later value will overwrite the previous value.
    2. When modifying the value, if the value does not exist, an error will be reported. In order to avoid the error that the key does not exist, you can judge whether the key exists in the dict through in in advance. You can also use the get() function to determine whether the key exists. If it does not exist, it will return none or return the default value made by yourself. (If the result is None when testing in the interactive environment of python, nothing will be displayed.)
    3. Comparing dict and list:
      1. A dict can store data in key-value pair format.
      2. The query speed of dict is very fast and will not slow down as the number of elements increases
      3. The memory space occupied by dict is large and the memory is wasted.
      4. dict summary: dict can be used in places that require a lot of calcium queries. It is almost ubiquitous in python code. It should be noted that the key of the element in the dict must be an immutable object. This is because dict needs to calculate the storage location of the value according to the key. If the location of each calculation is different, it will be completely confusing. Strings and integers are immutable in python, so they can be safely used as keys.
  2. set: The format of the elements stored in the set is similar to that of the list, but the position of the stored elements and the order of storage are irrelevant, and the elements stored in the set cannot be repeated.

    1. add() : Add elements to the set via the add() function.
    2. remove() : Remove the element from the set with the remove() function.
    3. In the concept of mathematics, a set is a collection of unordered and non-repeating elements, so the intersection and union operations can be performed on the set.

    4. Set summary: The only difference between set and dict is that the elements stored in dict are in the form of key-value pairs, while set only stores keys. The keys in set and dict are not repeatable, and the storage order is relative to the storage order. It is unordered, and the principle of set and dict is the same. Also, variable elements cannot be stored, because it is impossible to judge whether two elements are equal, and there is no guarantee that there will be no duplicate elements in the set. (str and integer are immutable elements in python)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324493647&siteId=291194637