Table of Contents
Python application scenarios
2 Quick Start" >2 Quick Start
2.1 Hello world
2.2 International support
2.3 Convenient and easy-to-use calculator
2.4 String, ASCII and UNICODE
2.5 Using List
2.6 Conditional and loop statements
2.7 How to define functions
2.8 文件I/O
异常处理" >2.9 异常处理
2.10 类和继承
2.11 包机制
总结
Home Backend Development Python Tutorial Why use Python and Python quick start tutorial

Why use Python and Python quick start tutorial

Apr 18, 2017 pm 05:58 PM
python Getting Started Tutorial

1 Why use Python?

Suppose we have such a task: simply test whether the computers in the LAN are connected. The IP range of these computers is from 192.168.0.101 to 192.168.0.200.

Idea: Use shell programming. (Linux is usually bash and Windows is batch script). For example, on Windows, use the ping ip command to test each machine in turn and get the console output. Because the console text is usually when the ping succeeds It is "Reply from...". When it is not connected, the text is "time out...". Therefore, by searching the string in the result, you can know whether the machine is connected.

Implementation: Java code 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();
}
Copy after login


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

  • Write a class file

  • Write a main method

  • Compile it into byte code

  • Since byte code cannot be run directly, you need to write a small bat or bash script to run it.

Of course, use C/C++ can also complete this work. But C/C++ is not a cross-platform language. In this simple enough example, you may not be able to see the difference between C/C++ and Java implementation, but in some more complex scenarios, such as Record the connectivity information to the network database. Due to the different implementation methods of the network interface between Linux and Windows, you have to write two versions of the function. There is no such thing in Java Concerns.

The same work is implemented 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 after login


Compared with Java, Python’s implementation is simpler and your writing time is faster. You There is no need to write the main function, and the program can be run directly after saving. In addition, like Java, Python is also cross-platform.

Experienced C/Java programmers may argue that writing in C/Java It will be faster to write than Python. This opinion has different opinions. My idea is that after you master both Java and Python, you will find that writing such programs in Python will be much faster than Java. For example, when operating local files, you only need to One line of code without the need for Java's many stream wrapper classes. Each language has its own naturally suitable application range. Using Python to process some short programs similar to interactive programming with the operating system is the most time-saving and labor-saving.


Python application scenarios

Simple enough tasks, such as some shell programming. If you like to use Python to design large commercial websites or design complex games, you are welcome.


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 language interpreter. The statements you write can be run immediately. Let’s write down a famous program statement:

print "Hello,world!"
Copy after login


and press Enter. You will see this famous saying introduced to the programming world by K&R.

Select "File"--"New Window" in the interpreter or shortcut Ctrl+N , open a new editor. Write the following statement:

print "Hello,world!"
raw_input("Press enter key to close this window");
Copy after login


Save it as a.py file. Press F5, you can see the results of the program. This is Python The second way to run.

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


2.2 International support

Let’s greet the world in a different way. Create a new editor and write the following code:

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
Copy after login

Save the code after you , Python will prompt you whether to change the character set of the file. The result is as follows:

# -*- coding: cp936 -*- 
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
Copy after login


Change the character set to a more familiar form:

# -*- coding: GBK -*- 
print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");
Copy after login


The program still runs well.


2.3 Convenient and easy-to-use calculator

It is too troublesome to count with the calculator provided by Microsoft .Open the Python interpreter and perform calculations directly:

a=100.0
b=201.1
c=2343
print (a+b+c)/c
Copy after login

2.4 String, ASCII and UNICODE


You can print out the string in the predefined output format as follows :

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


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 # 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 after login

Please 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&#39;m sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
Copy after login

2.5 Using List

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

word=[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;]
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 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(&#39;h&#39;)
print word
Copy after login

2.6 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 = [&#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]
for x in a:
    print x, len(x)
Copy after login

2.7 How to define functions
# 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 after login


And, introduce a convenient and easy-to-use 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 after login

2.8 文件I/O
spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn&#39;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()
Copy after login

2.9 异常处理
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 after login

2.10 类和继承
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 after login

2.11 包机制

每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

# a.py
def add_func(a,b):
    return a+b
Copy after login
# 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 after login



module可以定义在包里面.Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:

parent 
  --init_.py
  --child
    -- init_.py
    --a.py
b.py
Copy after login


那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

import sys
print sys.path
Copy after login


通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

import sys
sys.path.append(&#39;D:\\download&#39;)
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 after login

总结

    你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.我认为一个熟练的程序员应该对这些概念相当了解,这样在你挤出宝贵的一小时阅读这篇短短的教程之后,你能够通过已有知识的迁移类比尽快熟悉Python,然后尽快能用它开始编程.

    当然,1小时学会Python颇有哗众取宠之嫌.确切的说,编程语言包括语法和标准库.语法相当于武术招式,而标准库应用实践经验则类似于内功,需要长期锻炼.Python学习了Java的长处,提供了大量极方便易用的标准库供程序员"拿来主义".(这也是Python成功的原因),在开篇我们看到了Python如何调用Windows cmd的例子,以后我会尽量写上各标准库的用法和一些应用技巧,让大家真正掌握Python.

The above is the detailed content of Why use Python and Python quick start tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

See all articles