Home  >  Article  >  Backend Development  >  Python introductory tutorial: Learn Python in 1 hour in detail_python

Python introductory tutorial: Learn Python in 1 hour in detail_python

不言
不言Original
2018-05-30 14:50:281610browse

This article is suitable for experienced programmers to enter the world of Python as soon as possible. In particular, if you master Java and Javascript, you can quickly and smoothly write useful Python programs in Python in less than an hour.

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 usually It is bash and Windows is a batch script). For example, on Windows, use the ping ip command to test each machine in sequence and get the console output. Because the console text is usually "Reply from..." when the ping succeeds, it does not work. The text is "time out...", so by searching the string in the result, you can 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<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 paragraph The code runs fine, the problem is that in order to run this code, you need to do some extra work. This extra work includes:

  • Write a class file

  • Write a main method

  • Compile it into byte code

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

Of course, this work can also be done with C/C++. But C/C++ is not 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 recording connectivity information to a network database. Due to the network differences between Linux and Windows The interface implementation is different, and you have to write two versions of the function. There is no such concern in Java.
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()

Comparing the implementation of Java and Python It’s more concise, and you write faster. You don’t need to write the main function, and the program can be run directly after saving it. In addition, like Java, Python is also cross-platform.
Experienced C/Java programmers It may be argued that writing in C/Java is faster than writing in Python. This point of view has different opinions. My idea is that when you master both Java and Python, you will find that writing such programs in Python will be much faster than in Java. .For example, when operating local files, you only need one line of code and do not need many stream wrapper classes in Java. Various languages ​​​​have their naturally suitable application ranges. Using Python to process some short programs is the most time-saving work similar to interactive programming with the operating system. Effort-saving.

Python application scenarios

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

2 Quick Start

2.1 Hello world

After installing Python (my version is 2.5.4), open IDLE (Python GUI), the program is Python language interpreter, the statement you write can be run immediately. We write down a famous program statement:

print "Hello,world!"

and press Enter. You can see this sentence introduced into the programming world by K&R Famous quotes.
Select "File"--"New Window" or shortcut Ctrl+N in the interpreter to open a new editor. Write the following statement:

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

Save It is a.py file. Press F5 and you can see the running results of the program. This is the second running method of Python.
Find the a.py file you saved and double-click. 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 another way. Create a new editor and write the following code:

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

When you save the code, 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");

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

# -*- coding: GBK -*- 

print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");

The program also runs well.

2.3 Convenient and easy-to-use calculator

Use the calculator provided by Microsoft Counting is too troublesome. Open the Python interpreter and calculate directly:

a=100.0
b=201.1
c=2343
print (a+b+c)/c
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
"""

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)

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);
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
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)
2.7 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

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

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

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 Classes 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)
2.11 Package mechanism

Each .py file is called a module, and modules can interact with each other Import. Please see the following example:

# 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(1,2)    # If using "import a" , then here should be "a.add_func"

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

parent 
  --__init_.py
  --child
    -- __init_.py
    --a.py

b.py

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

import sys

print sys.path

    通常我们可以将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)

总结

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

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

    但不管怎样,至少你现在会用Python代替繁琐的批处理写程序了.希望那些真的能在一小时内读完本文并开始使用Python的程序员会喜欢这篇小文章,谢谢!

相关推荐:

python入门教程之列表操作

一篇不错的Python入门教程

简洁的十分钟Python入门教程



The above is the detailed content of Python introductory tutorial: Learn Python in 1 hour in detail_python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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