Why use Python
Let's say we have a task: simply test whether the computers in the LAN are connected. The IP range of these computers ranges from 192.168.0.101 to 192.168.0.200.
Idea: use shell programming. (Linux is usually bash and Windows is a batch script). For example, the ping IP command on Windows tests each machine in turn and gets the console output. The console text is usually "Reply from ..." When Ping is used. "And the text is" Time out ... , so a string lookup in the result will tell if the machine is connected.
Implementation: Java code is as follows:
--> String cmd="Cmd.exe Ping";
String Ipprefix="192.168.10.";
IntBegin=101;
IntEnd=200;
Process P=Null;
For(IntI=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 very well, the problem is to run this code, you need to do some extra work. These additional tasks include:
- Write a class file
- Write a Main method
- Compile it into a byte code
- Since the byte code can't run directly, you'll need to write a little bat or bash script to run.
Of course, the same can be done with C + +. But C + + is not a cross-platform language. In this simple enough example, it may not be possible to see the difference between C + + and Java implementations, but in some more complex scenarios, For example, to record connectivity information to the network database. Because Linux and Windows have different implementations of the network interface, you have to write two versions of the function. There is no such concern in Java.
The same work is done in Python as follows:
-->
Import subprocess
Cmd="Cmd.exe"
Begin=101
End=200
WhileBegin 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 ()
The comparison Java,python is simpler and you write faster. You do not need to write the main function, and the program can be run directly after it has been saved. Also, like Java, Python is cross-platform.
Experienced C/java programmers may argue that writing with C/java is faster than Python. This is a matter of opinion. My idea is that when you master both Java and Python, You'll find that writing this kind of program in Python can be a lot faster than Java. For example, if you are working with a local file, you need only one line of code instead of a lot of Java flow wrapper classes. Various languages have their own natural suitability for application. Use Python to handle some short programs like the operating system's interactive programming works most time-saving .
Python applications
Simple enough tasks, such as some shell programming. If you prefer to design large business websites with Python or design complex games, you may do so.
2 Quick Start
2.1 Hello World
After you install Python (my native version is 2.5.4), open the idle (Python GUI), which is the Python language interpreter, and the statements you write can be run immediately. We write the next famous program sentence:
and press ENTER. You can see this quote that was k&r into the program world.
In the Interpreter, select "File"--"New Window" or shortcut key CTRL + N to open a new editor. Write down the following statement:
Print "hello,world!"
Raw_input ("press ENTER key to close this window");
Save as a a.py file. By pressing F5, you can see the results of the program running. This is the second way Python runs.
Find the a.py file you saved, double-click. You can also see the results of the program. Python programs can run directly, compared to Java, which is an advantage.
2.2 Internationalization support
Let's greet the world in a different way. Create a new editor and write the following code:
Print " Welcome to the Olympic Games China!"
Raw_input ("press ENTER key to close this window");
When you save the code, Python prompts you to change the character set of the file, and the result is as follows:
#-*-coding:cp936-*-
Print " Welcome to the Olympic Games China!"
Raw_input ("press ENTER key to close this window");
Change the character set to our more familiar form:
#-*-CODING:GBK-*-
Print " Welcome to the Olympic Games China!" # using Chinese examples
Raw_input ("press ENTER key to close this window");
Program to work as well.
2.3 Easy to use calculator
It's too much of a hassle to count the calculators that came with Microsoft. Open the Python interpreter and calculate directly:
A=100.0
b=201.1
c=2343
Print (a+b+c)/C
2.4 Strings, ASCII and Unicode
You can print a string of predefined output formats as follows:
Print "" "
usage:thingy [OPTIONS]
-H Display this usage message
-H hostname hostname to connect to
"""
How is the string accessed? Please see this example:
--> Word="Abcdefg"
A=word[2]
Print"A is:"+A
B=word[1:3]
Print"B is:"+B # Index1and2Elements of Word.
C=word[:2]
Print"C is:"+C # Index0and1Elements 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:
--> Print"Input your Chinese name:"
S=Raw_input ("Press ENTER to be continued");
Print "Your name is : " +s;
L=Len (s)
Print "Length of your Chinese name in ASC codes is:"+str (l);
A=Unicode (s,"GBK")
L=Len (a)
Print "I ' m sorry we should use Unicode char! Characters number of your Chinese \
name in Unicode is:"+str" (l);
2.5 Use List
Like a list in Java, this is an easy-to-use data type:
--> Word=['A','B','C','D','E','F','G']
A=word[2]
Print"A is:"+A
B=word[1:3]
Print"B is:"
Print B # index1and2Elements of Word.
C=word[:2]
Print"C is:"
Print C # index0and1Elements of Word.
D=word[0:]
Print"D is:"
Print D # all elements of Word.
E=word[:2]+word[2:]
Print"E is:"
Print e # all elements of Word.
F=word[-1]
Print"F is:"
Print F # The last elements of Word.
G=word[-4:-2]
Print"G is:"
Print G # Index 3 and 4 elements of word.
H = word[- 2 :]
print " h is: "
Print h # the last two elements.
I = word[: - 2 ]
print " i is: "
Print i # everything except the last two characters
L = Len (word)
print " length of word is: " + str (l)
print " adds new element "
Word.append ( ' h ' )
Print word
2.6 Pieces and loop statements
--> # Multi-Way decision
X=Int(Raw_input ("Please enter an integer:"))
if x 0 :
x = 0
print negative changed to zero
Elif x = = 0 :
print " Zero "
Else :
print " more "
# loops list
a = [ ' cat ' , ' window ' , ' defenestrate ' ]
for x , in a:
print x, len (x)
2.7 How to 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
Also, introduce a handy and useful function:
# the range () function
A =range (5,ten)
Print a
A = range (-2,-7)
Print a
A = range (-7,-2)
Print a
A = range (-2,-one,-3) # The 3rd parameter stands for Step
Print a
2.8 File I/O
--> spath="d:/download/baa.txt"
F=open (spath,"w") # Opens file for writing. Creates this file doesn't exist.
F.write ("The1.\n")
F.writelines ("The2." )
F.close ()
F=open (spath,"r") # Opens file for reading
For line in F:
Print Line
F.close ()
2.9 Exception Handling
--> S=Raw_input ("Input Your Age:")
IfS=="":
Raise Exception ("Input must no be empty.")
Try:
I=Int(s)
Except ValueError:
Print"could not convert data to an integer. "
Except
Print "Unknown exception!"
else: # It is useful for code so must be executed if the ' try clause does not Raise an exception
Print "are%d" % I,"years old "
Finally: # Clean up action
Print "goodbye!"
2.10 Classes and inheritance
--> Class base:
def __init__ (self):
self.data = []
def add (self, x):
self.data.append (x)
def Addtwice (self, x):
self.add (x)
self.add (x)
# child extends base
class child (Base):
def plus (self,a,b):
&NBSP;&NBSP return a + b
ochild = Child ()
Ochild.add ( str1 )
Print ochild.data
Print ochild.plus ( 2 , 3 ) (* * * [* *] [*)] /span>
2.11 Packet mechanism
Each. py file is referred to as a module,module between each other. Please refer to the following examples:
# a.py
def add_func (a,b):
return a+b
# b.py
From a import Add_func # Also can be:import a
Print "Import add_func from module a"
Print "Result of1 plus 2 is: "
Print Add_func (1,2) # If using 'import a' , then here should is "a.add_func"
Module can be defined inside the package. The way Python defines a package is a little odd, assuming we have a parent folder that has a child subfolder. There is a module a.py. How do I get Python to know this file hierarchy? very simply, each directory has a name _
Init_.py file. The contents of the file can be empty. This hierarchy looks like this:
Parent
- -__init_.py
- -child
- - __init_.py
- -a.py
b.py
So how does python find the module we defined? In standard package SYS, the Path property records the Python package path. You can print it out:
Import Sys
Print Sys.path
In general, we can place the package path of module into the environment variable Pythonpath, which is automatically added to the Sys.path property. Another convenient approach is to programmatically specify our module path to the Sys.path:
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 of1 plus 2 is: "
Print Add_func (1,2)
Summarize
You will find this tutorial quite simple. Many Python features are implicitly presented in your code, which include: Python does not need to explicitly declare data types, keyword descriptions, string function explanations, and so on. I think a skilled programmer should be fairly knowledgeable about these concepts, So after you squeeze in a valuable hour to read this short tutorial, you can familiarize yourself with Python as quickly as possible with the migration analogy of existing knowledge, and then start programming with it as soon as possible.
Of course, the 1-hour learning Python is a pretty grandstanding. Specifically, the programming language includes syntax and standard libraries. Grammar is equivalent to martial arts, while the standard library application experience is similar to internal strength, need long-term exercise. Python learns Java's strengths and provides a number of Easy-to-use standard libraries for programmers to "copycat". (This is also the reason for Python's success), and at the beginning we saw examples of how Python invokes Windows cmd, and I'll try to write down the usage of the standard libraries and some application techniques to get people to really master Python.
But anyway, at least you'll be using Python instead of cumbersome batch-writing programs. Hopefully those programmers who really can read this article in an hour and start using Python will love this little article, thank you!