Sie sind auf Seite 1von 13

Table of Contents

1. Introduction
2. Chapter 1 - What Is Python ?
3. Chapter 1 - Basic Types
4. Chapter 2 - Variables
5. Chapter 3 - Lists
6. Chapter 4 - Dictionaries

pbom
"Python's Book of Magic" is a small, simple and easy tutorial for non coders about Python programming language

What is python ?
This is probably the very first question you will be asking. Python is a programming language. A programming language
is a language that help the user communicate with the machine. The machine itself understands only machine language
which nothing more than a series of 0s and 1s, known as the binary format. Those 0s and 1s operate like switches with 0
being "off" and 1 being "on". Of course, coding in 0s and 1s is not ideal, so programming languages have been invented
with the sole purpose of bringing coding as close to a natural (e.g. English) language as possible.
Programming languages that are close to machine code are known as "low level". Assembly is the only low level
programming language, and while it can use some commands that make some sense like "MOV" for data movement, it's
still very much machine (CPU) dependent in its syntax. High level languages move away from machine code and are
more English like, such as Java , C, C++, C#, D, Objective C, and many more. Higher level languages are much closer to
English, and they generally implement concepts that are not technical. They are not closely tied to the machine
architecture. Some of the higher level languages are Visual Basic, Ruby, Runrev, and more.

1. Why use Python ?


Python is a highly readable language. It is easy to read and understand Python source code.
Python is popular, with million of coders worldwide. Python is powerful, and used by demanding companies Like
Google, YouTube, and NASA.

Python is flexible enough to run with Java, .NET, Javascript, etc.


Python is portable, so without changing a line of code, it runs on Windows, Linux, Mac, etc.
Python is compact, meaning code can be much shorter and simpler compared to C /C++, Java, etc.
Python is easy to debug because the source code is short and easy to understand.
Most importantly, Python is an excellent choice for absolute beginners. Visiting any programming forum or any user
forum, when a poster asks "what language should I first learn", Python is one of the most recommended choices.

2. How to install Python ?


You can get Python from the Python website . If you use MacOS and Linux Python comes already included in these
operation system but because we will be using the latest Python version, Python 3, it would be better if you installed it
yourself. The installation process should be pretty straighforward.
As soon as you install it if you know how to user the terminal (an application for entering and executing command line
code) , executing
[[[ python3 ]]]
should be enough to launch the intepreter and you should see something very similar to this

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21)


[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Anythong entered at >>> is python command that can be executed if the syntax is correct.

3. What is an intepreter ?
As I said earlier your machine understands only machine code. That being said, a tool is required to convert Python
commands to machine code. This where the interpreter comes in. It takes your Python module, reading it line by line, and
converting any Python command to machine code, which then executes. The beauty of the interpreter is that you can

execute code interactively one command at a time, thus really test what works and what does not, making it easy to
debug code, find errors, mistakes, and test different approaches.

Basic types
We will be using the intepreter's command prompt ">>>" to enter python command to help us understand the basic types
that python uses to store data.

1. Integer type
Type the following command

>>> 1+2
3

This a command containing and manipulating data. The data is "1" and "2", and the command is "+". "+" is also called an
"operator", a mathematical operator in this case. What you see in the second line is the returned result which is of course
"3". Python includes addition, subtraction, multiplication, and division mathematical operators.
example of multiplication:

>>> 2*3
6

example of division:

>>> 6/3
2.0

example of subtraction:

>>> 2-1
1

2. String type
Another Python command that can be used is the print() command. Below is an example of using the print() command:

>>> print("this is pure python magic")


this is pure python magic

This Python command is called a "function". This is considered a function because it includes a name, print, and opening
and closing parentheses. That is the basic syntax for any Python function. However, it's not necessary to worry about
what a function is exactly, for we will deal with it later.
The "this is pure Python magic" is called a string. What exactly is a string? Type the following into the Python Console,
and then press enter toe execute the command:

>>> "1" + "2"


'12'

As shown above, the output is the string '12'. String can be represented with single quotes or double quotes. Why is this?
Because the command was not 1 + 2, but "1" + "2". Since quotes surround each number, they are considered strings.
Therefore, when using the addition operator, it combines the 2 strings into one string. That being said, "1" + "2" becomes

"12". Now, type "1" * "2" into the Python Console, and press enter to execute the command.

>>> 1" * "2"


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

The output result in what is called a "Python error". Python errors are bad. Everyone wants to type perfect code, and
nobody wants to experience all the pain of correcting mistakes. However, the world isn't perfect, and Python helps by
reporting what is wrong.
The error may seem a bit cryptic, but it's not hard to decipher. The first line reports an error that was found, the second line
reports where the error is, and the third line reports what the error is. In this case, the error is TypeError. "TypeError"
means there is an error with the type. When reading the rest of the line, it becomes obvious that it expected data type "int",
but it got data type "str", which is short for string. A string is a 'string' of characters, one character after another. The "int"
data type, short for integer, is one of the many types of numerical data. Types matter a lot for all programming languages.
However, Python tends to be more forgiving with mixing different types in the same command. To help provide an
example, type the following into the Python Console, and press enter to execute the command.

>>> "1" * 2
'11'

Now it works like a charm. Not only did the command contain the data type "str", and also an "int" as it expected. Another
way of saying this is that the command provided correct Python Syntax. Type the following into the Python Console, and
then press enter to execute the command:

>>> "you are a python wizard"[0]


'y'

The command included a string, and then "[0]". The command, in english, means output the first letter in the string, which
in this case, is "y". Though it would be easier to understand the number if it was one, it is 0 because it represents 'first'.
Note that a character doesn't have to be a letter. It can be "!", "@", "4", or of course any mix of that.

3. Text editor
The Python interpreter prompt is really fun and useful, but scripts and addons rarely are one line long. That being said,
something is required that will allow the typing and execution of multiple lines as one script. Luckily, the only thing that's
necessary is a regular text file with *.py extension. This is called a Python module. In order to edit a Python module, a text
editor is necessary. The preferred choice is an editor that can highlight Python syntax, which means that it colors
differently different Python commands to make them easier to notice. Python already comes with a text editor bundled
with a GUI python interpreter prompt called IDLE , that it works very good for Python coding. So you can use IDEL to
create python modules . To execute python modules all you have to do in the terminal is :

python mymodule.py

of course you replace "mymodule.py" with the name of your module. If you decide to use IDLE then you can bypass the
terminal completely and instead use IDLE's "run module" option you can find in its menu bar.

Variables
1. Assignment
OK, let's get back to coding. Where were we? Ah, yes. We explained data types such as integers and strings. But would it
be cool if we could store data in some way, after your computer already stored data in files on a hard disk, on memory,
online, etc. Data changes all the time, so storage is a must.
Programming languages store data in variables. Let's see this example.

a = 12
b = "I have"
c = "ideas"
print(b+" "+str(a)+" "+c)

OK, let's take this step by step. On the first line, we define a variable called a, and we store inside it the 12, an int value.
Assigning variables is that easy. You basically provide the name, equal sign, and a value. On the second line, we define
a variable called b, stored inside "I have", a str value. Last but not least, the third line defines c, is assigned "ideas",
another str value.
The next line takes a bit of explaining, but is easy to figure it out. It's a print function. It's a function because it has a name,
a parameter, and opening and closing parentheses. The "+" is used as an operator to unite the strings. A variable can be
of any type, but as I said, Python does not like it when you mix different types because our print function only takes string
values. If we just let it be "+a", it would complain with an error because it is an integer (int value). What we need to do is
convert variable "a"'s value to a string. Since we can use int() and float() to convert a type to an integer or float, we should
be able to convert a type to a string by using str(). Therefore, the function str() is used with the parameter a.
Notice that we used +" " as part of the parameter of the print function to type spaces between the strings. We could have
as well included those spaces in the strings when we assigned the variables. The beauty of coding is that it allows us to
be flexible.

2. User input
A program that does not interact with a user is not a very useful program. What if we could communicate with the user in
some way? We can, using the input() function.

name = input("What's your name?")


print("Hello "+name+". My name is Python, nice to meet you." )

Go ahead and type your name and hit enter. If you typed John, it will print "Hello John. My name is Python, nice to meet
you". Isn't Python fun?!
As you can see, we assign the output of the function input() to a variable. Functions can take input with parameters and
can output data with returning types. In this case, it returns data type 'str', and to be precise, a string with the name we
input. From there on we just unite the name variable with the 2 other strings to form the final print.
Let's try the following code:

number1 = int(input("Give me the first number : "))


number2 = int(input("Give me the second number : "))
print( "If I add " + str(number1) + " and "+str(number2)+" it equals to "+str(number1+number2))

Don't let this confuse you; it's still easy to understand. The first thing you observe is that it is possible for a function to take
another function as a parameter. What we did in line 1 and 2 is that we take input from the user and convert it into integer,
remembering that input returns only strings. Then in the print function, we reconvert the variables to strings in order to

unite them in one string. After that, we add variable number1 and number2 together. The result is converted to a string,
which is then united to the final string.
There is another way of doing this, shown below:

number1 = input("Give me the first number : ")


number2 = input("Give me the second number : ")
print( "If I add %s and %s it equals to %d" %(number1 ,number2, int(number1)+int(number2)))

So this is doing the exact same thing, it only does it differently. The "%s" inside our string is not actually part of string. It
only tells print that it should place a string here, which is defined inside %(). So the first %s places the string value of
number1 the second %s places the string value of number2. However, %d places an integer which is the the result of
converting number1 variable and number2 variable to integers and then adding them together. As you see, with this way
we don't have to convert our variables except only when we add them together. This process is called string formatting. It
is useful for when you do many conversions between different types and want to join everything in a single string. What
you use is up to you.

3. Variable rules
There are some rules to be followed for variables. First, when you name them, you are allowed to use numbers inside but
the name of the variable must start with a letter. Below is what NOT to do:

123 = 3

Do not do this either:

123b = 3

Don't put spaces in variable names:

number 1= 3

You can do this though:

number_1= 3

You also can do this, because it's possible to give a variable a different value at any time:

number_1= 3
number_1 = 4

Variables can also be assigned values contained in other variables. The final value of the variable in this case will be 4.

number_1= 3
number_2 = 4
number_1 = number_2

However, if we do this, again the final value of number_1 will be 4. Why is this? Because the variable change of
number_2 doesn't change the value of number_1 after assignment.

number_1= 3
number_2 = 4
number_1 = number_2
number_2 =10

4. 3.4 Case Sensitivity


Another extremely important rule that applies to everything in Python is case sensitivity. Case sensitivity is the
capitalization of letters. For example, Var1 and var1 are two different variables. That means that capitalization matters A
LOT. Many programmers use it for naming. MyFirstVariable is, of course, different from myfirstvariable or mYfirsTvariable,
etc. Personally, I don't use capitalization to name anything I define or assign. I prefer the use of underscores, but it's
completely up to you. Bare in mind that capitalization applies to everything inside Python, so you need to be careful how
you type your commands.

Lists
You may think that since we got integers and floats and strings we have pretty much finished with Data types. However
python is a huge programming language, there is ton of stuff available . Of course the goal of this book is not to teach you
all of python, just enough to get you started and working with blender so we will keep things as simple as possible.
However there are still some types that even though they are not absolutely necessary for making a working program
they are absolutely necessary for keeping code simple and short. One of those types is list.
I can hear you wondering whether a variable can be assigned not one but several values. Lists do exactly that. Actually
lists work very similarly to strings. Lets see how we assign a list to variable.

a = [ 1, 2, "hello" ,4 , 5.0 ]
print(a)
print(a[2])

a variable is assigned a list and we know its a list because we start the declaration with [ and end it with ]. Its important for
python to recognize that this is a list because list are not the only way to assign multiple values to a single variable. Lists
work similarly to strings in a sense that we access them via an index, a[x] will return the value of variable a from index x .
In this case its clear that index 2 contains the string "hello" . Remember what we said earlier 0 is always first for computer
so here value 1 is in index 0 , that is why "hello" is in index 2.
ok lets do the following

a = "hello"
a[0] = "y"

It gives this error --> TypeError: 'str' object does not support item assignment. Basically it says we are not allowed to
assign value in a string in a specific index. Why ? Because strings are immutable , or read only. Remember the string is
immutable not the variable if we add to the previous example a = "yello" its perfectly ok.
One may wonder why python implements mutable types that can be changed but also immutable types that cant be
changed. The reason is of course to provide means to protect values the same way some of your files in your system are
read only . Because they are very important files and you dont want anyone or anything messing with those files. The
same happens with data inside a python module.
This is where a list comes handy because list is mutable and thus it can be changed.

a = "hello"
b=list(a)
b[0] = "y"
print(str(b))
print("".join(b))

so we assign a the string "hello" , b is assigned the value of a after it has been converted to a list , we can now change the
h to y because lists are mutable but when we convert b back to string and print it we get spaces between and also "[" ","
and "]". This happens because python converts the full declaration of the list to a string, but we dont want that . We want
only the values joined together in a single string. So we use the function join.
You will observer here the weird dot between "" and function join. Types in python are objects and objects are groups of
both data and\/or functions. Actually there are alot of functions we can use for each types some are part of their object
some are just built in functions so they dont need a dot in the syntax. Dont worry about objects right now and how they
work we will talk about them when we explain Object Orientated Programming.
Lets see some cool functions about lists

names = ["john" ,"mary" ,"peter" ]


names.append("jane")
print(names)
Append is member function of the object list , and of course it appends another index to the list. Observe that we use the dot to access the function. W
names = ["john" ,"mary" ,"peter" ]
names = names[0:1]
print(names)

in this case it prints ['john'] . Observe that we dont use a second variable as names is reassigned the result of the split.
However now names has lost its previous values. [0:1] means give me the indexes started from index 0 and ending on
index 1 , index 1 is not included.
Another cool thing about lists is that they can be multidimensional , there is no limit to how many dimensions a list has.
For example lets create a 3d list.

data3d = [[["x1"],["x2"],["x3"]] ,
[["y1"],["y2"],["y3"]] ,
[["z1"],["z2"],["z3"]] ]
print(data3d[0][1][0])

The comma allows us to use multiple lines for this one statement making our code easier to read. Basically each
dimension is a list inside another list for example this [] is one dimension list this [[]] is a 2d list this [[[]]] is 3d list and so on .
So [0][1][0] means the first sub-sub-sub list from the second sub-sub list from the first sub list. It may get abit confusing to
understand multidimensional lists so its better that you do your own tests to make sure you have a good feeling about it
because multidimensional lists is something that you may use several times in blender as their advantages are obvious.
The important thing to remember is that a dimension is just a list inside another list.
Bare in mind that when accessing a list the dimensions are optional for example using the above source code we could
do data3d[0][1] or just data3d[0]. Try it and get a feel of how a list really works. There is no hurry , take your time. These
foundations you build now they will help a lot in the future. There are many more things that can be done with lists , but I
wont go to full detail, I only care of giving you basic knowledge but if you want to learn more you can visit the official
documentation here.

1. Tuples
Tuples behave like lists the big difference is that they are not mutable so they cannot be changed , so they are preffered
for sensitive data that should not change. This is how you define a tuple

names = ("john" ,"mary" ,"peter" )


print(names)

Line 1 is not a function because even though it has open , close parentheses and parameters that are separated via
commas there is no name in front of the parentheses so this way we know its a tuple and not a function. Tuples like lists
are accessed via index exactly the same way and like lists they can be multidimensional. x

data3d = ( (("x1"),("x2"),("x3")) ,
(("y1"),("y2"),("y3")) ,
(("z1"),("z2"),("z3")) )
print(data3d[0][1])

Dictionaries
1. References
Before continuing to Dictionaries , I would like to explain a very important and fundamental concept of python that applies
to pretty much anything. Its a concept that is crucial to understand because if you don't you will come against problems
that will be impossible to solve. No worries though this concept is very easy to understand.
When you assign a variable lets say a =1 or name= "john" its easy to assume that basically what is happening is that the
computer finds an address in memory and stores there number 1 and assign the variable to that address and then finds
another address in memory stores there the string "john" and assign this address to variable name. So far so good.
But if we then do variable b=1 and name2="john" we assume once more that previous process is repeated. This
assumption is wrong .What it really has happened here is that the previous address that has stored 1 now is assigned to
both a and b and the address that has stored "john" is assigned to both name and name2. Ok so where is the problem ?
Lets try this

list1 = ["one","two","three"]
list2=list1

this means that now list 2 is ["one","two","three"] if we do

list2[0]=1

this means that now list2 is [1,"two","three"] so far so good , but if we check list1 again list one is [1,"two","three"]
and if we do

list1[0]="bazooka"

then of course list1 is ["bazooka","two","three"] but also lists2 is ["bazooka","two","three"]


This phenomenon is called "shared references" and it is used alot by Python in order to save memory. Imagine what
would happen if our program generated thousands of lists all of them having the exact same data , that would be mean
using loads of memory while in this case shared reference means that we can save 1000 times more memory and of
course it is absolutely crucial when your application deals with megabytes or even gigabytes of data. One will ask how
then we seperate the reference of list1 from the reference of list2, notice here that the entire list is referenced not just its
indices. On way doing this is by copying the data in case of list it can happen this way

list1 = ["one","two","three"]
list2=list1[:]

if you remember we used [0:2] to spit a list but in this case because there is no start and end index the list is copied index
by index and thus the copy returned is assigned in a different memory address and we can change it without affecting the
original data.
So this all was references, we will discuss how we deal with deep copies (no reference) and references in later chapters,
but it is crucial you remember the basic concept and that it applies to pretty much anything data wise inside python.

2. Dictionaries
Dictionaries are by far my favorite type of data in python. Actually I think they are the favorite type of python data for most

python wizards out there. Dictionaries are very similar to lists, like lists they store multiple types, like lists they are mutable
so their data can be modified . like lists they are accessed via index but unlike lists their indexes can be not only numbers
but names as well.
This is the basic syntax

record = { "Name" : "James" , "Surname" :"Bond" , "age" : 32 , "license to kill": [0,23,12,45,67], 5 : "ok" }
print(record["Name"])

So there some things that are obvious from the start.


First ,that python knows that this is a dictionary because of { and }
Second, the index names also called keys are strings like "name"
Third, a dictionary can contain a list
Forth, the key is separated from its data using the : symbol.
the print will print the string value "James" , since that is what corresponds to keyword "Name".
You may ask why keys dont use names like {name:"James"] . Because in this case python will actually try to search for a
variable named name and use its data as a name for our key and this is not what we want here.
Another advantage of dictionaries over lists is that the numerical indices are not in a sequence, so you have index 1 and
3 for example (or more correctly key 1 and key 3) but not index 2 . This is useful when data is in not continuous.
I dont want to go very deeply into dictionaries, we will use them later , but more or less this what they do and how they
behave.Two important functions you should remember is dict.keys() which return the names of the keys and dict.values()
that returns only the values stored in the keys. Observe that both functions use dot sign so that means they are members
of the object of dictionary type so in the above example you would do record.keys() or record.values()

Das könnte Ihnen auch gefallen