Pythonの基本構文(例付き)
Pythonは「Cファミリー」の言語に似ていますが、いくつかの重要な違いと独自のプロパティがあります。
Pythonと、CやSTなどの言語との最も明らかな構文上の違いは、Pythonパーサーがインデントによってブロック構造を認識することです。ありません BEGIN/END
または中かっこ {}
のブロックを識別するために IF/ELSE
条件、 FOR
と WHILE
ループ、または関数。
コメントはで始まります #
行の終わりまで延長します。ソースコードの1行目と2行目には、ファイルのエンコードを宣言するための特別なマーカーを設定できます。 ASCII文字が不要な場合は、エンコーディングとしてUTF-8を使用することをお勧めします。
デバッグの目的で、 print
簡単に出力できます。とともに %
演算子、C関数と同様の機能を実現します printf()
。出力はのメッセージビューに表示されます CODESYS。
print
# encoding:utf-8 # defining a function with the parameter i def do_something(i): # if branch if i>0: print("The value is: %i" % i) sum += i print("The new sum is: %i" % sum) # else if (optional, there can be none or several elif branches) elif i=0: print("The sum did not change: %i" % sum) # and the final else branch (also optional). else: handle_error() # an endless while loop while True: print("I got stuck forever!")
同じブロックに属するものはすべて、同じ距離でインデントする必要があります。インデントのサイズは関係ありません。角かっこや中かっこなどの要素は、くぼみよりも優先されます。したがって、次のコードセグメントは、「貧弱なプログラミングスタイル」で記述されている場合でも、完全に正しいものです。
# warning: bad style below. Kids, don't try this at home! if foo >= bar: print("foobar") else: print( "barfoo" )
あいまいさを避けるために、ファイル内でタブとスペースを混在させないでください。
ヒント
現時点では、Python3でタブとスペースを混在させることは構文エラーと見なされます。
公式のPythonスタイルガイドでは、4つのスペースのインデントを推奨しており、良いスタイルと悪いスタイルの例がいくつか含まれています。 Pythonチュートリアルでは、コーディングスタイルの概要を説明しています。
Pythonは「大文字と小文字を区別」し、Cと同様であり、STとは対照的です。などのキーワード def
、 if
、 else
、 と while
、小文字である必要があります(STルールとは対照的に:キーワードは大文字です)。 「i」や「I」などの2つの識別子も、2つの異なる変数を識別します。
次のキーワードはPythonで予約されており、変数や関数などの識別子として使用することはできません。 and | as | assert | break | class | continue | def | del | elif | else | except | exec | finally | for | from | global | if | import | in | is | lambda | not | or | pass | print | raise | return | try | while | with | yield
。
Python 3は、他に4つのキーワードを定義しました。 False | None | True | nonlocal
。最初の3つは本当に新しいものですが、最初の3つはPython 2ですでに事前定義された定数であり、他の目的には使用しないでください。
詳細については、以下を参照してください。 Pythonスタイルガイド と Pythonチュートリアル
変数とデータ型
Pythonは強力な動的型付け言語であり、すべての型情報は実行時に評価されます。変数はオブジェクトへの参照を保持し、オブジェクトは変数ではなくそのタイプを認識します。プログラマーが不可能な操作(整数と文字列の追加など)を実行しようとすると、Pythonは実行時に例外をスローします。
したがって、変数とその型の宣言はありません。 Pythonでは、変数はそれらに値を割り当てるためにのみ作成されます。これは、型が強く静的であるCとSTでは完全に異なります。すべての変数は型で宣言され、コンパイル時にコンパイラは型と演算子が許可されていることを確認します。
変数の処理については、次の例を参照してください。
# assign the integer 1 to the variable i (also "creates" the variable") i = 1 # assign the string "foobar" to the variable s s = "foobar" # Add 5 to the integer i - this is equivalent to i = i + 5 i += 5 # i now holds the integer 6. # Try to add i and s - this will throw an exception when executed # TypeError: unsupported operand type(s) for +: 'int' and 'str' result = i + s # variables can also be "undeclared" by deleting them. # Further access to the variable i will throw a NameError exception, # as the variable does not exist any more. del i i += 5 # now throws an exception: NameError: name 'i' is not defined
既存のすべての変数は1つの値のみを参照します。 Pythonには、割り当てられていない変数や初期化されていない変数はありません。値がないことを表すために、Pythonは特別なオブジェクトを提供します。 None
。 CまたはSTでは、nullポインターを使用します。その唯一の目的は「ここには価値がない」ことを表現することですが None
実際にはクラスの既存のインスタンスです NoneType
。
数値タイプと浮動小数点
IECまたはCの数十の整数型とは対照的に、Pythonには1つの整数型しかありません。 Pythonの整数型のサイズは固定されていません。代わりに、それらは必要に応じて大きくなり、使用可能なメモリによってのみ制限されます。
Integers.py
from __future__ import print_function i = 1 print(i) j = 0x1234 # hex number, is 16#1234 in IEC and 4660 in decimal k = 0o123 # octal number, is 8#123 in IEC and 83 decimal l = 0b101010 # binary number, is 2#101010 in IEC and 42 in decimal print(j, k, l) m = (2 + 3)*10 # k is 50 now print(m) n = 10 ** 100 # 10 to the power of 100 print(n)
結果の出力:

Pythonには、IECデータ型に類似した浮動小数点型が1つだけあります。 LREAL
。 64ビットIEEE浮動小数点演算を提供します。
構文は、ほとんどの場合、Cベースの言語に似ています。
# A simple float... a = 123.456 # A float containing the integral value 2 b = 2. # Leading zeroes can be left off c = .3 # same as 0.3 # Exponential / scientific representation d = -123e-5
2つの特別なケースは True
と False
、ブール真理値を定義する2つの定数。それらは整数値と同様に動作します 0
と 1
、文字列に変換されて名前を返す場合を除きます。
Booleans.py
# booleans behave like integers, except when converted to strings. # The built-in function "type" can be used to query the type of a value. print("True: ", True, type(True)) print("False: ", False, type(False)) print("1: ", 1, type(1)) print("False + 0: ", False + 0, type(False + 0)) print("True * 5: ", True * 5, type(True * 5))
結果の出力:

文字列
IronPythonでは、文字列は常にUnicodeで任意の長さです。それらが囲まれていても違いはありません '
また "
。文字列には三重引用符を付けることもできます """
また '''
、複数行の文字列リテラルを使用できます。
Cと同様に、バックスラッシュ文字を使用して特殊文字を除外できます。比較として、ドル記号($
)は、この目的のためにIECで使用されます。
バックスラッシュの他のルールを持つ生の文字列もあります。これは、文字列に文字通りの円記号が必要な場合に実用的です。例:Windowsファイルパスまたは正規表現。
Strings.py
# encoding:utf-8 from __future__ import print_function a = "a simple string" b = 'another string' c = "strings may contain 'quotes' of the other type." d = "multiple string literals" ' are concatenated ' '''by the parser''' e = "Escaping: quotes: \" \' backslash: \\ newline: \r\n ascii code: \x40" f = """triple-quoted strings may contain newlines, "single" 'quotes' and '''multiquotes''' of the other type""" g = "Üňíçǿđȩ is also possible: 北京, Москва, Αθήνα, القاهرة" h = r"c:\raw\strings\retain\backslashes.txt" # we iterate over a sequence of all the variables defined above: for i in (a,b,c,d,e,f,g,h): print(i) # prints the contents of the variable
結果の出力:

Pythonには文字タイプがありません。文字は、長さが1の文字列を使用して表現されます。このように、文字列を介した反復、または文字列のインデックス付けは、単一の文字列を返します。
リストとタプル(データセット)
リストとタプルは基本的にCとIECの配列に対応していますが、いくつかの顕著な違いがあります。
インデックスアクセスは常にチェックされます。無効なインデックスを持つリストまたはタプルにアクセスすると、例外がスローされます。
リストとタプルの両方に、異なるタイプの要素(他のリストとタプルも)を含めることができます。 CおよびIECとは対照的に、配列には単一タイプの要素のみを含めることができます。
リストは動的であり、要素はいつでも追加、削除、または置換できます。
タプルは変更できません。タプルが作成されると、それ以上変更することはできません。
リストはで作成されます list()
コンストラクタ。別の方法として、角かっこを使用できます []
。タプルは tuple()
コンストラクターまたは括弧 ()
。
list_tuples.py
from __future__ import print_function print("Testing tuples and lists") # We define a tuple with the numbers from 1 to 10: t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print("Tuple:", t) # We can access the 6th element of the tuple. # As in C, index counting starts with 0. print("Element 5:", t[5]) # Subscription is more powerful using the range syntax: print("Range[2:5]:", t[2:5]) # lower bound is inclusive, upper bound is exclusive. print("Range[2::2]:", t[2::2]) # start with 3rd element, and print every 2nd element. print("Range[-3:-1]:", t[-3:-1]) # Start with the 3rd last element, end just before the last element (upper bound is exclusive) print("Range[::-1]:", t[::-1]) # negative step with - print backwards # lists are similar to tuples... l = [11, 12, 13, "8", t] # contains mixed types: 3 integers, a string, and the tuple defined above. print("List:", l) # ... but elements can be added or removed dynamically. l.append(9) # Add a 9 to the list. print("List with 9:", l) print("List Range[3:6:2]:", l[3:6:2]) # print the 4th and 6th element. del l[1] # remove the element at index 1, the 12. print("Removed[1]:", l) del l[1:3] # Remove the elements at index 1 and 2, the 13 and the '8'. print("Removed[1:3]:", l)
結果の出力:

辞書
Pythonには、ハッシュテーブルタイプ(「ハッシュマップ」)もあります。リストとは対照的に、文字列などの任意の要素でインデックスを付けることができます。そのコンストラクタは dict()
そしてそのリテラルは中括弧で宣言されます {}
。
サンプルスクリプト dictionaries.py
以下に表示される出力を作成します。最後の行で、スクリプトは「KeyError」例外で終了します。
dictionaries.py
from __future__ import print_function print("Testing dictionaries") # Declare a dictionary with three entries, the third being a list d = {1: "a", 2: "b", "my list": [1, 2, 3]} print(d) # print the value of the key 1 print(d[1]) # remove the value with the key "my list" del d["my list"] # Add a value 4 with the key 3 d[3] = 4 print(d) # The "get" method returns the second argument if the key cannot be found. print(d.get(1, 42)) print(d.get(23, 42)) # print all keys in the dictionary for key in d: print(key) # index access for unknown keys will throw a "KeyError" exception! print(d[23])
結果の出力:

そして最後の行で、スクリプトは終了します。

クリック 詳細 ボタンをクリックして、スタックトレースを表示します。ここで行番号を決定します 27
と未知の鍵 23
。
