Python study notes (1) - basic grammar

    Written in front: As a third-year student majoring in electronic information, I feel that I have little knowledge, so I decided to learn Python by myself. I used to read other people's blogs. This is the first time I used a blog to write study notes. I hope it can be used as a record of the learning process and a summary of my learning knowledge. I hope I can stick to it~

    When I decided to learn Python, I actually considered several self-study methods. At first, I watched the video course on the course website, but I felt that this learning was too slow. While searching, I found Liao Xuefeng's official website, and I thought it was suitable for self-study, so I used it as a reference to start learning. Yesterday, I read three chapters in one afternoon. The knowledge points are very easy to understand. They are all basic grammar. If you write more code, you will naturally remember it. However, when you first started learning, I decided to write some simple records for easy search and review.


1. String representation

1. Strings are represented by "" or ' '. When the string contains ', enclose it with "". You can also use the escape character \ when representing "

For example: 'I\'m \"OK"!' The output is I'm "OK"!

2. If many characters need to be escaped, you can use r ' ' 

For example: print(r'\\\t\\') The output is \\\t\\

3. When the string has many newlines: you can use ''' ''' to indicate

For example: print('''line1 (press enter) line2 (press enter) line3''') The output is:

line1

line2

line3

Second, the string encoding

In the latest Python 3 version, strings are encoded in Unicode.

Python provides the ord() function to obtain the integer representation of a character, and the chr() function to convert the encoding to the corresponding character:

>>> ord('A')
65
>>> ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'Arts'

Because strings need to be converted to bytes in bytes to be transmitted over the network or saved to disk, understand the following functions:

A.    encode()

The str in Unicode can be encoded into the specified bytes through the encode() method, for example:

>>> 'ABC'.encode('ascii')
b'ABC'
>>> 'Chinese'.encode('utf-8')
b '\ xe4 \ xb8 \ limit \ xe6 \ x96 \ x87'

B.    decode()

When the byte stream is read on the network or disk, it is necessary to convert the bytes type to str, and this function can be used. Such as:

>>>b'ABC'.decode('ascii')
'ABC'
>>>b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'Chinese'

C. Other related functions

len()  calculates how many characters str contains or how many bytes bytes contains, depending on the type of string enclosed in parentheses.

>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('Chinese'.encode('utf-8')) #Convert to bytes
6

Precautions:

 1. It is recommended to use utf-8 to convert str and bytes

  2. When the source code contains Chinese, be sure to specify utf-8 encoding. Usually written at the beginning of the file:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
The first line of comment is to tell the Linux/OS X system that this is a Python executable program, and the Windows system will ignore this comment;
the second line of comment is to tell the Python interpreter to read the source code according to UTF-8 encoding, otherwise , the Chinese output you wrote in the source code may have garbled characters

Also note that text editors also use utf-8without BOM encoding.


3. Data Type

list A list is  like an array.

Elements can be accessed by index. The last element index is len(classments)-1. The last reciprocal element can be represented by a negative index subscript

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> len(classmates)
3
>>> classmates[-1]
'Tracy'

Related functions: xx.append() adds an element to the end, xx.insert() inserts, xx.pop deletes the end element, xx.pop(i) deletes the corresponding element

>>> classmates.append('Adam')
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']

>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

>>> classmates.pop()
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']

>>> classmates.pop(1)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']


tuple

Once initialized, it cannot be modified, and it is safer because it is immutable.

But list can be used as a tuple element, making it appear mutable

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

Feature: Slicing

Slicing can be used to take part of a list or tuple. Similar to matlab, except that matlab starts from 1, and python starts from 0. And python does not include the last number. And not parentheses, use []

For example: L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

To take the first three, you can use L [ 0:3 ] which is equivalent to [ L[0], L[1], L[2] ], that is, the index is 0-N-1; when the first number is 0, Can be omitted, ie L[:3] =   [ L[0],L[1],L[2] ]

Since L[-1] can be used to take the last element, similarly, slices can also take the reciprocal. Such as:

L[-2 : -1] takes the second to last, and L[ -2 : ] takes the second to last. which is

>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']

You can also take numbers at intervals , that is, add another number at the back: L[ : 10: 2 ] is expressed as the first ten numbers, one for every two.

Create a list.

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]
>>> L[:10:2]
[0, 2, 4, 6, 8]
The top ten are listed above, one for every two. The following are all numbers, one for every five
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
If you take all of them, you can use the L[ : ]
tuple operation as above, and the string 'xxx' can also be used as a slice operation, and each element is a character.


dict dictionary

Known as map in other languages, it uses key-value storage (key-value).

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

How to put data in:

>>> d['Bob'] = 67
>>> d['Bob']
67

Determine if the key is in the dictionary

>>> 'Thomas' in d #judging by in
False

>>> d.get('Thomas') #Judging by get(), there is no return None
>>> d.get('Thomas', -1)# does not exist and returns -1.
-1

Remove using xx.pop(key)


set is similar to dict, but without value. And there are no duplicate keys in the set.

Add element: xx . add(key)

Remove an element: xx .remove(key)

A set can be regarded as a collection of unordered and non-repetitive elements in a mathematical sense. Therefore, two sets can perform operations such as intersection and union in a mathematical sense.

4. Logic

Conditional judgment

Python does not use curly brackets to distinguish paragraphs or use end, but directly uses indentation. example:

age = 3
if age >= 18:
    print('your age is', age)
    print('adult')
#If there is no indentation, it is equivalent to not inside the if.
elif age>=6:
    print('teenager')
else:
    print('your age is', age)
    print('teenager')
Be careful not to miss the colon, the general editor can automatically complete it.

cycle

There are two kinds of loops in Python, one is the for...in... loop, which iterates each element in the list or tuple in turn. The second type of loop is the while loop.

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

If you want to calculate the sum of integers from 1-100, Python provides a range() function, which can generate a sequence of integers, and then convert it to a list through the list() function. For example, the sequence generated by range(5) is an integer starting from 0 and less than 5:

>>> list(range(5))
[0, 1, 2, 3, 4]

Use while to represent a loop:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

The break and continue in the loop are the same as the c language.


5. Input and output

A. output

print() output, the parentheses can be data or strings, and commas can be added to output multiple strings or data, each comma will output a space

>>> print('The quick brown fox', 'jumps over', 'the lazy dog')
The quick brown fox jumps over the lazy dog

B. Input

input() can receive input, the return value is str type, and the prompt can be entered in parentheses.

name = input('please enter your name: ')
print('hello,', name)

The output is:

please enter your name: Michael
hello, Michael

Notice:

The data type returned by input() is str, and str cannot be directly compared with an integer. If the input is data, str must be converted to an integer first. Python provides the int() function to do this:

s = input('birth: ')
birth = int(s)
if birth < 2000:
    print('before 00')
else:
    print('after 00')
C. Formatting.
Similar to the C language, just replace , with %, and add parentheses when there are more than one variable. Such as:

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'



6. Calculation

Division: / indicates floating point division calculation. Return a floating point number. For example: >>>9/3 output 3.0

         // Also called floor division, returns an integer. 10//3 is 3.

remainder %


    The above is a simple record of the first note~ There are some advanced features about list and tuple that have not been written, so I will write it with the function next time. Many examples in this study note are cited from Liao Xuefeng's website .

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946169&siteId=291194637