Python learning notes (1) Basics and python learning notes Basics
Python Basics
Python uses indentation to organize code blocks. Follow the conventions and stick to the indentation with four spaces.
In the text editor, you need to set the Tab to automatically convert to four spaces to ensure that Tab and space are not mixed.
Integer
Floating Point Number
Integers and floating-point numbers are stored in different computers. Integer operations are always accurate (Division is also), while floating-point numbers may have rounding errors.
String
A string is any text enclosed by single quotation marks or double quotation marks. If 'is also a character, you can use "" To enclose it, for example, "I'm OK ".
If the string contains both 'and', you can use the Escape Character \ to identify it:
'I\'m \"OK\"!'
The content of the string is I'm "OK "!
Escape characters can be escaped by many characters. For example, \ n indicates line feed, \ t indicates a tab, and the character \ itself must also be escaped. Therefore, \ indicates the character \.
If many characters in the string need to be escaped, you need to add a lot of \. To simplify the process, Python also allows the use of r'' to indicate that the character strings inside ''are not escaped by default.
>>> print('\\\t\\')\ \>>> print(r'\\\t\\')\\\t\\
If a string contains many line breaks, \ n is not easy to read in a row. to simplify it, Python allows multiple lines of content to be expressed in the format.
>>> print('''line1... line2... line3''')line1line2line3
If the written program coexist as A. py file, it is:
print('''line1line2line3''')
The multi-line string '''... ''' can also be added to the front with r, that is, the multi-line string is not escaped.
A boolean value can only be True or False. You can use and (&), or (|), or not to calculate a Boolean value.
>>> TrueTrue>>> FalseFalse>>> 3 > 2True>>> 3 > 5False
>>> True and TrueTrue>>> True and FalseFalse>>> False and FalseFalse>>> 5 > 3 and 3 > 1True
>>> True or TrueTrue>>> True or FalseTrue>>> False or FalseFalse>>> 5 > 3 or 1 > 3True
>>> not TrueFalse>>> not FalseTrue>>> not 1 > 2True
Null Value
The Null Value of Python is expressed as None.
Variable
In Python, = is a value assignment statement, which can assign any data type to a variable. The same variable can be assigned multiple times and can be of different types, for example:
A = 123 # a is an integer print (a) a = 'abc' # a is a string print ()
The variable itself is not a fixed type of language called dynamic language, that is, the scalar type does not need to be declared.
Understand the representation of variables in computer memory:
A = 'abc'
The Python interpreter does two things:
1. A 'abc' string is created in the memory;
2. Create a variable named a in the memory and point it to 'abc '.
You can also assign variable a to variable B:
a='ABC'b=aa='XYZ'print(b)
The result 'abc' is displayed '.
Constant
There are two types of division in Python, one of which is /:
>>>10/33.3333333333333335
/The Division calculation result is a floating point number. Even if the two integers are divisible, the result is also a floating point number:
>>>9/33.0
Another division is //, called floor Division. The Division of two integers is still an integer:
>>>10/33
// Division only takes the integer part of the result, which is equivalent to the C language/division.
Python provides the remainder operation: (%)
>>>10%31
Therefore, whether it is // or %, the result is always an integer, that is, the Integer Operation described above is always accurate.
Note: Python integers are not limited in size. There is no size limit for floating point numbers, but beyond a certain range, it is directly expressed as inf (infinitely large ).
Character encoding
UTF-8 encoding encodes a Unicode (usually 2 bytes) character into 1-6 bytes according to different numbers, commonly used English characters are encoded into 1 byte, Chinese characters are usually 3 bytes, only uncommon characters are encoded into 4-6 bytes. If the text to be transmitted contains a large number of English characters, using UTF-8 encoding can save space:
| Character |
ASCII |
Unicode |
UTF-8 |
| A |
01000001 |
00000000 01000001 |
01000001 |
| Medium |
X |
01001110 00101101 |
11100100 10111000 10101101 |
In computer memory, Unicode encoding is used in a unified manner, when you need to save to the hard disk or need to transfer, it is converted to UTF-8 encoding.
That is, when you edit text, UTF-8 characters are converted to Unicode characters to memory, after editing is complete, save or transfer, Unicode is then converted to UTF-8 for saving or transferring.
Python string
For the encoding of a single character, Python provides the ord () function to convert the character to the number of characters encoded. the chr () function converts the encoding to the corresponding character:
>>> Ord ('A') 65 >>> ord ('中') 20013 >>> chr (66) 'B' >>> chr (25991) 'wen'Because the string type of Python is str, It is represented in Unicode in memory. A character corresponds to several bytes. If you want to transmit data over the network or save the data to a disk, you need to change str to bytes in bytes.
Python uses single quotation marks or double quotation marks with a B prefix for bytes data:
X = B 'ABC'
Note that 'abc' and 'abc' are distinguished. The former is str and Unicode encoding. Although the content of the latter is consistent, each character occupies only one byte.
Str represented by Unicode can be encoded as the specified bytes through the encode () method, for example: (''. encode (''))
>>> 'Abc '. encode ('ascii ') B' abc'> 'Chinese '. encode ('utf-8') B '\ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87' >>> 'Chinese '. encode ('ascii ') >>> x = 'abc' >>> x. encode ('utf-8') B 'abc'Note: str with Chinese characters cannot be ASCII encoded.
If we read byte streams from the network or disk, the data we read is bytes. To change bytes to str, you need to use the decode () method: (''. decode (''))
>>> B 'abc '. decode ('ascii ') 'abc'> B' \ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87 '. decode ('utf-8') 'Chinese'
Len () function
To calculate the number of characters in str, you can use the len () function:
>>> Len ('abc') 3 >>> len ('Chinese') 2The len () function calculates the str Character Count. If it is changed to bytes, the len () function calculates the number of bytes:
>>> Len (B 'abc') 3 >>> len (B' \ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87 ') 6 >>> len ('Chinese '. encode ('utf-8') 6
In the operation of the string, often encounter str and bytes mutual conversion, in order to avoid garbled problem, should always adhere to the use of UTF-8 encoding str and bytes conversion.
Since Python source code is also a text file, when the source code contains Chinese characters, when saving the source code, you need to specify to save as UTF-8 encoding. When the Python interpreter reads the source code, we usually write these two lines at the beginning of the file to make it read by UTF-8:
#! /Usr/bin/env python3
#-*-Coding: UTF-8 -*-
(If the source code contains Chinese characters:
1. Make sure that the text editor uses the UTF-8 without BOM;
2. Write two lines of comments at the beginning of the source code .)
Format
In Python, the format is the same as that in C, and % is used. For example:
>>> 'Hello, %s' % 'world''Hello, world'>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)'Hi, Michael, you have $1000000.'How many %? Placeholders, which are followed by several variables or values in one-to-one order. If there is only one % ?, Parentheses can be omitted.
Common placeholders:
| % D |
Integer |
| % F |
Floating Point Number |
| % S |
String |
| % X |
Hexadecimal integer |
To Format integers and floating-point numbers, you can also specify whether to fill in the digits of 0 and integer and decimal places:
>>> print('%2d-%02d' % (3, 1))3-01>>> print('%.2f' % 3.1415926)3.14If you are not sure what to use, % s will always work, and it will convert any type to a string:
>>> 'Age: %s. Gender: %s' % (25, True)'Age: 25. Gender: True'
When % in the string is a common character, this is represented by % escape:
>>> 'growth rate: %d %%' % 7'growth rate: 7 %'
List and tuplelist
A built-in data type in Python is list: list. List is an ordered set that allows you to add and delete elements at any time. (List = [,])
>>> classmates = ['Michael', 'Bob', 'Tracy']>>> classmates['Michael', 'Bob', 'Tracy']
The variable classmates is a list.
You can use the len () function to obtain the number of list elements:
>>> len(classmates)3
Use indexes to access the elements at each position in the list. Remember that the index starts from 0:
>>> classmates[0]'Michael'>>> classmates[1]'Bob'>>> classmates[2]'Tracy'>>> classmates[3]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
Note: Make sure that the index does not cross-border.
If you want to take the last element out of the index location, you can also use-1 for indexing to directly obtain the last element:
>>> classmates[-1]'Tracy'
And so on, you can get the second and third:
>>> classmates[-2]'Bob'>>> classmates[-3]'Michael'>>> classmates[-4]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
You cannot cross the border.
List Function
In addition to the number of list elements obtained by the len () function, the following functions are available:
. Append () can append elements to the end of the list:
>>> classmates.append('Adam')>>> classmates['Michael', 'Bob', 'Tracy', 'Adam']. Insert (n,) inserts an element into the specified nth position:
>>> classmates.insert(1, 'Jack')>>> classmates['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
. Pop () deletes the elements at the end of the list:
>>> classmates.pop()'Adam'>>> classmates['Michael', 'Jack', 'Bob', 'Tracy']
. Pop (I:
>>> classmates.pop(1)'Jack'>>> classmates['Michael', 'Bob', 'Tracy']
If you replace an element with another element, you can assign it to the index position of your teammates:
>>> classmates[1] = 'Sarah'>>> classmates['Michael', 'Sarah', 'Tracy']
The Data Types of elements in the list can also be different:
>>> L = ['Apple', 123, True]
The list element can also be another list:
>>> s = ['python', 'java', ['asp', 'php'], 'scheme']>>> len(s)4
Note that s has only four elements, and s [2] is a list.
To get 'php', you can write s [2] [1], so s can be regarded as a two-dimensional array. There are also three-dimensional, four-dimensional, and so on ......
If one element in the list does not exist, it is an empty list with a length of 0.
Tuple
Another ordered list is tuple. (Tuple = (,,)). Once initialized, tuple cannot be modified:
>>> classmates = ('Michael', 'Bob', 'Tracy')Now, the tuple of classmates cannot be changed, and there is no such method as append () and insert. Other methods for retrieving elements are the same as those for listing. classmates [0] and classmates [-1] can be used normally, but cannot be copied to another element. Because tuple is immutable, the code is immutable.
Tuple trap: when defining a tuple, tuple must be determined, for example:
>>> t = (1, 2)>>> t(1, 2)
To define an empty tuple, you can write it ():
>>> t = ()>>> t()
However, when defining a tuple with only one element, you must add a comma (,) to eliminate ambiguity (because when t = (1), the number of tuple is not defined, but 1):
>>> t = (1,)>>> t(1,)
When Python displays a tuple with only one element, it also adds a comma.
"Variable" tuple:
When tuple is a list-type element, the elements in the list can be changed:
>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t[2][1] = 'Y'>>> t('a', 'b', ['X', 'Y'])This is because the elements in the list are changed, and the list pointed to by tuple is not changed to other lists. The so-called "unchanged" means that every element of the tuple is always pointed. That is, if you point to 'A', you cannot change it to 'B'. If you point to a list, you cannot change it to another object. However, the list you point to can be changed. (The list can be changed, but the list to be pointed to cannot be changed)
Condition judgment
Basic statement:
If condition: execution statement elif condition: execution statement else: execution statement
Elif is short for else if. Do not write less colons. For example:
age = 20if age >= 6: print('teenager')elif age >= 18: print('adult')else: print('kid')
Input ()
There are the following programs:
Birth = input ('birth: ') if birth <2000: print (before '00') else: print (after '00 ')Enter 1982 and an error is returned.
This is because the data type returned by input () is str. str cannot be directly compared with an integer. str must be converted to an integer first. The int () function completes this task:
S = input ('birth: ') birth = int (s) if birth <2000: print (before '00') else: print (after '00 ')Run the command again to obtain the correct result. However, if abc is input, an error is returned because the int () function finds that a string is not a valid number.
Similarly, float () converts integers and strings to floating-point numbers.
Loop
Python has two types of loops: for... in, which iterations each element in list or tuple in sequence:
names = ['Michael', 'Bob', 'Tracy']for name in names: print(name)
The range (n) function can generate an integer sequence, and then generate a list through the list function. The integer range is 0 ~ N-1.
>>> list(range(5))[0, 1, 2, 3, 4]
Range can be used to calculate 1 ~ Sum of 100:
sum = 0for x in range(101): sum = sum + xprint(sum)
Range can also specify the starting value:
>>>for num in range(2,6): print(num)2345
In addition, you can specify the step in range, and indicate the step in the third value:
>>>for num in range(2,10,2) print(num)2468
In 2 ~ Add 2 at a time in the range of 9.
The second type of loop is the while loop. If the condition is met, the loop will continue and exit when the condition is not met.
sum = 0n = 99while n > 0: sum = sum + n n = n - 2print(sum)
Dict and setdict
Dict is a dictionary in python. It stores keys and corresponding values for easy search.
Initialize dict:
>>>d={'a':95,'b':85,'c':5}>>>d['a']95
You can also directly add:
>>>d['d']=75>>>d['d']75
You can directly modify the value corresponding to the key:
>>>d['a']=55>>>d['a']55
If the key does not exist, the program reports an error. To ensure that the key does not exist, there are two methods:
The first is through in:
>>>'e' in dFalse
The second type is the get () function. If the key does not exist, None is returned, or the specified value is:
>>>d.get('e')>>>d.get('e',0)0To delete a key, you can use pop (key) and the corresponding value will also be deleted:
>>>d.pop('a')95>>>d{'b':85,'c':5,'d'75}Note: The key of dict must be immutable. in Python, strings and numbers are immutable, while lists are variable. Therefore, list cannot be the key of dict:
>>> key = [1, 2, 3]>>> d[key] = 'a list'Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'
Set
Set and dict store a set of keys, but they do not store values. Therefore, the key values in the set must be unique.
To create a set, you must provide a list as the input set:
>>> s = set([1, 2, 3])>>> s{1, 2, 3}Note that the input [, 3] is a list, and the displayed {, 3} indicates that the set contains the three elements 1, 2, 3.
Repeated elements are automatically filtered in the set:
>>> s = set([1, 1, 2, 2, 3, 3])>>> s{1, 2, 3}You can use add (key) to add elements to the set:
>>> s.add(4)>>> s{1, 2, 3, 4}>>> s.add(4)>>> s{1, 2, 3, 4}Use remove (key) to remove elements:
>>> s.remove(4)>>> s{1, 2, 3}
Set can be regarded as a set of unordered and non-repeating elements in mathematics, so operations such as intersection and union can be used (&, |)
>>> s1 = set([1, 2, 3])>>> s2 = set([2, 3, 4])>>> s1 & s2{2, 3}>>> s1 | s2{1, 2, 3, 4}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.