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 스크립트를 작성해서 실행해야 한다
인터페이스 의 구현 방법이 다르기 때문에 두 가지 버전의 를 작성해야 합니다. 함수 . 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");
🎜>
프로그램이 여전히 잘 실행될 때 코드를 저장하세요.
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'm sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
2.7 함수 정의 방법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그리고 편리하고 사용하기 쉬운 함수를 소개합니다:
# 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.
위 내용은 Python 및 Python 빠른 시작 튜토리얼을 사용하는 이유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

Inpython, "목록", isaversatile, mutablesequencetatcanholdmixeddatattypes, whilean "array"isamorememory-efficed, homogeneouseceenceRequiringElements ofthesAmeType.1) ListSareIdeAldiversEdatastorageandmanipulationDuetoIrflexibrieth

PythonlistsAndarraysareBotheBotheBothebothable.1) ListSareflexibleandsupporterogenousDatabutarabestemory-efficient.2) Arraysaremorememory-efforhomogeneousdatabutlessverstile, CorrectTypecodeusagetoavoidercer가 필요합니다.

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.
