Why use Python and Python quick start tutorial

Y2J
Release: 2017-04-18 17:58:36
Original
1295 people have browsed it

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
        
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 networkinterfacebetween Linux and Windows, you have to write two versions of thefunction. 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
        
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'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-usedata 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 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('h') 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 = ['cat', 'window', 'defenestrate'] 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'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('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(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!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!