Why say "life is short, I use Python"

Source: Internet
Author: User
Tags python script

Why say "life is short, I use Python"?

    • Why is life so short, I use Python
      • Question
        • 1 What is Python
        • 2 Why do people use Python
        • 3 is Python a scripting language?
      • Python version Hello World
      • Example
        • 1 Python
        • 2 Java

This article is not a big sermon, just introduce the background of Python, and then from a practical point of view to lift one or two real chestnuts.

First of all want to understand the good or bad of a language, or why programmers like (crouching Groove, the original programmer like not a girlfriend?) We start with the background of the language, for example, when he appeared in the era, in order to solve problems and so on. Of course, I just do a comparison with other languages, do not discuss who is good who is bad, say that the language also has no bad points, even if there are good or bad points, but also from the actual application scenario, all of us do not discuss this issue.

All right, all right, Big Brother, you all have to cool off, above I pull too much, the following directly on the point ...

1. Question

First of all, it is customary to come up with a few questions, so that beginners can be at a glance, there is a general understanding

What is 1.1 python?

is an object-oriented, interpreted computer programming language, by Guido van Rossum in 1989 Christmas to pass the boredom of time, and developed a new script interpreter, can feel what is called cattle, is an inheritance of ABC language, as to why the selection of Python as the language name , because he was a fan of a comedy group called Monty Python, the first public release to be released in 1991.

His philosophy of design is

    • Elegant
    • Clear
    • Simple

Completely object-oriented. Functions, modules, numbers, strings are objects, do not want Java also have basic type, in Python all objects, that as programmers we are afraid to find objects, directly new one Ah, hehe

1.2 Why do people use Python

This question is often the first question for the starter, and I found this answer in a book:

Software Quality
Develop this efficiency
Portability of programs
Many standard library support
Component integration
Enjoy the fun

Other needless to say, need detailed understanding of can search under, I just provide you a few aspects let everybody understand, because often for beginners, is confused, because do not support from what direction to understand a thing, and I just provide direction, concrete everyone can understand. I only say the last one, detailed can refer to this article each programmer should learn to use Python or ruby article inside also said very clearly, I summed up the points are

    • Small amount of code
    • Low maintenance costs
    • High programming efficiency

The same problem, in different languages, the code gap is too much, in general, Python is Java 1/5, so the number is too short, I use Python, more time to bubble sister, or old

1.3 Python a scripting language?

·
He is a multi-user language, as to why everyone's first feeling is the scripting language, I am because people look at him directly write a file, do not need to compile, with the script like, directly run on the line. So it's hard for me to give you a definite answer, I'll cite some common application scenarios:

    • Script: Can write some of the scripts to open their own, for example, Android development, will involve a common command, but if it is written in Windows with bat, so that the Mac can not run, so it is possible to use, Python write. In addition, if you are a server administrator, then the Python script is very suitable for you, the program has long been written in bash, you will hit the computer
    • Website development: He has a strong django,flask framework
    • Scientific calculation: NumPy and Matlab are as strong as the numerical computing interface
    • Graphical Interface Program development: This does not have much to explain, is the common kind of interface
2. Python version Hello World

Usually any language has a Hello world process, hehe, so we also here, because through him you will learn the language of a most basic program framework and running process, which corresponds to beginners is the most important.

Now that we have said it, we can take him as a scripting language, so we'll get the simplest one, the following steps:

    1. Create a hello.py file in your working directory, don't ask me you don't know what the working directory is, then you should learn the basics of computer.

    2. Write in this file

print‘hello world‘
    1. Open the command line and enter:
python hello.py

Well you will see Hello world output, is not feeling good simple, yes, you have not read wrong, so simple, now you can say you are a Python programmer, hehe ~

3. Example

Here is an example of my recent practical application, what is it, donor urgent, listen to the flat monk slowly arrived. The scene is such that the recent diary of the software itself is not available to the client, but the data in the SQLite database Ah, our demand is to export some of the data into a TXT file, how this needs simple

3.1 Python

First use Python to solve this problem, according to the above description, we clearly think of the following steps:

    1. Connecting the Sqlite3 Database
    2. Execute Query statement
    3. Open File
    4. Writes the interface of the query to the file that was just opened
    5. Close data
    6. Close File

Oh, I have thought, let the programmer put the elephant in the refrigerator story, can refer to this article drag and drop trilogy-from "Put the elephant in the refrigerator" talking about

Okay, no more nonsense, just on the code.

#!/usr/bin/python#-*-coding:cp936-*-ImportSqlite3ImportHtmlparserImportCodecsImportTimef=codecs.open (' Note.txt ',' A ',"Utf-8")#以追加方式打开一个文件conn = Sqlite3.connect (' note.db ')#打开sqlite数据库Print "opened database successfully";#执行查询语句, return a cursorcursor = Conn.execute ("Select Created,weather,address,latitude,longitude,content from Tb_notescontents,tb_notes where tb_ Notescontents.note_guid=tb_notes.guid ")#遍历每一行 forRowinchCursor#取出改行的每一列Created= row[0] Weather= row[1] address= row[2] Latitude= row[3] Longitude= row[4] Content= row[5] Html_parser = Htmlparser.htmlparser () d = time.localtime (created/ +) CurrentTime = Time.strftime ('%y-%m-%d%h:%m:%s ', d)#因为原理的内容是经过html转义了, so to turn back, shaped like:& #20170;& #22825;& #65292;Weather = Html_parser.unescape (weather) address = Html_parser.unescape (address) content = Html_parser.unescape (con Tent) F.write (currenttime)#写入文件F.write ("') F.write (weather) F.write ("') F.write (address) F.write ("') F.write (content) F.write (' \ n ') F.write (' \ n ') F.write (' \ n ') Conn.close ()# # Close the databaseF.close ()#关闭文件Print "Operation done successfully";

As for the logic, I also write very clearly in the above steps, the other program also thanks to the very detailed comments, so that even if you do not understand Python can easily read.

You can see that we've done it in about 50 lines of code, but what if it's a Java result?

3.2 Java

First of all we find a development tool, on Eclipse Bar. Create a project, and then add a Testman.java

The engineering structure is as follows:

Write a basic program framework in Testman.java

publicclass TestMain {    publicstaticvoidmain(String[] args) {    }}

Lying trough, so troublesome, engaged in a long way to put the shelves, to tell the truth Java is really good, do you have to follow his that set, so say, we can not directly paste the code, the steps have to be subdivided, what?

    1. Connecting the Sqlite3 Database
      Through the JDBC Connection: But because JDBC (Java Data Base Connectivity,java database connection) is a set of abstract design APIs for the Java Connection database, since it is abstract, it cannot be used directly, to find his implementation, Since is connected to SQLite so should go to SQLite official website or download from BitBucket here, I downloaded the version is sqlite-jdbc-3.8.11.2, downloaded after he put into the environment variables eclipse, download before the preparation work done, the following began to write code
    2. Execute Query statement
    3. Open File
    4. Writes the interface of the query to the file that was just opened
    5. Close data
    6. Close File

Now we're going straight to the code.

ImportJava.io.BufferedWriter;ImportJava.io.FileWriter;ImportJava.io.IOException;ImportJava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;ImportJava.sql.SQLException;ImportJava.sql.Statement;ImportOrg.apache.commons.lang3.StringEscapeUtils; Public  class testmain {     Public Static void Main(string[] args) {//Load the SQLITE-JDBC driver using the current class loaderConnection Connection =NULL; BufferedWriter BufferedWriter =NULL;Try{Class.forName ("Org.sqlite.JDBC");//Create a database connectionConnection = Drivermanager.getconnection ("Jdbc:sqlite:note.db");            Statement Statement = Connection.createstatement (); Statement.setquerytimeout ( -);//Set Timeout to + sec.ResultSet rs = statement. ExecuteQuery ("Select Created,weather,address,latitude,longitude,content from Tb_notescontents,tb_notes where tb_ Notescontents.note_guid=tb_notes.guid "); BufferedWriter =NewBufferedWriter (NewFileWriter ("Note.txt",true)); while(Rs.next ()) {//Read the result setString created = rs.getstring ("Created"); String weather = rs.getstring ("Weather"); String address = rs.getstring ("Address"); String latitude = rs.getstring ("Latitude"); String Longitude = rs.getstring ("Longitude"); String content = rs.getstring ("Content");//write to fileBufferedwriter.write (created);//write fileBufferedwriter.write ("              ");                Bufferedwriter.write (weather); Bufferedwriter.write ("              ");                Bufferedwriter.write (address); Bufferedwriter.write ("              ");//Escape HTML, you can see that we have also referenced the Commons-lang jar packageContent = STRINGESCAPEUTILS.UNESCAPEHTML4 (content);                Bufferedwriter.write (content);            Bufferedwriter.newline (); }        }Catch(SQLException e) {//If the error message is ' Out of memory ',            //It probably means no database file is foundSystem.err.println (E.getmessage ()); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }finally{Try{if(Connection! =NULL) Connection.close (); }Catch(SQLException e) {//Connection close failed.System.err.println (e); }Try{if(BufferedWriter! =NULL) {bufferedwriter.close (); }            }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }    }}

Now you can see the difference between Java and Python, what functionality in Java is also provided, but to refer to a variety of jars, but also to search everywhere to find or download, all kinds of ken, but in Python a lot of common libraries have built-in, so save a lot of trouble, so I personally feel , Python is suitable for solving some small problems in the work, of course, the big problem is also the problem of the ~, the article basically ended, of course, I did not take sides that side, but also I am just from my work or study to get some small comprehension here, if you have any good ideas welcome comments on the Groove ~

Thank:
Java Connection SQLite Reference: http://blog.csdn.net/litaoshoujiao/article/details/8535444
commom-lang:http://commons.apache.org/proper/commons-lang/download_lang.cgi

Why say "life is short, I use Python"

Related Article

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.