python basic abridged edition

Fragmented reading: Here I just briefly summarize the following basic syntax. Because I have experience in java development before, I haven't written some knowledge points. If I want to learn pyhton in detail, I suggest to see the rookie tutorial.

Learning the basic grammar of python

1. Mark coding method

# -*- coding: cp-1252 -*-

2. Input and output

# notes
print()

3. Identifier

Identifier, which is implemented in the way of letter array underline, and is case sensitive

4. Reserved words

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

5. Notes

# Single-Line Comments 
'''  multiline comment '''
""" multiline comment  """

6. Indent

python does not apply {} to represent data, but implements related operations by indentation

7. Multiline statements

For long statements, the /+Implementation of
total = str1 +\
		str2 +\
    	str3 +\
        str4

8. Number type

There are four main types of number

  • int shaping
  • Boolean type
  • float type 1.23, 3E-2
  • Complex complex type 1+2j, 1.1+2.2j

9. String

In python, you can use '' to define strings, and the form is the same as that of '' ''. Both can represent multiple lines of strings, and '' can be used for a single string

Escape character \ n \ t

The escape character r. 'abc\n' is useless at this time

There are no character types in python. One is a string

Index method:

The index can be understood as starting from 0 and ending at - 1

a = 'abctt'
a[0:-1] #Means from beginning to end
a[2:]#Start with 3
a[2:5:2]# From 3-5, there are two in the middle
a+"Hello" #String splicing

10. Blank line

Empty lines are used to separate functions or class methods, indicating the beginning of a new piece of code. The class and function entry are also separated by an empty line to highlight the beginning of the function entry.

Blank lines, unlike code indentation, are not part of Python syntax. When writing, do not insert blank lines, and the Python interpreter will run without error. However, the function of blank lines is to separate two sections of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of the code in the future.

**Remember: * * blank lines are also part of the program code.

11. Input

Input indicates input

12. Multiple statements on the same line

For multiple statements in the same line, you can use; division

import sys; print("hello")

13. For multiple statements

The code group can be processed in the form of:

14. Output

#For python, there are mainly newline output and non newline output
print('hello')
print('word')
#No newline output
print('hello',end=" ")
print('word',end=" ")

15. Import package

  • Import all sys
  • Import part from sys import input
  • Import all from sys import*

Basic data type

1. Assignment

# For assignment, even equals
a = b= c
a ,b,c = 1,1.4,'root'

2. Standard data type

There are six basic data types in python

Number, character, tuple, set, list, the first three tuples are variable, and the last three tuples are immutable

There are two main methods to judge data types

Method 1: through type (1, int)

Method 2: isInstance (a ()) through isInstance

Difference: the type here is only True and the same. The subclass in isInstance is also True and correct

Here you can use IS to judge the type. Here you can use type. Note that bool IS a subclass of int, so true == 1

false = 0

When creating a value, an object is also created. You can delete an object by del

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wi1mvjsb-163749554431) (E: \ Python \ learning document \ Snipaste_2021-11-17_23-22-05.png)]

2. List

Basic operations and characters of the list

list = ['a','b','c','d']
list[0:]
list[1:5:2]
# Unlike String, the data in the list can be modified

Common methods:

append(). pop () and other methods

3. Tuple

Note: the data in the tuple cannot be modified, but the elements contained in the tuple can be modified

tup = (1,2,3,4,5,6)
tup[1:4]#It is the same as the previous work, so there is no need to change, but the relevant parameter information can be changed

Note: the characters, tuples, and lists mentioned here are elements that can be changed, so there are many similarities in the operation methods

4. Assembly

The set here can be regarded as a set of multiple types of data, and the set set can delete the reread elements.

5. Dictionary

Dictionaries are equivalent to Map related operations in java, which are stored here through key value pairs

6. Character conversion

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vb3t7txa-163749554433) (E: \ Python \ learning document \ Snipaste_2021-11-17_23-56-30.png)]

python operators

The basic operators of python are used here. The operators here are the same as those in java

# Define number
var =1
var2 = 2
#Delete related references
del var
del var,var2
# Convert numeric type
var3= 1.0
var4= int(var3)

2. String

The functions described here are the same as those described above, so the functions related to strings are used here

#!/usr/bin/python3
 
a = "Hello"
b = "Python"
 
print("a + b Output results:", a + b)
print("a * 2 Output results:", a * 2)
print("a[1] Output results:", a[1])
print("a[1:4] Output results:", a[1:4])
 
if( "H" in a) :
    print("H In variable a in")
else :
    print("H Not in variable a in")
 
if( "M" not in a) :
    print("M Not in variable a in")
else :
    print("M In variable a in")
 
print (r'\n')
print (R'\n')

String output

Adopted here

print("I am s% this year %d year" % ('zhao',10))

Basic value type

Technology added later

f-string is actually f{}

>>> name = 'Runoob'
>>> f'Hello {name}'  # Replace variable
'Hello Runoob'
>>> f'{1+2}'         # Use expressions
'3'

>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'

In addition, there are many operations such as characters and functions for strings. Because there are too many, there is not much to show here

list

There is no need to elaborate on the operation of the list here. It is mainly the same as the data, which can delete and store data. The data here is shown below

# Create list
list1 = [1,2,3,4,5]
# Query list
list1[3]
#Add element
list1.append(6)
# Delete list element
del list1[5]
# Nested list 
a = [1,2,3]
b = [4,5,6]
c = [a,b]

Common functions

tuple

The basic operation of tuple and list here is the same, but the value cannot be changed

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-brlzed-16374950554442) (C: \ users \ Xinyu \ appdata \ roaming \ typora \ user images \ image-20211118211255304. PNG)]

Dictionaries

Delete a data item

def1 = {1:'w' , 2:'e', 3:'t' }
#Delete specific elements
del def1['1']
# Empty dictionary
def1.clear()
#Delete dictionary
del def1

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-skp5rz56-16374955443) (C: \ users \ Xinyu \ appdata \ roaming \ typora user images \ image-20211118214007882. PNG)]

Related functions and functions

aggregate

#Create form for collection
{} , set()
{'g','r','y','u'}
a = set('hello')
#There are several kinds of set functions
a -b #a contains b does not contain
a |b a,b Elements in
a&b  #Elements contained in ab
a^b ab Elements not included at the same time

#Add element to collection
a.add('t')
# Removing Elements 
a.remove()

Basic process control statement

Here, there are several basic process control statements, including if else, for while, etc. the use here will not be described in detail, which is the same as that in Java

function

  • Required parameters
  • Keyword parameter, which determines the type of function through keywords
  • The default parameter is defined during the period defined by the function and during the period passed in the parameter
  • The variable length parameter is mainly transmitted through * args to determine the value of the variable length
  • Anonymous function, which is determined by the anonymous function, i.e. lambed function, sum = lambed arg1, arg2; arg1+arg2
  • Return return value function
  • In Python 3.8, / can be used to force the location information of functions.

data structure

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fm0ukp1c-163749554443) (C: \ users \ Xinyu \ appdata \ roaming \ typora \ user images \ image-20211118231218003. PNG)]

Program block

The information of the program block here is to process the data by writing a python related data file

  • Import module (implemented by means of import, from import *)
  • Return,, and related contents of modularization

*__name _ attribute

#This represents the main program of the program, and only the main program can run
if __name__ == '__main__':
   print('The program itself is running')
else:
   print('The first mock exam is from another module.')

The dir() function can find the function names defined inside all modules

Standard module. The standard block function here adopts sys, and common functions can be used

package

Package is a form of managing Python module namespace, which adopts "point module name".

For example, if the name of a module is A.B, it represents sub module B in package a.

Just as you don't have to worry about the interaction of global variables between different modules when using modules, you don't have to worry about the duplicate names of modules between different libraries in the form of point module names.

In this way, different authors can provide NumPy module or Python graphics library.

Suppose you want to design a module (or a "package") that processes sound files and data uniformly.

There are many different audio file formats (basically distinguished by suffixes, such as:. wav,: file:.aiff,: file:.au,), so you need to have a group of increasing modules to convert between different formats.

And for these audio data, there are many different operations (such as mixing, adding echo, adding equalizer function, creating artificial stereo effect), so you also need a set of endless modules to deal with these operations.

sound/                          Top package
      __init__.py               initialization sound package
      formats/                  File format conversion sub package
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Sound effects sub package
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  filters subpackage 
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

When importing a package, Python will find the subdirectories contained in the package according to the directory in sys.path.

The directory can only be regarded as a package if it contains a file called init.py, mainly to avoid some vulgar names (such as string) inadvertently affecting the effective modules in the search path.

In the simplest case, just put an empty file:init.py. Of course, this file can also contain some initialization code or assign values to the _all variable (which will be described later).

Users can import only specific modules in one package at a time, such as:

#Import package data
import sound.effects.echo

Import all data from one package. Here, you can use from sound.effects.echo

Input and output

Python can output values in two ways:

  • Expression statement

  • print() function.

  • Using the write() method of the file object, the standard output file can be referenced with sys.stdout.

If you want the output to be more diverse, you can use the str.format() function to format the output value.

If you want to convert the output value into a string, you can use the repr() or str() function.

  • str(): the function returns a user-friendly expression.
  • repr(): produces an interpreter readable expression.
>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'
>>> repr(s)
"'Hello, Runoob'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x The value of is: ' + repr(x) + ',  y The value of is:' + repr(y) + '...'
>>> print(s)
x The value of is: 32.5,  y The value of is 40000...
>>> #  The repr() function can escape special characters in a string
... hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'
>>> # The argument to repr() can be any Python object
... repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"
for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

format is a commonly used form of digitized characters

Read from keyboard

The input function is mainly used

Read and write files

It mainly adopts open(filename, mode), where filename represents the name of the file and mode represents the mode

r. w and a represent related operations and related permissions

Method of reading file object

adopt

Read stands for read all

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# Close open files
f.close()

readline () means to read a row of data

str = f.readLine()

In addition, you can iterate through for

for line in f:
    print(line,end = " ")
f.close()

write module

Here you can write the function write

Close means to close the file

OS

The os module provides rich methods for processing files and directories. The common methods are shown in the following table:

python errors and exceptions

  • Try – exception: the exceptions here need to be clearly explained. For the exceptions in try, if there is an exception with the name after exception, it will be thrown. If the exception does not match it, it will be directly thrown to the upper level try statement

  • try --except --else combination: else here represents the code executed when there is no exception

  • try --except – else – finally here, for finally, the code will be executed whether it is executed or not

Throw an exception (the exception here refers to the self-defined exception)

Use raise to set

X= 10
if x>5:
	raise Exception("The value of the data cannot exceed 5")

Auto define exception

def divide(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
        else:
            print("result is", result)
        finally:
            print("executing finally clause")
   
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

object-oriented

Class definition:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

Class object

Class objects support two operations: attribute reference and instantiation.

Attribute references use the same standard syntax as all attribute references in Python: obj.name.

After the class object is created, all names in the class namespace are valid attribute names. Therefore, if the class definition is as follows:

#!/usr/bin/python3
 
class MyClass:
    """A simple class instance"""
    i = 12345
    def f(self):
        return 'hello world'
 
# Instantiation class
x = MyClass()
 
# Access the properties and methods of the class
print("MyClass Properties of class i Is:", x.i)
print("MyClass Class method f Output is:", x.f())

The class has a special method (constructor) named init(). This method will be called automatically when the class is instantiated, as follows:

def __init__(self):
    self.data = []

Class defines the init() method, and the class instantiation operation will automatically call the init() method. Instantiate class MyClass as follows, and the corresponding init() method will be called:

x = MyClass()

Of course, the init() method can have parameters, which are passed to the instantiation operation of the class through init(). For example:

#!/usr/bin/python3
 
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # Output result: 3.0 - 4.5

hello world'

Instantiation class

x = MyClass()

Access the properties and methods of the class

print("attribute I of MyClass class is:", x.i)
print("the method f output of MyClass class is:", x.f())

Class has a name __init__() Special method of(**Construction method**),This method will be called automatically when the class is instantiated, as follows:

def init(self):
self.data = []

Class defines __init__() Method, the instantiation operation of the class will be called automatically __init__() Method. Instantiate the class as follows MyClass,Corresponding __init__() Method will be called:

x = MyClass()

of course, __init__() Method can have parameters, which can be passed through __init__() Passed to the instantiation operation of the class. For example:

~~~
#!/usr/bin/python3
 
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # Output result: 3.0 - 4.5
~~~





















Tags: Python

Posted on Mon, 22 Nov 2021 03:28:01 -0500 by phpwizard01