Python を使用する理由と Python クイック スタート チュートリアル

Y2J
リリース: 2017-04-18 17:58:36
オリジナル
1309 人が閲覧しました

1 なぜ Python を使用するのですか?

このようなタスクがあるとします。LAN 内のコンピューターが接続されているかどうかを単純にテストします。

アイデア: シェル プログラミングを使用します。通常、Windows はバッチ スクリプトです)。たとえば、Windows では、ping ip コマンドを使用して各マシンを順番にテストし、ping が成功するとコンソールのテキストが「Reply from...」となるためです。 "、ping が失敗した場合は "タイムアウト..." というテキストが表示されるため、結果の文字列を検索することで、マシンが接続されているかどうかを知ることができます。

実装: 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 ではネットワークの違いがあるため インターフェースの実装方法が異なるため、2 つのバージョンの関数を記述する必要があります 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の実装はより簡潔で、より速く書くことができます。また、Javaと同様に、プログラムを保存した後に直接実行することができます。

経験豊富な C/Java プログラマは、C/Java で書くほうが Python で書くよりも速いと主張するかもしれませんが、私の考えは、Java と Python の両方をマスターした後であるということです。たとえば、ローカル ファイルを使用する場合、必要なコードは 1 行だけであり、Java には多くのストリーム ラッパー クラスが必要ありません。各言語には、自然に適した独自のアプリケーションがあります。 Python を使用して、オペレーティング システムを使用した対話型プログラミングに似たいくつかの短いプログラムを処理するのが、最も時間と労力を節約できます。 Python を使用して大規模な商用 Web サイトをデザインするか、複雑なゲームをデザインするかはあなた次第です。


2 クイック スタート
2.1 Hello world


Python (私のバージョンは 2.5.4) をインストールした後、 IDLE (Python GUI) このプログラムは Python 言語インタープリターです。 記述したステートメントはすぐに実行できます。 有名なプログラム ステートメントを書き留めて、Enter キーを押します。 K&R によるプログラミングの世界。

「ファイル」--「新しいウィンドウ」を選択するか、Ctrl+N を押して新しいエディターを開きます。
print "Hello,world!"
ログイン後にコピー

.py ファイルとして保存します。 F5 を押すと、プログラムの結果が表示されます。これは 2 番目の Python 実行方法です。保存した a.py ファイルをダブルクリックすると、プログラムの結果が表示されます。これは、Java と比較して利点です。


2.2 国際的なサポート

世界に挨拶する方法を変更しましょう。 新しいエディタを作成し、次のコードを作成します。


print "Hello,world!"
raw_input("Press enter key to close this window");
ログイン後にコピー

コードを保存するとき、 Python は、ファイルの文字セットを変更するかどうかを尋ねます。結果は次のようになります。

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
ログイン後にコピー

文字セットを変更します。 使い慣れた形式に変更します。

# -*- coding: cp936 -*- 
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");
ログイン後にコピー


プログラムは引き続き正常に実行されます。


2.3 便利で使いやすい電卓


Microsoftが提供する電卓で数えるのは面倒なので、Pythonインタプリタを開いて直接計算してください:


# -*- coding: GBK -*- 
print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");
ログイン後にコピー

2.4 String、ASCII、UNICODE

次のように事前定義された出力形式で文字列を出力できます:


a=100.0
b=201.1
c=2343
print (a+b+c)/c
ログイン後にコピー

文字列にアクセスする方法は次の例を参照してください:
print """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""
ログイン後にコピー

ASCII 文字列と UNICODE 文字列の違いに注意してください:

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.5 Listの使い方
JavaのListと同様、便利で使いやすい

データ型
:

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.6 条件とループ文

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.7 関数の定義方法

# 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)
ログイン後にコピー


そして、便利で使いやすい機能をご紹介します:

# 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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!