How to learn Python for the first time? What knowledge do you need to learn to get started with Python?

picture.png
Python basic data types

Integers: 1, -1, 0, and hexadecimal integers: 0xff00, 0xa5b4.
Floating point numbers: 1.23, 3.13, -0.12.
String: A string is any text wrapped with "or". If the string itself has 'or", then "\" needs to be escaped.
Boolean values: Only True and False. Boolean values ​​can be operated through and (AND operation), or (OR operation), and not (not operation).
Null value: It is represented by None and cannot be understood as 0, because None is a special null value.
Python print statement

When the print statement prints a string, it will output a space when it encounters a comma ",".
print 'god is a','girl.'#Print statement
god is a girl.#Run result

print can also print integers or calculation results.
Python annotations

Python comments start with #, and then the entire line is considered a comment.
Python variables

The name of the variable: must be a combination of uppercase and lowercase English, numbers and underscores (_), and cannot start with a number.
-In Python, the type of the variable itself is not fixed. It is called a dynamic language. Any data type can be assigned to a variable. The same variable can be assigned repeatedly, and it can be a variable of different types.
Raw strings and multi-line strings in Python

If a string contains many characters that need to be escaped, escaping each character can be cumbersome. In order to avoid this situation, we can add a prefix r in front of the string, indicating that this is a raw string, and the characters inside do not need to be escaped.
If the package represents a multi-line string, it can be represented by "'…………"'.
If multiple lines require escaped strings, you can use r"'..."' to represent them.
Unicode strings in Python

Because Python was born earlier than the release of the Unicode standard, Python supports ASCII encoding by default. If you want to use Chinese, you need to make Python support the Unicode encoding format:

转义,加u。

u'Chinese\nJapanese\nKorean'

Multi-line.
u'''First line
Second line'''

raw+multiple lines.
ur'''…


…’’

If a Chinese string encounters UnicodeDecodeError in the Python environment, it is because there is a problem with the format in which the .py file is saved. Comments can be added to the first line.

-- coding: utf-8 --

Boolean types in Python

Python treats 0, "empty string" and None as False, and other values ​​and non-empty strings as True.
Short-circuit calculation
① When calculating a and b, if a is False, according to the AND operation rule, the entire result must be is False, so a is returned; if a is True, the entire calculation result must depend on b, so b is returned. ②
When calculating a or b, if a is True, then according to the OR algorithm, the entire calculation result must be True , so a is returned; if a is False, the entire calculation result must depend on b, so b is returned. For novices who want to learn the basics of Python more easily, Python crawlers, web development, big data, data analysis, artificial intelligence, etc. Technology, here we give you system teaching resources, contact me Wei X: 762459510 [python tutorial/tool/method/question solving]

If a and b in a and b are both strings or integers, the corresponding type will be returned instead of True or False.
List in Python

A List is an ordered collection in which elements can be added and removed at any time.
To construct a List, you only need to enclose all elements with [ ] to create a List object. Usually, the List is assigned to a variable, so that the List can be referenced through the variable.
The elements contained in the List are not required to be of the same data type and can contain various data.
A List without an element is an empty List, represented by [].
The index of List starts from 0, that is, the first element of List is: L[0]. When using indexes, be careful not to cross boundaries.
The reverse index of List uses L[-1] to represent the first to last element, and then L[-2] to represent the second to last element.
There are two methods for adding new elements to List:
①Append() method, add new elements to the end of List, L.append('Paul').
②insert() method. This method has two parameters. The first parameter is the index number, and the second parameter is the new element to be added, L.insert(0,'Paul').

Method to delete elements from List: pop() method, L.pop() will delete the last element of List, and L.pop(2) will delete the element with index number 2 in List.
You can use the index number to replace elements in List and assign the value directly to complete the replacement work, L[1]='Paul'.
Slice the List: L[x:y:z], x represents the index number, y represents the index cutoff number, and z represents every fewth one.
L[0:3] # means taking the first three elements, that is, taking out the first, second, and third elements. The result is still a list.
L[:3] #Represents taking the first three elements.
L[:] # means taking out all elements, which actually copies a new list.
L[::2] #This means taking out one element for every two elements.

List slicing also supports reverse slicing of
tuples in Python.

Tuple is another ordered list. The difference from List is that once Tuple is created, it cannot be modified.
A tuple is constructed by enclosing all elements with ().
Tuple does not have append(), insert(), or pop() methods, and the original elements cannot be replaced.
A tuple can contain 0, 1, or any number of elements. Empty tuples are directly represented by ().
Because () can both represent a tuple and can also be used as parentheses to represent the priority of an operation, we need to add an extra comma "," when defining a single-element tuple to avoid ambiguity: t = (1,).
Variable tuple in python, t = ('a','b',['A','B']), can be passed L = t[2],L[0]='X' L[1] = 'Y' to replace the List inside the tuple, but the tuple has not changed.
Tuple slicing is the same as list, but replaced by tuple.
(At the bottom of my article, there is a complete set of zero-based information on Python, which is very suitable for beginners to learn Python. If you are confused about how to learn Python for the first time, you may wish to take a look. It is an electronic version and is free) Conditional judgment and looping in
Python

Indentation rules for Python code:Code with the same indentation is considered a code block.
The indentation rule of Python is 4 spaces. Do not use Tab, and do not mix Tab and spaces, otherwise it is easy to cause syntax errors due to indentation. To exit the indentation, you need to press Enter one more line.
if-else: When if is true, execute the code block contained in if. After else, the code block after else: will be executed.
if-elif-else: When an if-else is not enough, if-elif-... -else to use
for loop: pay attention to the writing, the loop code block will be executed first, and then exit the loop after execution
L=['Adam', 'Lisa', 'Bart']
for name in L:
print name

while loop: Pay attention to the writing. The loop code block will be executed first, and then exit the loop
N = 10
x = 0
while x<N:
print x
x = x + 1

In a for loop or while loop, if you want to exit the loop directly within the loop body, you can use the break statement.
During the loop, you can use break to exit the current loop, or you can use continue to skip and continue the loop code to continue the next loop.
Multiple loops: Inside loops, nested loops.
dict in Python

dict is similar to Map in Java, an unordered collection.
The composition is enclosed by {'adam':95,'lisa':80}, and the comma in the last key:value can be omitted.
The len() method is used to calculate the size of any collection.
To find value, you can use the form of d[key] to find the corresponding value.
You can use the in operator to determine whether the key exists.
Dict also provides a get method. Get(key) gets the value. When the key does not exist, None is returned.
The first feature of dict is its fast search speed. Whether the dict has 10 elements or 100,000 elements, the search speed is the same. The search speed of the list gradually decreases as the number of elements increases. However, the fast search speed of dict does not come without a price. The disadvantage of dict is that it takes up a lot of memory and wastes a lot of content. List is just the opposite, taking up little memory but the search speed is slow. Since dict is searched by key, keys cannot be repeated in a dict.
The second characteristic of dict is that the stored key-value pairs are in no order.
The third characteristic of dict is that the elements used as keys must be immutable. Python's basic types such as strings, integers, and floating point numbers are all immutable and can be used as keys. But the list is variable and cannot be used as a key.
Dict update: Use an assignment statement to add it, d['paul'] = 72. If 'paul' already exists, the assignment statement will replace the original value with the new value. If it does not exist, it will be added.
You can traverse the dict through a for loop to get all the keys, and then get the value based on the key.
set in Python

Set is similar to set in java, an unordered and non-repeating collection.
The way to create a set is to call set() and pass in a list. The elements of the list will be used as the elements of the set
s = set([1,2,3,4,5])

Access to set: Because set is an unordered set, we cannot access it through the index. We can only use the in operator to determine whether it exists.
Features of set: The internal structure of set is very similar to dict. The only difference is that the value is not stored. Therefore, it is very fast to determine whether an element is in the set.
Features of set: The elements stored in set are similar to the keys of dict and must be immutable objects. Therefore, any mutable objects cannot be placed in set.
Features of set: Finally, the elements stored in set are also in no order.
You can use a for loop to traverse the set.
To add new elements to set, you can use add() of set. If the added element already exists in set, add() will not report an error, but it will not be added.
To delete an element from set, you can use the remove() method of set. However, if the element does not exist, remove() will report an error. You need to determine the
function in Python before using it.

Calling a function in Python requires knowing the name and parameters of the function.
In Python, to define a function, use the def statement, write the function name, parentheses, parameters in the parentheses, and colon:, then, inindent blockWrite the function body in , and use the return statement to return the return value of the function.
Python functions return multiple values. In Python, functions are allowed to return multiple values, and the returned result will be a tuple type return value.
Default parameters can be defined in Python functions to simplify calls. Necessary parameters need to be passed in, but when needed, additional parameters can be passed in to override the default parameter values.
To define variable parameters in a Python function, add an * sign in front of the name of the variable parameter, so that zero or more parameters can be passed in. In Python, the variable parameter will be passed into the function as a tuple.
Slicing strings in Python

The string 'xxx' and the Unicode string u'xxx" can also be regarded as a list, each element is a character. Therefore, the string can also be sliced, but the result of the operation is still a string. In
Python Iterate

In Python, iteration is done through for...in.
In Python, iteration takes out the element itself, not the index of the element.
For an ordered set, if you want to get its own index, you can use the enumerate() function. This function can turn each element in the ordered set into a tuple, so that you can get the index value of the element.
L = ['adam','lisa','bart','paul']==>L = [(0,'adam'),(1,'lisa'),(2,'bart'),( 3,'paul')]
for t in enumerate(L):
index = t[0]
name = t[1]
print index,'-', name

The above code can be abbreviated as:

for index,name in enumerate(L):
print index,‘-’,name

For dict iteration to remove value, there are two methods:
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
for v in d.values():
print v
for v in d.iteravlues( ): The output results of
print v
are the same, all the value values ​​​​of the dict are output, but the difference is that the values() method actually converts a dict into a list containing all values, while the itervalues() method does not Conversion, it will take out the values ​​from the dict in turn during the iteration process, so the itervalues() method saves the memory of generating the list than values().

  • To iterate the keys and values ​​of the dict, you can use the items() method to convert the dict object into a list of tuples, and then iterate the list to obtain the key and value at the same time. items() also has an iteritems() method. During the iteration process, tuples are not given, so iteritems() does not occupy additional memory.
    d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
    print(d.items())

Output results

[(‘Lisa’, 85), (‘Adam’, 95), (‘Bart’, 59)]

The above are all things you need to learn to get started with Python. But many friends may still not know how to get started with Python. Is it enough to learn the above to get started with Python? Don’t worry at all, the editor has compiled a complete set of zero-based learning materials for Python.

Guess you like

Origin blog.csdn.net/q762459510/article/details/127823460