Introduction to Python Tutorial丨More than 1300 lines of code, allowing you to easily master the basics

Why use Python

Suppose we have such a task: simply test whether the computers in the LAN are connected. The ip range of these computers is from 192.168.0.101 to 192.168.0.200.

Idea: Use shell programming. (Linux is usually bash and Windows is batch script). For example, on Windows, use the ping ip command to test each machine in turn and get the console output. Since the console text is usually " Reply from ... " When there is no connection, the text is "time out ... " , so, by performing a string search in the result, you can know whether the machine is connected.

The Java code is as follows:

This code works just fine, the problem is that in order to run this code you need to do some extra work. These extra work include:

  • write a class file

  • write a main method

  • compile it to byte code

  • Since byte code cannot be run directly, you need to write a small bat or bash script to run it.

Of course, C/C++ can also do the job. But C/C++ is not a cross-platform language. In this simple enough example, the difference between C/C++ and Java implementation may not be visible, but in some more complex scenarios , for example, to record the connectivity information to a network database. Due to the different implementations of network interfaces in Linux and Windows, you have to write two versions of the function. With Java, there is no such concern.

The Python implementation is as follows:

Compared with Java, Python's implementation is more concise, and your writing time is faster. You don't need to write the main function, and the program can be run directly after saving. In addition, like Java, Python is also cross-platform.

Experienced C/Java programmers might argue that writing in C/Java is faster than writing in Python. This opinion is a matter of opinion. My idea is that when you master both Java and Python, you will find that writing these kinds of programs in Python The speed will be much faster than Java. For example, when operating a local file, you only need one line of code instead of Java's many stream wrapper classes. Various languages ​​have their natural suitable application scope. Using Python to process some short programs is similar to operations The interactive programming of the system is the most time-saving and labor-saving.

Basic syntax of Python

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324341219&siteId=291194637