This article is for experienced programmers to enter the Python world as quickly as possible. In particular, if you know Java and Javascript, you can write useful Python programs quickly and smoothly in Python in less than an hour.
Why use Python
Suppose we have a task that simply tests whether the computers on the LAN are connected. These computers have IP addresses ranging from 192.168.0.101 to 192.168.0.200.
Linux is bash and Windows is batch script. For example, on Windows, test each machine in turn with the ping IP command and get console output. Since the console text is usually “Reply from… “When it doesn’t, the text is” Time out… “, so a string lookup in the result will tell you if the machine is connected.
Implementation :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(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();
}
Copy the code
This code works fine, but the problem is that in order 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 bytecode
- Since bytecode can’t run directly, you’ll need to write a small bat or bash script to run it.
Of course, you can do the same with C/C++. But C/C++ is not a cross-platform language. The difference between C/C++ and Java implementations may not be noticeable in this simple enough example, but in more complex scenarios, such as logging connectivity to a network database. Because Linux and Windows implement network interfaces differently, you have to write versions of both functions. With Java, there are no such concerns.
The same work is done in 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()
Copy the code
Python’s implementation is much cleaner and you write faster than Java. You don’t need to write main, and the program can be saved and run directly. Also, like Java,Python is cross-platform.
Experienced C/Java programmers might argue that writing in C/Java is faster than writing in Python. It’s a matter of opinion. My idea is that when you learn both Java and Python, you’ll find it much faster to write programs like this in Python than in Java. For example, you only need one line of code to manipulate a local file instead of Java’s many stream-wrapping classes. Each language has its own natural range of applications. Dealing with short programs like interactive programming with the operating system in Python saves the most time and effort.
Python applications
Simple enough tasks, such as some shell programming. If you like to design large commercial websites or complex games in Python, be my guest.
Hello world
After installing Python (my native version is 2.5.4), open IDLE(Python GUI). This program is the Python language interpreter, and your statements will run immediately. Let’s write down the famous program statement:
print "Hello,world!"
Copy the code
And press Enter. You’ll see this quote introduced by K&R into the world of programming.
Select “File”–“New Window” or the shortcut Ctrl+N in the interpreter to open a New editor. Write the following:
print "Hello,world!"
raw_input("Press enter key to close this window! ");
Copy the code
Save as a.py file. Press F5 and you can see the results of the program. This is the second way Python works.
Find your saved A.py file and double-click. You can also see the program results. Python programs can run directly, which is an advantage over Java.
Internationalization support
Let’s greet the world in a different way. Create a new editor and write the following code:
print "Welcome to Olympic China!"
raw_input("Press enter key to close this window!");
Copy the code
When you save the code,Python will prompt you to change the character set of the file.
# -*- coding: cp936 -*-
print "Welcome to Olympic China!"
raw_input("Press enter key to close this window! ");
Copy the code
Change the character set to the more familiar form:
# -*- coding: GBK -*-
print "Welcome to Olympic China!" # Examples of using Chinese
raw_input("Press enter key to close this window");
Copy the code
The program also works well.
Easy to use calculator
The calculator that comes with Microsoft is too cumbersome to count. Open the Python interpreter and compute directly:
a=100.0
b=201.1
c=2343
print (a+b+c)/c
Copy the code
Strings,ASCII and UNICODE
You can print strings in the predefined output format as follows:
print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """
Copy the code
How is a 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)
Copy the code
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);
Copy the code
Use the List
Similar to the Java List, this is a handy 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 # index1 and 2 elements of word. c=word[:2] print "c is: " print c # index0 and 1 elements 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 # index3 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[image-b4CED -1616074265420-0] "word.append('h') print wordCopy the code
Conditional 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 ina:
print x, len(x)
Copy the code
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
Copy the code
And, introduce a convenient function:
# The range() function
a =range(5.10)
print a
a = range(-2, -7)
print a
a = range(-7, -2)
print a
a = range(-2, -11, -3) # The 3rd parameter stands for step
print a
Copy the code
File I/O
spath="D:/download/baa.txt" f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist. f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file forreading for line in f:
print line
f.close()
Copy the code
Exception handling
s=raw_input("Input your age:") if s =="":
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 that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old" finally: # Clean up action
print "Goodbye!"
Copy the code
Class 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) :
return a+b
oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2.3)
Copy the code
Package mechanism
Each.py file is called a module, and modules can be imported from one another. Please refer to the following examples:
# a.py
def add_func(a,b) :
return a+b
Copy the code
# b.py
from a import add_func # Also can be : import a
print "Import add_func from module a"
print"Result of 1 plus 2 is: " print add_func(1.2) # If using "import a" , then here should be "a.add_func"
Copy the code
Modules can be defined in packages. Python defines packages in a slightly odd way, assuming we have a parent folder that has a child folder. Child has a module A.py. How do I let Python know about this file hierarchy? Very simply, each directory has a file named _init_.py. The file contents can be empty. The hierarchy is as follows:
parent
--__init_.py
--child
-- __init_.py
--a.py
b.py
Copy the code
So how does Python find the module we defined? In the standard package SYS, the path property records the Python package path. You can print it out:
import sys
print sys.path
Copy the code
Normally we can put the package path of the Module into the environment variable PYTHONPATH, which is automatically added to the sys.path property. Another convenient way is to programmatically specify our module path to sys.path directly:
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)
Copy the code
conclusion
You’ll find this tutorial fairly simple. Many Python features are presented implicitly in code, including :Python does not require explicit declarations of data types, keyword descriptions, string function explanations, and so on. I think a skilled programmer should know a lot about these concepts, so that after you squeeze in a precious hour of reading this short tutorial, you’ll be familiar with Python through the analogy of transferring your existing knowledge and starting programming with it as soon as possible.
Resource portal
- Pay attention to [be a gentle program ape] public account
- In [do a tender program ape] public account background reply [Python information] [2020 autumn recruit] can get the corresponding surprise oh!
- Build their own blog address: nightmare back to life blog
“❤️ thank you.”
- Click “like” to support it, so that more people can see this content.
- Share your thoughts with me in the comments section, and record your thought process in the comments section