Python basics-week02, python-week02
Summary of this section:0. xmind8 cracking and Installation(If you want to crack the version and materials, please leave a message below. I will not describe it here)1. Initial Knowledge of the module2. What is pyc?3. python Data Type(Bytes data type, data operator, and Collection)4. Use 1-2 for the list
5. tuples: Shopping Cart program exercises and Examples
6. common string operations
7. Exercise for dictionary usage: Three-Level menu instance
8. Job: Shopping Cart Optimization
I. Initial Knowledge of the module
Import The Py built-in modules, such as OS and sys, and their own Py files. import them to other files. The current directory is searched by default. If the file is not in the same directory, an error will be reported. Put the custom py file module in the site-packages directory. Other methods will be explained in the following notes.
Python is powerful because it has a rich and powerful standard library and third-party library. Almost any function you want to implement has the corresponding Python library support, in future courses, we will explain in depth the various frequently-used libraries. Now, let's start with a symbolic study of two simple ones.
Sys:
Import sys
Print (sys. argv)
OS:
Import OS
OS. system ("df-h") # Call system commands
Import OS sys
OS. system (''. join (sys. argv [1:]) # Use your input parameters as a command and hand it to OS. system for execution.
Ii. What is pyc?
Before talking about this, let's talk about two concepts: PyCodeObject and pyc files.
The pyc we see on the hard disk naturally does not need to say much, but in fact, PyCodeObject is actually compiled by the Python compiler. We can simply know it and continue to look down.
When the python program runs, the compilation result is saved in the PyCodeObject in the memory. When the Python program runs, the Python interpreter writes the PyCodeObject back to the pyc file.
When the python program runs for the second time, the program first looks for the pyc file in the hard disk. if it finds the file, it loads it directly; otherwise, the above process will be repeated.
Therefore, we should locate the PyCodeObject and pyc files in this way. We say that the pyc file is actually a persistent storage method of PyCodeObject.
Summary: pyc is actually a pre-compiled Python file. Every time you run the py file, it will check whether the pyc file exists. If it does not exist, re-compile the file, if the source file and pyc file are updated at the latest time, if the source file is not updated, the execution speed is fast directly from the Pyc file. If the source file has been updated, the latest source file will be compiled to generate the Pyc file.
Iii. python Data Types
1. numeric type
INTEGER (int): On 32-bit machines, the number of digits of an integer is 32 bits, and the value range is-2 ** 31 ~ 2 ** 31-1, I .e.-2147483648 ~ 2147483647
In a 64-bit system, the number of digits of an integer is 64-bit, and the value range is-2 ** 63 ~ 2 ** 63-1, that is,-9223372036854775808 ~ 9223372036854775807
Floating Point Type(Float): A floating point number is used to process a real number, that is, a number with a decimal number. Similar to the double type in C, it occupies 8 bytes (64-bit), where 52 bits represent the bottom, 11 bits represent the index, and the remaining one represent the symbol.
Example of floating point number: 3.14 and 52.3E-4. E indicates the power of 10, which is the abbreviation of 52.3*10 **-4.
Plural(Complex): for example, 3 + 4j consists of real numbers and virtual numbers. to traverse the complex numbers, you need to traverse the real numbers and virtual numbers separately.
2. String
The string in python is embodied in the C language as a character array. Each time you create a string, you need to open up a continuous empty block in the memory. Once you need to modify the string, you need to open up space again, every time the "+" icon appears, it will open up a new space.
String formatting output
Name = "alex" print "I am % s" % name # output: I am alex
PS: string is % s; integer % d; floating point % f
Common functions of strings:
Remove blank: strip () goes to the beginning and end, lstrip () goes to the left, rstrip () goes to the right
Split: split (',')
Length: len ()
Index: zifucuan [I]
Slice: zifucuan []
Replace ('c1 ', 'c2'): replace c1 in the string with c2. Therefore, replace ('','') can be used to remove all spaces in the string.
3. List
Creation list:
Name_list = ['Alex ', 'seven', 'Eric'] Or name_list = list (['Alex ', 'seven', 'Eric'])
Basic operations:
Index: Starting from 0, list [-1] is the last non-empty list
Slice: list []
Append: list. append ()
Delete: list. pop ()/list. remove ()/del list
Length: len ()
Loop: for I in list:
Including: (tuples)
4. Ancestor (immutable List)
Common Operations: Same as list operations.
Ages = (11, 22, 33, 44, 55) or ages = tuple (11, 22, 33, 44, 55 ))
5. Dictionary
Create a dictionary:
Person = {"name": "mr. wu ", 'age': 18} or person = dict ({" name ":" mr. wu ", 'age': 18 })
Common Operations:
Index
New
Delete
Key, value, and key-Value Pair
Loop
Length
6. boolean type
True/False
7. None
***************Data operators and their priorities:
* ********* Collection:
1. Ternary operation
Format: retsult = value 1 if condition else value 2
If the condition is true, the output result = value 1
The condition is false, and the output result = value 2
Example: a, B, c = 1, 3.5
D = a if a> B else c
Output d = 5
D = a if a <B else c
Output d = 1
2. hexadecimal
A. Binary 01
B. Gossip 01234567
C. Decimal 0123456789
D. hexadecimal 0123456789 ABCDEF,Prefix notation BH, suffix notation 0x53
Learn how to convert binary data into hexadecimal data!
3. Object
Have you found the object?
Everything in python is an objectDon't tell others that you have no object in the future,Create object based on classSuch as pure category, mature category, cute girl category, charm category, intellectual category ......
************ ***** Bytes data type:
(1)One of the most important new features of Python 3 is the explicit distinction between strings and binary data streams. Text alwaysUnicode,strType, binary data is representedbytesType. Python 3 is not implicitly mixed.strAndbytesYou cannot concatenate strings or throttling characters, search for strings in byte streams (or vice versa), or input strings into byte streams (or vice versa ).
(2) differences between bytes and str:
BackbytesAndstr.bytesIt is a bit stream, which exists in the form of 01010001110. No one will read this bit stream directly in the process of writing code or reading the article. It must have an encoding method to make it a meaningful bit stream, instead of a bunch of obscure 01 combinations. Because of the different encoding methods, the interpretation of this bit stream will also be different, causing a lot of trouble for actual use. Let's take a look at how Python handles this series of coding problems:
>>> S = "Chinese"
>>> S 'Chinese'
>>> Type (s) <class 'str'>
>>> B = bytes (s, encoding = 'utf-8 ')
>>> B B '\ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87'
>>> Type (B) <class 'bytes '>
(3). For example, the conversion between bytes and str:We all know that string classesstrThere isencode()Method, it isEncoding of a stream from a string to a bitProcess. WhilebytesThere is exactly one typedecode()Method, it isDecodes data from bits to strings. In addition, we can view the Python source code and findbytesAndstrHas an almost identical list of methods,The biggest difference is thatencodeAnddecode.
In essence, the storage format of strings on the disk is also a combination of 01 and also requires encoding and decoding.
If the above explanation does not allow you to clarify the differences between the two, remember the following two sentences:
In the process of mutual conversion between bytes and str, it is actually the process of encoding and decoding, And the encoding format must be explicitly specified.
# Author Jame-Mei
Msg1 = 'I Love China'
Print (msg1)
Print ("\ n converts str to bytes encoding :")
Print (msg1.encode (Encoding = 'utf-8'))
# The default value of python3 is UTF-8. If python2.x does not exist, an error is returned !!
Print ('\ n converts bytes to str :')
Print (B '\ xe6 \ x88 \ x91 \ xe7 \ x88 \ xb1 \ xe4 \ xb8 \ xad \ xe5 \ x9b \ xbd'. decode (Encoding = 'utf-8'))
(4) Why should bytes and str be converted to each other?
It involves python network programming and converts the str string type to the bytes type for communication and transmission.