A simple way to get started with Python encoding

Source: Internet
Author: User

Why use Python

Let's say we have a task: simply test whether a computer in a local area network is connected. The IP range of these computers ranges from 192.168.0.101 to 192.168.0.200.

Idea: Programming with the shell. (Linux is usually bash and Windows is a batch script). For example, use the ping IP command on Windows to test each machine sequentially and get console output. The console text is usually "Reply from ..." Because of the ping pass. "When the text is" Time out ... , so the string lookup in the results will tell 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 (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, and the problem is that you need to do some extra work to run the code. These additional tasks include:

    • Write a class file
    • Write a Main method
    • Compile it into a byte code
    • Since the byte code cannot be run directly, you need to write a little bat or bash script to run it.

Of course, the same work can be done in 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 or not information to the network database. Because Linux and Windows have different network interfaces, you have to write two versions of the function. There is no such concern with Java.

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 ()


Comparing Java,python is more concise and you write faster. You do not need to write the main function, and this program can be run directly after saving. In addition, like Java, Python is also cross-platform.

Experienced C/java programmers may argue that writing with C/java is faster than Python. This view is a matter of opinion. My idea is that when you master Java and Python at the same time, You will find that writing this kind of program in Python is much faster than Java. For example, you only need one line of code to manipulate a local file, and you don't need a lot of Java's streaming wrapper classes. Various languages have their natural suitable application range. Using Python to process some short programs like interacting with the operating system is the most time-saving task. .

Python Application Scenarios

Simple enough tasks, such as some shell programming. If you prefer to use Python to design large commercial websites or design complex games, you're on your own.

2 Quick Start 2.1 Hello World

After you install Python (my version of this machine is 2.5.4), open the idle (Python GUI), which is the Python language interpreter, and the statements you write can be run immediately. Let's write down a famous program sentence:

Print "hello,world!"


and press ENTER. You can see this quote that was introduced into the world of programming by K&r.

In the Interpreter, select "File"--"New Window" or shortcut 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.py file. Press F5, and you can see the results of the program running. This is the second way to run Python.

Locate the a.py file you saved, and double-click it. You can also see the program results. Python programs can run directly, compared to Java, which is an advantage.

2.2 Internationalization support

We will 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");


When you save the code, Python will prompt you to change the character set of the file, as follows:

#-*-coding:cp936-*-

Print "Welcome to Olympic China!"
Raw_input ("Press ENTER key to close this window");


Change the character set to the form we are more familiar with:

#-*-CODING:GBK-*-

Print "Welcome to Olympic China!" # Example of using Chinese
Raw_input ("Press ENTER key to close this window");


The program works as well.

2.3 Easy-to-use calculator

It's too much trouble 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? See 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 of the elements.
I=word[:-2]
Print "I am:" +i # Everything except the last of the characters
L=len (Word)
Print "Length of Word is:" + str (l)


Note the differences 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 Using 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 # index 1 and 2 elements of Word.
C=word[:2]
Print "C is:"
Print C # index 0 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 # index 3 and 4 elements of Word.
H=word[-2:]
Print "H is:"
Print H # The last of the elements.
I=word[:-2]
Print "I is:"
Print I # Everything except the last of the 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 the 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, a handy function is introduced:

# 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

2.8 File I/ospath= "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 for reading

For line in F:
Print Line

F.close ()

2.9 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 this must be executed if the TRY clause does isn't raise an exception
Print "You is%d"% i, "years old"
Finally: # Clean up action
Print "goodbye!"

Class 2.10 and inheriting 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)

2.11 Package Mechanism

Each of the. py files is called a module,module that can be imported between each other. See the example below:

# 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 of 1 plus 2 is:"
Print Add_func # If using "Import a", then here should is "A.add_func"



Module can be defined inside the package. Python defines the package in a slightly odd way, assuming that 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? It's easy to put a file named _init_.py in each directory. 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 define? In standard package SYS, the Path property records the Python package path. You can print it out:

Import Sys

Print Sys.path


Usually we can put the module's package path into the environment variable Pythonpath, which is automatically added to the Sys.path property. Another convenient way is to directly specify our module path 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

Summarize

You will find this tutorial quite simple. Many of the python features are implicitly presented in the code, including: Python does not need to explicitly declare data types, keyword descriptions, the interpretation of string functions, and so on. I think a skilled programmer should understand these concepts quite well, So after you squeeze out the precious hour to read this short tutorial, you'll be able to familiarize yourself with Python as soon as possible with the knowledge of the migration analogy, and then start programming with it as soon as possible.

Of course, the 1-hour learning of Python is quite grandstanding. Specifically, the programming language includes syntax and standard libraries. Grammar is equivalent to martial arts, while standard library application practice is similar to internal strength, requiring long-term exercise. Python learns Java's strengths and provides a number of easy-to-use standard libraries for programmers to "take doctrine". (This is also why Python succeeds), and at the beginning we see examples of how Python invokes Windows cmd, and I'll try to write about the usage of the standard libraries and some application techniques in the future so that you can really master Python.

But anyway, at least you'll be using Python instead of a tedious batch program. Hopefully those programmers who can really read this article in an hour and start using Python will love this little article, thank you!

Transferred from: http://blog.csdn.net/chengyakun11/article/details/8140200

Well, now that we have a simple understanding of Python, here's a more systematic study of Python:

Jump Link:

[Python] web crawler (a): crawl the meaning of the Web page and the basic structure of the URL

A simple way to get started with Python encoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.