Why Python and Python Quick Start tutorial

Source: Internet
Author: User
Why use Python? suppose we have a job: simply test whether computers in the Lan are connected. the ip addresses of these computers range from 192.168.0.101 to 192.168.0.200. & amp; nbs... 1. Why Python?

Suppose we have a task: simply test whether the computers in the Lan are connected. the ip addresses of these computers range from 192.168.0.101 to 192.168.0.200.

Idea: use shell programming. (Linux is usually bash, while Windows is a batch processing script ). for example, in Windows, ping the ip command to test each machine in sequence and obtain the console output. the console text is usually "Reply from... "The text is" time out... ", so you can find the string in the result to know whether the machine is connected.

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
 
  


This code runs well. The problem is that you need to do some additional work to run this code. the additional work includes:

  • Compile a class file

  • Compile a main method

  • Compile it into byte code

  • Because the byte code cannot be run directly, you need to write a little bat or bash script to run it.

Of course, C/C ++ can do the same job. however, C/C ++ is not a cross-platform language. in this simple enough example, the differences between C/C ++ and Java implementations may not be seen, but in some more complex scenarios, for example, you need to record the connected information to the network database. because the network interfaces of Linux and Windows are implemented in different ways, you have to write two function versions. there is no such concern when using Java.

The same work is implemented in Python as follows:

Import subprocesscmd = "cmd.exe" begin = 101end = 200 while begin
   
    


Compared with Java, Python is more concise and faster. you do not need to write the main function, and the program can be directly run after being saved. in addition, Python is also cross-platform like Java.

Experienced C/Java programmers may argue that writing in C/Java is faster than writing in Python. this is a matter of opinion. my idea is that when you master both Java and Python, you will find that writing such programs using Python is much faster than Java. for example, when operating a local file, you only need a line of code instead of many Java stream packaging classes. various languages have their own natural application scopes. using Python to process some short programs, similar to interactive programming with the operating system, saves the most time and effort.

Python application scenarios

Simple enough tasks, such as shell Programming. if you prefer to use Python to design large commercial websites or complex games, just listen to them.

2 Quick Start 2.1 Hello world

After installing Python (my local version is 2.5.4), open IDLE (Python GUI). This program is a Python interpreter and the statements you write can be run immediately. let's write down a famous program statement:

print "Hello,world!"


Press enter to see the famous saying that K & R has been introduced to the program world.

Select "File" -- "New Window" in the interpreter or press Ctrl + N 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 file. press F5 to see the program running result. this is the second Python running method.

Find the. py file you saved and double-click it. you can also see the program result. the Python program can run directly. this is an advantage over Java.

2.2 International support

We try to greet the world in another way. create an editor and write the following code:

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

When saving the code, Python prompts you whether to change the character set of the file. 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 a more familiar form:

#-*-Coding: GBK-*-print "Welcome to the Olympic Games China! "# Chinese example raw_input (" Press enter key to close this window ");


The program runs well.

2.3 easy-to-use calculator

It is too much trouble to use the calculator that comes with Microsoft to count. open the Python interpreter and perform computation directly:

a=100.0b=201.1c=2343print (a+b+c)/c
2.4 String, ASCII, and UNICODE


The predefined output format string can be printed as follows:

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


How is a string accessed? See this example:

word="abcdefg"a=word[2]print "a is: "+ab=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 charactersl=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 Use List

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

word=['a','b','c','d','e','f','g']a=word[2]print "a is: "+ab=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 two elements.i=word[:-2]print "i is: "print i # Everything except the last two charactersl=len(word)print "Length of word is: "+ str(l)print "Adds new element"word.append('h')print word
2.6 condition and loop statements
# Multi-way decisionx=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 Lista = ['cat', 'window', 'defenestrate']for x in a:    print x, len(x)
2.7 how to define functions
# Define and invoke function.def sum(a,b):    return a+bfunc = sumr = func(5,6)print r# Defines function with default argumentdef add(a,b=2):    return a+br=add(1)print rr=add(1,5)print r


In addition, we will introduce a convenient and easy-to-use function:

# The range() functiona =range(5,10)print aa = range(-2,-7)print aa = range(-7,-2)print aa = range(-2,-11,-3) # The 3rd parameter stands for stepprint a
File I/O 2.8
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 for readingfor line in f:    print linef.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 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!"
2.10 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 Baseclass Child(Base):    def plus(self,a,b):        return a+boChild =Child()oChild.add("str1")print oChild.dataprint oChild.plus(2,3)
2.11 package mechanism

Each. py file is called a module, and modules can be imported to each other. See the following example:

# a.pydef add_func(a,b):    return a+b
# b.pyfrom a import add_func # Also can be : import aprint "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"



The module can be defined in the package. the Python definition package method is a little odd. Suppose we have a parent folder, which has a child subfolder. child has a module. py. how to let Python know the file hierarchy? It is very simple. Each directory is named _Init_. Py file. the file content can be blank. the hierarchical structure is as follows:

parent   --init_.py  --child    -- init_.py    --a.pyb.py


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

import sysprint sys.path


Generally, we can put the module package path in the environment variable PYTHONPATH, which will be automatically added to sys. path attribute. another convenient method is to specify the module path directly to sys in programming. path:

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

You will find this tutorial quite simple. many Python features are implicitly proposed in code. These features include: Python does not need to explicitly declare data types, keyword descriptions, and interpretation of string functions. I think a skilled programmer should have a good understanding of these concepts, so that after you take an hour to read this short tutorial, you can get familiar with Python as soon as possible through the existing knowledge migration analogy, then start programming with it as soon as possible.

Of course, learning Python in an hour is quite a bit of a favor. specifically, programming languages include syntax and standard libraries. the syntax is equivalent to the martial arts trick, while the practical experience of the standard library is similar to internal strength and requires long-term exercise. python has learned the advantages of Java and provides a large number of easy-to-use standard libraries for programmers to "take things ". (This is also the reason for Python's success). at the beginning, we saw an example of how Python calls Windows cmd. in the future, I will try my best to write the usage of each standard library and some application skills, let everyone really master Python.

The above is the details of the Quick Start tutorial on Python and Python. For more information, see other related articles in the first PHP community!

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.