Python basic tutorial Python introductory tutorial of ultra detailed

  • 2021-11-13 07:55:56
  • OfStack

Directory Why Use PythonPython Applications Hello world Internationalization Support Easy Calculator Strings, ASCII and UNICODE Use List Conditions and Loop Statements How to Define Function Files I/O Exception Handling Classes and Inheritance Package Mechanisms Summary

Why use Python

Suppose we have one task: Simple test the connectivity of computers in the LAN. The ip of these computers ranges from 192.168. 0.101 to 192.168. 0.200.

Idea: Programming with shell. (Linux is usually bash and Windows is a batch script). For example, on Windows, each machine is tested in turn with the command of ping ip and the console output is obtained. Because the console text is usually "Reply from …" when ping is on and "time out …" when it is not, you can know whether the machine is connected or not by searching the string in the result.

Implementation: The Java code is as follows:


String cmd="cmd.exe ping ";
String ipprefix="192.168.10."; int begin=101; int end=200;
Process p=null; for(int i=begin;i<end;i++){
     p= Runtime.getRuntime().exec(cmd+i);
     String line = null;
     BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
     while((line = reader.readLine()) != null)
     {
         //Handling line , may logs it.  }
    reader.close();
    p.destroy();
} 

This code works well, but the problem is that in order to run this code, you need to do 1 extra work. These extra work include:

Write a class file Write an main method Compile it into byte code Since ByteCode can't run directly, you need to write a small bat or bash script to run.

Of course, you can do the same with C/C + +. But C/C + + is not a cross-platform language. In this simple enough example, you may not see the difference between C/C + + and Java implementations. But in a more complex scenario, such as recording connectivity information to a network database, you have to write versions of the two functions because of the different network interface implementations of Linux and Windows. With Java, there is no such concern.

The same work is done with Python as follows:


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 

Compared to Java, the implementation of Python is simpler and you write faster. You don't need to write the main function, and this program can be run directly after saving. In addition, like Java1, Python is also cross-platform.

Experienced C/Java programmers might argue that writing with C/Java is faster than writing with Python. This is a different view. My idea is that when you master Java and Python at the same time, You will find that writing such programs with Python is much faster than with Java. For example, you only need one line of code to manipulate local files instead of many stream wrapper classes of Java. Various languages have their natural application range. Working with short programs with Python is the most time-saving and labor-saving work, such as interacting with the operating system.

Python Applications

Simple enough tasks, such as some shell programming. If you like to use Python to design large commercial websites or complex games, you can do whatever you want.

Hello world

After installing Python (my native version is 2.5. 4), open IDLE (Python GUI), which is the Python language interpreter, and the statement you write can run immediately. Let's write a famous program statement:


print "Hello,world!"

And press Enter. You can see this sentence by K & R is a famous saying introduced into the programming world.

Select "File", "New Window" or the shortcut key Ctrl+N in the interpreter to open a new editor. Write the following statement:


print "Hello,world!"
raw_input("Press enter key to close this window! ");

Save as a. py. Press F5 and you will see the result of the program. This is the second way of Python.

Find your saved a. py file and double-click. You can also see the results of the program. The program of Python can run directly, which is an advantage over Java.

Internationalization support

Let's greet the world in another way. Create a new editor and write the following code:


print " Welcome to Olympic China !" 
raw_input("Press enter key to close this window!");

When you save the code, Python will prompt you whether to change the character set of the file. The result is as follows:


# -*- coding: cp936 -*-
print " Welcome to Olympic China !" 
raw_input("Press enter key to close this window! ");

Change this character set to a more familiar form:


# -*- coding: GBK -*-
print " Welcome to Olympic China !" #  Examples of using Chinese  
raw_input("Press enter key to close this window");

Program 1 works well.

An easy-to-use calculator

It's too much trouble to count with the calculator that comes with Microsoft. Open the Python interpreter and calculate directly:


a=100.0 
b=201.1 
c=2343 
print (a+b+c)/c 

String, ASCII and UNICODE

You can print a string in a predefined output format as follows:


print """ Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to """

How is the string accessed? Look at this example:


word="abcdefg" a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)

Note the difference between ASCII and UNICODE strings:


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
0

Using List

Similar to List in Java, this is a convenient and easy-to-use data type:


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
1

Conditional and loop statements


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
2

How do I define a function


# Define and invoke function.
def sum(a,b):
    return a+b
func = sum
r = func(5,6)
print r
# Defines function with default argument
def add(a,b=2):
    return a+b
r=add(1)
print r
r=add(1,5)
print r

In addition, a convenient and easy-to-use function is introduced:


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
4

Document I/O


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
5

Exception handling


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
6

Classes and inheritance


 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
7

Packet mechanism

Every 1. py file is called 1 module, and module can be imported into each other. See the following example:


# a.py
def add_func(a,b):
    return a+b

 import subprocess
cmd="cmd.exe" begin=101 end=200  while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.1."+str(begin)+"\n")
    p.stdin.close()
    p.wait()
    print "execution result: %s"%p.stdout.read() 
9

module can be defined in packages. Python defines packages in a slightly odd way, suppose we have an parent folder with an child subfolder. module a. py in child. How do you let Python know about this file hierarchy? Quite simply, each directory has a file named _init_. py. The contents of the file can be empty. The hierarchy is as follows:


parent 
  --__init_.py
  --child
    -- __init_.py
    --a.py
b.py

So how does Python find the module we defined? In the standard package sys, the path property records the package path of Python. You can print it out:


import sys
print sys.path

Usually we can put the package path of module into the environment variable PYTHONPATH, which is automatically added to the sys. path property. Another convenient method is to specify our module path directly to sys. path in programming:


import sys
sys.path.append('D:\\download')
from parent.child.a import add_func
print sys.path
print "Import add_func from module a" print"Result of 1 plus 2 is: " print add_func(1,2)

Summarize

You'll find this tutorial fairly straightforward. Many of the Python features are implicitly presented in the code, These features include: Python does not require explicit declarations of data types, keyword descriptions, string function explanations, etc. I think a skilled programmer should be fairly familiar with these concepts so that after you squeeze out an hour to read this short tutorial, you can get familiar with Python as soon as possible through the migration analogy of your knowledge, and then start programming with it as soon as possible.

This article is here, I hope to bring help to you, and I hope you can pay more attention to more content of this site!


Related articles: