Python 入門チュートリアル: 1 時間で Python を学ぶ、detail_python

不言
リリース: 2018-05-30 14:50:28
オリジナル
1624 人が閲覧しました

この記事は、経験豊富なプログラマーができるだけ早く Python の世界に入るのに適しており、特に Java と Javascript をマスターすれば、Python で便利な Python プログラムを 1 時間以内に迅速かつスムーズに作成できます。

次のようなタスクがあるとします。LAN 内のコンピューターが接続されているかどうかをテストします。これらのコンピューターの IP の範囲は 192.168.0.101 から 192.168.0.200 です。
アイデア: シェル プログラミングを使用します (通常、Linux は bash です。たとえば、Windows で ping ip コマンドを使用して、各マシンを順番にテストし、コンソールの出力を取得します。これは、ping が成功した場合のコンソールのテキストは通常​​「Reply from...」であり、テキストは「time」です。 out..." 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++ と 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 関数を記述する必要がなく、プログラムは Java と同様にクロスプラットフォームです。

経験豊富な C/Java プログラマーは、 C/Java で書いたほうが Python で書くよりも速いと主張する人もいますが、この考え方はさまざまです。Java と Python の両方をマスターすると、そのようなプログラムを Java で書くよりも Python で書く方がはるかに高速になるということです。たとえば、ローカル ファイルを操作する場合、必要なコードは 1 行だけであり、Java では多くのストリーム ラッパー クラスは必要ありません。各言語には、Python を使用して対話型プログラミングと同様の短いプログラムを処理するための、独自の適切なアプリケーション スコープがあります。


Python アプリケーション シナリオ

Python を使用して大規模な商用 Web サイトや複雑なゲームをデザインするのが好きなら、それはあなた次第です。
2 クイックスタート

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 ファイルとして保存します。これは、Python を実行する 2 番目の方法です。保存したファイルをダブルクリックして、プログラムの結果を確認することもできます。Java と比較して、これは利点です。

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

文字セットを変更します。私たちがよく知っているフォーム:


# -*- coding: GBK -*- 

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

プログラムは今でも問題なく動作します


2.3 便利で使いやすい電卓


マイクロソフトに付属の電卓を使用します コンピューターを使って数えるのは面倒です。 Python インタープリタを使用して直接計算します:

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。


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 を学ぶ、detail_pythonの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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