Introduction to Python/ja

これは、Pythonをはじめる人のために作られた短いチュートリアルです. Pythonはオープンソース、マルチプラットフォームのプログラミング言語です. Pythonは他の一般的なプログラミング言語と違い、あなたのようなはじめてのユーザーにとって非常に使いやすくするいくつかの機能を持っています.


 * 人間が読みやすいように特別に設計されたので、それを学習し理解することは非常に容易であるされています.
 * C言語のようなコンパイル言語とは異なり、実行する前にコンパイルを必要とせずにコードを解釈します. あなたがそうしたい場合は、記述したコードはすぐに1行ずつ実行することができます. これは、ステップごとに実行されるので、簡単に学習でき、あなたのコード内のエラーを検出することが極めて容易になります.
 * スクリプト言語として他のプログラムに埋め込むことができます. FreeCADは、埋め込まれたPythonインタプリタを持っているので、FreeCADの部品を操作する例えばジオメトリを作成することをFreeCADのPythonコードで書くことができます. これは非常に強力でプログラマが用意した"球体作成"のボタンをクリックするかわりに自由にかつ簡単に作成した独自のツールであなたが望む正確なジオメトリを作成することができます.
 * それは拡張可能であり、新しいPythonのモジュールをプラグインとして簡単にインストールし機能を拡張することができます. 例えば、jpg画像の読み書き、Twitterとの通信、使用しているオペレーティングシステムによって実行されるタスクのスケジュール等のモジュールがあります.

まずは、実際に使ってみましょう！次は非常に簡単な紹介であることに注意してください. これは完全はチュートリアルではありません. しかし、私の希望は、後にFreeCADのメカニズムをより深く探求するための十分な基礎を得ることです.

We strongly encourage you to enter the code snippets below into a Python interpreter. For many of our discussions, the important point is the line after the snippet is run, the reveal. Not running the code would be all build up, without a punch line. So, hands on! The following is a very simple introduction, and by no means a complete tutorial. But our hope is that this will provide enough basics to explore deeper into the FreeCAD mechanisms.

インタプリタ
通常、コンピュータプログラムを書くとき、単にテキストエディタを使用するかほとんど場合は、特別なプログラミング環境のテキストエディタと周辺のツールを利用して プログラムを書き、それをコンパイルして実行します. ほとんどの場合、記述中に誤りがあるとあなたのプログラムは動作しません. そして、何が悪かったのかを伝えるエラーメッセージが表示されます. あなたはテキストエディタに戻って、間違いを修正し、再度実行するということをプログラムが正常に動作するまで繰り返します.

Pythonにおけるプロセスは、Pythonインタプリタの内部で透過的に実行できます. Pythonインタプリタは、Pythonウィンドウのコマンドプロンプトを使って簡単にPythonコードを入力することができます. お使いのコンピュータにPythonをインストールする場合は、（WindowsもしくはMacの場合はPythonのWebサイトからダウンロードしてください. GNU/Linuxの場合はパッケージリポジトリからインストールしてください）スタートメニューにPythonインタプリタが入ります. しかし、FreeCADは、ウィンドウ下部にPythonインタプリタが入っています.





（表示されない場合は、View → Views → Python consoleをクリックしてください. ）

インタプリタは、Pythonのバージョンを表示し、そしてコマンドプロンプトとなる>>>のシンボルを表示します. ここへPythonコードを入力します. インタプリタでコードを書くことは簡単です：1行は1命令です. あなたがEnterを押すと、入力したコードが実行されます. （瞬時にコンパイルされます）例えば、これを書いてください.

print "hello"

は言うまでもなく画面に何かを表示することを意味する特別なPythonのキーワードです. Enterキーを押すと、操作が実行され、"hello"というメッセージが表示されます. エラーにしたい場合は、次の例を書いてください：

print hello

Pythonは"hello"が何かを知らないということを教えてくれる. 「"」はその中身が文字列であることを指します. それはプログラミング用語において、ひとつのテキスト文字列ｆであることを示します. 「"」がない場合、printコマンドは、helloがテキストの一部ではなく特別なPythonのキーワードだと思います. 重要なことは、あなたがすぐにエラーになった通知を受けとれることです. 上矢印を押して、（FreeCADのインタプリタの場合はCtrl + 上矢印）、あなたが書いた最後のコマンドに戻って、それを修正することができます.

Pythonインタプリタにもヘルプ機能があります. 次の命令を試してください：

help

または、例として、先ほどの「print hello」コマンドを使用して何が悪かったのかわからず"print"コマンドに関する具体的な情報が欲しい時は：

help("print")

あなたは、printコマンドが実行できるすべての完全な説明を得ることができます.

今、私たちはインタプリタを使いこなせます. 本気になって使いはじめましょう.

The interpreter shows the Python version, then a >>> symbol, which is the command prompt, that is, where you enter Python code. Writing code in the interpreter is simple: one line is one instruction. When you press Enter, your line of code will be executed (after being instantly and invisibly compiled). For example, try writing this:

is a special Python keyword that means, obviously, to print something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write:

Python will tell us that it doesn't know what hello is. The " characters specify that the content is a string, which is simply, in programming jargon, a piece of text. Without the ", the print command believed hello was not a piece of text but a special Python keyword. The important thing is, you immediately get notified that you made an error. By pressing the up arrow (or, in the FreeCAD interpreter, CTRL+up arrow), you can go back to the last command you wrote and correct it.

The Python interpreter also has a built-in help system. Try typing:

or, for example, let's say we don't understand what went wrong with our print hello command above, we want specific information about the "print" command:

You'll get a long and complete description of everything the print command can do.

Now that we totally dominate our interpreter, we can begin with the serious stuff.

変数
もちろん、"hello"を表示することが注目すべき点ではありません. より注目すべき点は、あなたが気づかなかったことをPythonが解釈して表示していることです. これが変数の概念です. 変数は単に名前をつけて値を格納しているのです. 例えば次のように入力します.

a = "hello" print a

何がおこったのか解説すると、"hello"という文字列をaという名前をつけて格納しました. この時点でaは未知の名前ではありません！printコマンドなどで、どこでも使用することができます. スペースや句切り点を使用しないというような簡単なルールに守っていれば任意の名前を使用できます. この例は、非常によく使います.

hello = "my own version of hello" print hello

見ましたか？helloはもう未定義の言葉ではありません. 不運にもPythonで予約されているキーワードを選んだ場合はどうなりますか？"print"という名前で文字列を格納したいとしましょう：

print = "hello"

Pythonは非常に知的であり、これが不可能であることを私たちに教えてくれます. いくつかの予約されたキーワードを持っており、変更することはできません. しかし、我々の独自の変数は、正確には変数と呼ばれており、いつでも変更することができます. たとえば、次のように：

myVariable = "hello" print myVariable myVariable = "good bye" print myVariable

myVariableの値を変更しました. また、変数をコピーすることができます：

var1 = "hello" var2 = var1 print var2

あなたの使う変数に適切な名前を付けることが重要であることに注意してください. なぜなら、長いプログラムを書こうとしたときに"a"という名前の変数が何のためにあるのか覚えられないと思います. しかし、あなたが例のようにmyWelcomeMessageという変数の名前を使用した場合、あなたはその変数を見たり使ったりするときに簡単に思い出すことができます.

I guess you understood what happened, we "saved" the string "hello" under the name "a." Now, "a" is not an unknown name any more! We can use it anywhere, for example in the print command. We can use any name we want, just follow some simple rules, like not using spaces or punctuation. For example, we could write:

See? now hello is not an undefined word any more. What if, by terrible bad luck, we choose a name that already exists in Python? Let's say we want to store our string under the name "print":

Python is very intelligent and will tell us that this is not possible. It has some "reserved" keywords that cannot be modified. But our variables can be modified any time, that's why they are called variables, the contents can vary. For example:

We changed the value of myVariable. We can also copy variables:

Note that it is important to give meaningful names to your variables. After a while you won't remember what your variable named "a" represents. But if you named it, for example myWelcomeMessage, you'll easily remember its purpose. Plus your code is a step closer to being self-documenting.

Case is very important. myVariable is not the same as myvariable, the difference in the upper/lower case v. If you were to enter print myvariable it would come back with an error as not defined.

数値
もちろん、あなたがプログラムを作る上で文字列だけでなくすべての種類のデータ、特に数値を使うことを知っている必要があります. 重要なことの一つにPythonでどのような種類のデータを使うことができるか知っておく必要があります. print helloの例題から　printコマンドで"hello"という文字列を表示できることがわかりました. それは"を使用すると、printコマンドにおいてその後に続くのが文字列であることがわかりました.

特別なPythonのキーワードを入力することにより、いつでも変数のデータ型が何なのか確認することができます:

myVar = "hello" type(myVar)

これはmyVarの中身が'str'、つまりPython用語における文字列であることがわかります. また、他の基本的なデータ型には、整数型や浮動小数点数型などがあります:

firstNumber = 10 secondNumber = 20 print firstNumber + secondNumber type(firstNumber)

これは、今までよりはるかに興味深いですが、それはないですか？今、私たちは、すでに強力な電卓を持っています！それが機能していることをよく見てください. Pythonは10と20が整数であることを認識しています. だからそれらは "int"型として格納されており、Pythonは整数として扱うことができます. この結果を見てください:

firstNumber = "10" secondNumber = "20" print firstNumber + secondNumber

見ましたか？これはPythonは2つの変数が数字ではなく単なる文字列として認識していることを意味しています. Pythonは、2つの文字列を合わせて一つにすることができますが、2つの合計を求めようとはしません. しかし、我々は、整数型のことも話題にしていました. 浮動小数点型もあります. これらの違いは浮動小数点の数値は小数部を有することができ、整数の数値は、小数部を持っていないということです:

var1 = 13 var2 = 15.65 print "var1 is of type ", type(var1) print "var2 is of type ", type(var2)

int型と浮動小数点型は問題なく一緒に混合することができます:

total = var1 + var2 print total print type(total)

いいですか？もちろん合計は小数になります. Pythonは自動的に結果が浮動小数点型であると判断しました. この例のように、いくつかのケースではPythonは自動的に何型かをを判断します. 他のケースではそれはしていません. たとえば、次のように:

varA = "hello 123" varB = 456 print varA + varB

これは、エラーになります. varAは文字列であり、varBのデータ型は整数型で、Pythonは何をすればいいのかわかりません. しかし、型の変換をPythonに強制することもできます:

varA = "hello" varB = 123 print varA + str(varB)

これで、両方が文字列となり実行できます！表示する時にvarBが"文字列"となっていますが、私たちはvarB自体を変更していないことに注意してください. varBを常に文字列にしたい場合は、次のようにします:

varB = str(varB)

また、場合によって整数型や浮動小数点型に変換するためにintやfloatを使用することができます:

varA = "123" print int(varA) print float(varA)

Pythonコマンドに関する注意

このセクションでprintコマンドをいくつかの方法で使用したことに気づいている必要があります. 変数の値、合計、コンマで区切られたいくつかの事項、そしてtypeのようなPythonコマンドの結果を出力しています. これらの2つのコマンドを実行してみてはどうでしょうか:

type(varA) print type(varA)

まったく同じ結果になります. それはインタプリタであり、すべてのものが画面上に自動的に表示されているからです. インタプリタの外で複雑なプログラムを書いて実行させようと思うと、自動的にすべてが画面上に表示されないので、printコマンドを使用する必要があります. しかし、今からここではそれは使わないでおきましょう. それよりはやいからです. だから簡単に書くことができます:

myVar = "hello friends" myVar

そのPythonコマンド（またはキーワード）のほとんどはtype、int、strなどのように括弧はコマンドとして動作することを伝えるために使用するとわかりました. 唯一の例外は、実際は例外ではありませんがprintコマンドです. これは通常print("hello")のように動作します. しかし頻繁に使用されるのでPythonのプログラマは簡易版を作りました.

We can always check the data type of a variable with the special Python keyword type:

It will tell us the contents of myVar is 'str', short for string in Python jargon. We have also other basic types of data, such as integer and float numbers:

This is much more interesting, isn't it? Now we have a powerful calculator! Look at how well it worked, Python knows that 10 and 20 are integer numbers. So they are stored as "int", and Python can do with them everything it can do with integers. Look at the results of this:

See? We forced Python to consider that our two variables are not numbers but mere pieces of text. Python can add two pieces of text together, but it won't try to find out any sum. But we were talking about integer numbers. There are also float numbers. The difference is that integer numbers don't have decimal part, while float numbers can have a decimal part:

Int and Floats can be mixed together without problem:

Of course the total has decimals, right? Then Python automatically decided that the result is a float. In several cases such as this one, Python automatically decides what type to use. In other cases it doesn't. For example:

This will give us an error, varA is a string and varB is an int, and Python doesn't know what to do. However, we can force Python to convert between types:

Now both are strings, the operation works! Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:

We can also use int and float to convert to int and float if we want:

Note on Python commands

You must have noticed that in this section we used the print command in several ways. We printed variables, sums, several things separated by commas, and even the result of other Python command such as type. Maybe you also saw that doing those two commands,

have exactly the same result. That is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print command. From now on, let's stop using it here, it'll go faster. So we can simply write:

You must have seen that most of the Python commands (or keywords) type, int, str, etc. have parenthesis to limit the command contents. The only exception is the print command, which in fact is not really an exception, as it also works normally: print("hello"). However, since it is used often, the Python designers allowed a simpler version.

Lists
Another interesting data type is a list. A list is simply a collection of other data. The same way that we define a text string by using " ", we define a list by using [ ]:

You see that it can contain any type of data. Lists are very useful because you can group variables together. You can then do all kinds of things within that group, for example counting them:

or retrieving one item of a list:

You see that while the len command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more with lists, you can read here, such as sorting contents, removing or adding elements.

A funny and interesting thing: a text string is very similar to a list of characters! Try doing this:

Usually, what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Outside strings, ints, floats and lists, there are more built-in data types, such as dictionaries, or you can even create your own data types with classes.

Indentation
One big cool use of lists is also browsing through them and do something with each item. For example look at this:

We iterated (programming jargon) through our list with the "for ... in ..." command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that a colon ended line has happened and more is coming.

How will Python know how many of the next lines will be to be executed inside the for...in operation? For that, Python uses indentation. That is, your next lines won't begin immediately. You will begin them with a blank space, or several blank spaces, or a tab, or several tabs. Other programming languages use other methods, like putting everything inside parenthesis, etc. As long as you write your next lines with the same indentation, they will be considered part of the for-in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you finished, just write another line without indentation, or simply press Enter to come back from the for-in block

Indentation is cool because it aids in program readability. If you use large indentations (for example use tabs instead of spaces because it's larger), when you write a big program you'll have a clear view of what is executed inside what. We'll see that commands other than for-in, can have indented blocks of code too.

For-in commands can be used for many things that must be done more than once. It can, for example, be combined with the range command:

(If you have been running the code examples in an interpreter by Copying and Pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste to the interpreter.  In the interpreter issue an until the three dot prompt disappears and the code runs.  Then copy the final two lines into the interpreter followed by one or more The final answer should appear.)

If you would type into the interpreter help(range) you would see:

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the range parameters to be an integer using int

Or more complex things like this:

You see that the range command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

Another interesting use of indented blocks is with the if command. If executes a code block only if a certain condition is met, for example:

Of course this will always print the first sentence, but try replacing the second line by:

Then nothing is printed. We can also specify an else: statement:

Functions
There are few standard Python commands. In the current version of Python, there are about 30, and we already know several of them. But imagine if we could invent our own commands? Well, we can, and it's extremely easy. In fact, most the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

(Another copy and paste error, only copy through the end of the indented section i.e. " square meters" Paste to the interpreter, and issue until the three dot prompt goes a way, then copy and paste the final line.)

Extremely simple: the def command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len command. If you just write len alone, Python will tell you it needs an argument. That is, you want len of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len function. The len function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.

The "myValue" name can be anything, and it will be used only inside the function. It is just a name you give to the argument so you can do something with it, but it also serves to tell the function how many arguments to expect. For example, if you do this:

There will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. We could instead do something like this:

We made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable. Of course, since we are in the interpreter and everything is printed, doing:

will print the result on the screen, but outside the interpreter, since there is no print command inside the function, nothing would appear on the screen. You would need to:

to have something printed. Read more about functions here.

Modules
Now that we have a good idea of how Python works, we'll need one last thing: How to work with files and modules.

Until now, we wrote Python instructions line by line in the interpreter, right? What if we could write several lines together, and have them executed all at once? It would certainly be handier for doing more complex things. And we could save our work too. Well, that too, is extremely easy. Simply open a text editor (such as the windows notepad, Linux gedit, emacs, or vi), and write all your Python lines, the same way as you write them in the interpreter, with indentations, etc. Then, save that file somewhere, preferably with a .py extension. That's it, you have a complete Python program. Of course, there are much better editors than notepad, but it is just to show you that a Python program is nothing else than a text file.

To make Python execute that program, there are hundreds of ways. In windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your .py program is. In FreeCAD, the easiest way is to place your program in a place that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. (In Linux, you probably have a directory /home/ /.FreeCAD/Mod, let's add a subdirectory to that called scripts where we will put the text file.) Suppose we write a file like this:

and we save it as myTest.py in our FreeCAD/bin directory (or on Linux to /home/ /.FreeCAD/Mod/scripts.) Now, let's start FreeCAD, and in the interpreter window, write:

without the .py extension. This will simply execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. There is one big difference: the import command is made not only to execute programs written in files, like ours, but also to load the functions inside, so they become available in the interpreter. Files containing functions, like ours, are called modules.

Normally when we write a sum function in the interpreter, we execute it simply like that:

Like we did earlier. When we import a module containing our sum function, the syntax is a bit different. We do:

That is, the module is imported as a "container", and all its functions are inside. This is extremely useful, because we can import a lot of modules, and keep everything well organized. So, basically, everywhere you see something.somethingElse, with a dot in between, that means somethingElse is inside something.

We can also import our sum function directly into the main interpreter space, like this:

Basically all modules behave like that. You import a module, then you can use its functions: module.function(argument). Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

One last extremely useful thing. How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We saw already that Python has a help function. Doing:

Will give us a list of all available modules. We can now type q to get out of the interactive help, and import any of them. We can even browse their content with the dir command

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. The __doc__ is extremely useful, it is a documentation text. Every function of (well-made) modules has a __doc__ that explains how to use it. For example, we see that there is a sin function in side the math module. Want to know how to use it?

(It may not be evident, but on either side of doc are two underscore characters.)

And finally one last little goodie: When we work on a new or existing module, it's best to replace the file extension with py such as: myModule.FCMacro => myModule.py. We often want to test it so we will load it as above.

But what if we see that myTestFunction doesn't work correctly? We go back to our editor and make changes. Then, instead of closing and reopening the python interpreter, we can simply update the module like this:

This file renaming is because Python doesn't know about the extension FCMacro.

However, there are two alternates: Inside the one macro use Python's exec or execfile functions.

or

To share code across macros, you can access the FreeCAD or FreeCADGui module (or any other Python module) and set any attribute to it. This should survive the execution of the macro.

Starting with FreeCAD
Well, I think you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. So, just do

and read on to FreeCAD Scripting Basics...

Of course, we saw here only a very small part of the Python world. There are many important concepts that we didn't mention. There are three very important Python reference documents on the net: Be sure to bookmark them!
 * the official Python tutorial with way more information than this one
 * the official Python reference
 * the Dive into Python wikibook/ book.