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(); }
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()
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!"
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");
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");
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");
Change the character set to a more familiar form:
# -*- coding: GBK -*- print "欢迎来到奥运中国!" # 使用中文的例子 raw_input("Press enter key to close this window");
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
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'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=['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
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)
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
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 文件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()
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!"
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)
2.11 包机制
每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:
# 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('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)
总结
你会发现这个教程相当的简单.许多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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version
