Python 및 Python 빠른 시작 튜토리얼을 사용하는 이유

Y2J
풀어 주다: 2017-04-18 17:58:36
원래의
1320명이 탐색했습니다.

1 왜 Python을 사용하는가?

LAN에 있는 컴퓨터가 연결되어 있는지 테스트하는 작업이 있다고 가정해 보겠습니다. 이 컴퓨터의 IP 범위는 192.168.0.101에서 192.168.0.200입니다. 🎜>
아이디어: 쉘 프로그래밍을 사용하세요. (Linux는 일반적으로 bash이고 Windows는 배치 스크립트입니다.) 예를 들어 Windows에서는 ping ip 명령을 사용하여 각 머신을 차례로 테스트하고 콘솔 텍스트를 가져옵니다. 보통 ping이 성공한 경우는 "Reply from..."이고, 연결되지 않은 경우에는 "time out..."이라는 텍스트가 나오므로 결과에서 문자열을 검색하면 기기가 작동 중인지 알 수 있습니다.

구현: Java 코드 다음과 같습니다:

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();
}
로그인 후 복사

문제는 이 코드를 실행하려면 몇 가지 작업을 수행해야 한다는 것입니다. 추가 작업에는 다음이 포함됩니다.

  • 클래스 파일 작성

  • 메인 메소드 작성

  • 바이트코드로 컴파일

  • 바이트코드는 직접 실행할 수 없기 때문에 작은 bat나 bash 스크립트를 작성해서 실행해야 한다

물론 C/C++를 사용하여 이 작업을 완료할 수도 있습니다. 하지만 C/C++는 크로스 플랫폼 언어가 아닙니다. 이 간단한 예에서는 C/C++의 차이점을 확인하지 못할 수도 있습니다. 및 Java 구현이 있지만 네트워크 데이터베이스에 연결 정보 기록과 같은 좀 더 복잡한 시나리오에서는 Linux와 Windows에서 네트워크

인터페이스 의 구현 방법이 다르기 때문에 두 가지 버전의 를 작성해야 합니다. 함수 . Java Concerns에는 그런 것이 없습니다.
Python에서는 다음과 같이 동일한 작업이 구현됩니다.


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()
로그인 후 복사

Java에 비해 Python의 구현이 더 간단하고 작성 시간이 더 빠릅니다. 또한 이 프로그램은 Java와 마찬가지로 크로스 플랫폼입니다. 🎜>
경험 많은 C/Java 프로그래머는 C/Java로 작성하는 것이 Python보다 더 빠르다고 주장할 수 있습니다. 이 의견은 Java와 Python을 모두 마스터한 후에야 작성이 가능하다는 것입니다. 예를 들어, 로컬 파일을 작동할 때는 Java의 많은 스트림 래퍼 클래스가 필요 없이 한 줄의 코드만 있으면 됩니다. 각 언어에는 자연스럽게 적합한 응용 프로그램 범위가 있습니다. 운영 체제를 사용하여 대화형 프로그래밍과 유사한 일부 짧은 프로그램을 처리하는 것이



Python 응용 프로그램 시나리오
일부 쉘 프로그래밍과 같은 간단한 작업을 수행하려면 Python을 사용하여 대규모 상업용 웹사이트를 디자인하거나 복잡한 게임을 디자인하는 것이 좋습니다.



2 빠른 시작

2.1 Hello world


Python(내 버전은 2.5.4)을 설치한 후 IDLE(Python GUI)을 엽니다. 당신은 바로 실행할 수 있습니다.


print "Hello,world!"
로그인 후 복사

그리고 Enter를 누르면 K&R이 프로그래밍 세계에 소개한 유명한 말을 볼 수 있습니다. >

인터프리터에서 "파일"--"새 창"을 선택하거나 Ctrl+N 단축키를 사용하여 새 편집기를 엽니다.

print "Hello,world!"
raw_input("Press enter key to close this window");
로그인 후 복사


.py 파일입니다. F5를 누르면 프로그램의 결과를 볼 수 있습니다. Python을 실행하는 두 번째 방법입니다.

저장한 a.py 파일을 찾아 두 번 클릭해도 볼 수 있습니다. Python 프로그램을 직접 실행할 수 있다는 점이 Java에 비해 장점입니다.



2.2 국제화 지원


세상을 또 다른 방식으로 맞이해 봅시다. 새로운 편집기를 만들고 다음 코드를 작성하세요:
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
로그인 후 복사

🎜>
프로그램이 여전히 잘 실행될 때 코드를 저장하세요.


2.3 편리하고 사용하기 쉬운 계산기



Microsoft에서 제공하는 계산기를 사용하여 계산하는 것은 너무 번거롭습니다. Python 인터프리터를 열고 직접 계산을 수행합니다.

# -*- coding: cp936 -*- 
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
로그인 후 복사


2.4 문자열, ASCII 및 UNICODE


다음과 같이 사전 정의된 출력 형식으로 문자열을 인쇄할 수 있습니다.
# -*- coding: GBK -*- 
print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");
로그인 후 복사


문자열에 어떻게 액세스합니까? 다음 예를 참조하세요.


a=100.0
b=201.1
c=2343
print (a+b+c)/c
로그인 후 복사
ASCII와 UNICODE 문자열의 차이점에 유의하세요.

print """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""
로그인 후 복사


2.5 목록 사용


유사 Java에서 List를 작성하는 데 있어 편리하고 사용하기 쉬운
데이터 유형

:


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)
로그인 후 복사


2.6 조건문 및 루프문
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.7 함수 정의 방법

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
로그인 후 복사
그리고 편리하고 사용하기 쉬운 함수를 소개합니다:

# 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&#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 异常处理
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(&#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 빠른 시작 튜토리얼을 사용하는 이유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!