>  기사  >  백엔드 개발  >  Python 입문 튜토리얼: 1시간 안에 Python을 자세히 배워보세요_python

Python 입문 튜토리얼: 1시간 안에 Python을 자세히 배워보세요_python

不言
不言원래의
2018-05-30 14:50:281611검색

이 글은 경험 많은 프로그래머들이 하루라도 빨리 Python의 세계에 입문하기 적합한 글입니다. 특히, Java와 Javascript를 마스터한다면 1시간 이내에 Python으로 유용한 Python 프로그램을 빠르고 원활하게 작성할 수 있습니다.

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++와 Java 구현 사이에 차이가 없다는 것을 알 수 없지만 네트워크 데이터베이스에 연결 정보를 기록하는 것과 같은 좀 더 복잡한 시나리오에서는 볼 수 없습니다. Linux와 Windows의 인터페이스 구현 방법이 다르기 때문에 두 가지 기능 버전을 작성해야 합니다. Java에서는 그런 우려가 없습니다.
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의 구현이 더 간단하고 작성 시간이 더 빨라집니다. main 함수를 작성할 필요가 없으며 이 프로그램은 저장 후 바로 실행될 수 있습니다. 또한 Python도 Java와 마찬가지로 크로스 플랫폼입니다.
숙련된 C/Java 프로그래머는 다음과 같이 주장할 수 있습니다. C/Java로 작성하는 것이 Python으로 작성하는 것보다 빠릅니다. 내 생각은 Java와 Python을 모두 마스터하면 Python으로 작성하는 것이 Java에서 작성하는 것보다 훨씬 빠르다는 것입니다. , 로컬 파일을 작동할 때 한 줄의 코드만 필요하며 Java에서는 많은 스트림 래퍼 클래스가 필요하지 않습니다. 각 언어에는 고유하게 적합한 응용 프로그램 범위가 있습니다. Python을 사용하여 운영 체제를 사용한 대화형 프로그래밍과 유사한 일부 짧은 프로그램을 처리합니다.

Python 애플리케이션 시나리오

일부 셸 프로그래밍과 같은 작업이 충분히 간단합니다. Python을 사용하여 대규모 상업용 웹사이트나 복잡한 게임을 디자인하는 것을 좋아한다면 선택은 여러분에게 달려 있습니다. Quick Start

2.1 Hello world


Python(내 버전은 2.5.4)을 설치한 후 IDLE(Python GUI)을 열면 이 프로그램은 Python 언어 해석기이며 작성한 명령문을 즉시 실행할 수 있습니다. 유명한 프로그램 설명:

print "Hello,world!"

을 누르고 Enter를 누르면 K&R의 유명한 인용문이 프로그래밍 세계에 소개된 것을 볼 수 있습니다.

"파일"-"새 창"을 선택하거나 통역사에서 단축키 Ctrl+N을 엽니다.


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

a.py 파일로 저장하고 F5 키를 누르면 프로그램 실행 결과를 볼 수 있습니다.

a.py 파일을 찾으세요. 저장하고 더블클릭하면 프로그램 결과도 볼 수 있어요. Python 프로그램을 바로 실행할 수 있다는 점이 장점이죠.


2.2 국제화 지원

세상을 다르게 맞이해보세요. 새 편집기를 열고 다음 코드를 작성하세요.

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

코드를 저장하면 Python에서 파일을 변경할지 여부를 묻는 메시지가 표시됩니다. 문자 집합, 결과는 다음과 같습니다.

# -*- coding: cp936 -*- 

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

문자 집합을 좀 더 친숙한 문자 집합으로 변경합니다. form:

# -*- coding: GBK -*- 

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

프로그램은 여전히 ​​잘 돌아갑니다.


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


Microsoft에 포함된 계산기를 사용하세요. 컴퓨터를 사용하여 계산하기에는 너무 번거롭습니다. :

a=100.0
b=201.1
c=2343
print (a+b+c)/c

2.4 문자열, ASCII 및 UNICODE

다음과 같이 미리 정의된 출력 형식으로 문자열을 인쇄할 수 있습니다.

print """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

액세스된 문자열은 무엇입니까? 다음 예를 참조하세요.

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)

차이점에 유의하세요. ASCII와 UNICODE 문자열 사이:

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 List 사용


Java의 List와 유사하며 편리하고 사용하기 쉬운 데이터 유형입니다.

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 조건문 및 루프 문

# 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 방법 함수 정의
# 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
그리고 편리하고 사용하기 쉬운 함수를 소개합니다:

# 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 파일을 모듈이라고 하며, 모듈은 서로를 가져올 수 있습니다. 다음 예를 참조하세요.

# 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入门教程



위 내용은 Python 입문 튜토리얼: 1시간 안에 Python을 자세히 배워보세요_python의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.