2 Python Essentials
2.1 Language origin
Like conversational languages, programming languages group together in clusters. Python is a high level language, indicating that the language was designed to be easy for humans to understand. On the opposite end of the spectrum are extremely low level languages, (often referred to as machine-code), that are most definitely not easy to understand. In between are languages such as C or C++ which offer layers of abstraction above machine-code. As I mentioned, Python is a step even higher, meaning that it is far easier to read (closer to the English language) and we don’t need to manage difficult functionality like memory allocation, or declaring variables!
Lucky us.
Python was first released in 1991, since then it has grown to become freely available with a user-group exceeding tens of thousands. The Python documentation claims, “ Python plays well with others,” “ Python runs everywhere,” “ Python is friendly… and easy to learn” and “ Python is Open!” For more information about the Python programming language and its development see:.
Assuming that you might be reading these pages without any prior programming experience whatsoever, I still dare guess that the following example will not give you much trouble:
import rhinoscriptsyntax as rs somenumber = rs.GetReal("Line length") line = rs.AddLine([0,0,0], [somenumber,0,0]) print "Line curve inserted with id", line
Of course you might have no conception of what [0,0,0] actually means and you might be confused by rs.GetReal()' print a success message
Translating Python:
- Flow control » Depending on the outcome of the second line, some lines are not run
- Variable data » somenumber is used to store a variable number
- Communication » The user is asked to supply information and is informed about the result
2.2 Flow control
We use flow-control in Python to skip certain lines of code or to execute others more than once. We can also use flow-control to jump to different lines in our script and back again. You can add conditional statements to your code which allow you to shield off certain portions. If…Else…Else If model = rs.GetNumber("Line length")
Then later on we retrieve that specific value when we add the line curve to Rhino:
curve = rs.AddLine([0,0,0],  two- billion Python syntax for working with numeric variables should be very familiar:
x = 15 + 26 # x equals 41 x = 15 + 26 * 2.33 # x equals 75.58 x = math.sin(15 + 26) + math.sqrt(2.33) # x equals 1.368
You can use the
print() method to display the result of these computations. The
print() method will display the value in the command-line:
x = 2 * math.sin(15 + 26) + math.log(55) print(x)
Of course you can also use numeric variables on the right hand side of the equation:
x = x + 1 x = math.sin(y) + math.sqrt.
Note, there is a special shortcut in Python that allows you to define multiple variables in a single line of code:
x, y, z = [1,2,3] print x # returns 1 print y # returns 2 print z # returns 3.
In Python we never write “0” or “1” or “Yes” or “No”, for boolean values we always use “True” or “False”.
if curve is None: print "Something went terribly wrong!"
This will return either True or False, only if the result is True (the curve is None) will the code pass into the conditional statement and print “Something went terribly wrong!.”
2.3.3 Strings
Strings are used to store text. Whenever you add quotes around stuff in Python, it automatically becomes a String. So if we encapsulate a number in quotes, it will become text:
variable1 = 5 variable2 = "5"
You could print these variables to the command line and they would both look like 5, but the String variable behaves differently once we start using it in calculations:
print (variable1 + variable2) # Results in an "Unsupported Operand Type" Error
Python throws an error when we try to add a String variable to an Integer Variable. We must first convert the string to an integer, then we can add them together.
print (variable1 + int(variable2)) # Results in 10
When you need to store text, you have no choice but to use Strings. The syntax for Strings is quite simple, but working with Strings can involve some very tricky code. For the time being we’ll only focus on simple operations such as assignment and concatenation:
a = "Apfelstrudel" # Apfelstrudel a = "Apfel" + "strudel" # Apfelstrudel a = "4" + " " + "Apfelstrudel" # 4 Apfelstrudel a = "The sqrt of 2.0 = " + str(math.sqrt(2.0)) # The sqrt of 2.0 = 1.4142135623731
Internally, a String is stored as a series of characters. Every character (or ‘char’) is taken from the Unicode table, which stores a grand total of ~100.000 different characters. The index into the unicode table for the question mark for example is 63, lowercase e is 101 and the blank space is 32:
Further down the road we’ll be dealing with some advanced String functions which will require a basic understanding of how Strings work, but while we are still just using the simple stuff, it’s good enough to know it just works the way you expect it to.
Strings are used heavily in Python None variable
Whenever we ask Rhino a question which might not have an answer, we need a way for Rhino to say “I don’t know”. Using the example on page 5:
curve = rs.AddLine([0,0,0],  means that the return value of
rs.AddLine() is not a valid object ID. Almost all methods in Rhino will return a None variable if they fail, this way we can add error-checks to our script and take evasive action when something goes wrong:
curve = rs.AddLine([0,0,0], [somenumber,0,0]) if not curve: print "Something went terribly wrong!"
The statement,
if not x in Python will return a value True if the variable “curve” is None, 0 or an empty list.
2.3.5 Using variables
Conventionally, whenever we intend to use variables in a script, we would have to declare them first. However, with Python, we are relieved of this duty and we can simply create and use variables without initially declaring them. Python also does not require that we declare the type of variable we are using, as in other programming languages. Both of these qualities emphasize why Python is such a quick and easy to learn language. So, to declare a variable we simply write:
a = "Apfelstrudel"
When using a variable, you choose the name and then set it equal to a value (Number, String, Boolean etc) ‘out of scope’ whenever their containing function terminates. ‘Lifetime’ usage:
strComplaint = "I don't like " strFood = "Apfelstrudel. " strNag = "Can I go now?" print(strComplaint + strFood + strNag)
An important note to reiterate is Python’s case sensitivity. Unlike other languages, in Python “Apfelstrudel”, “apfelstrudel” and “ApfelStrudel” are not equivalent, this is also true for all variable names, functions, classes and any other part of the code. Just remember to be very careful with upper and lower case letters!:
import rhinoscriptsyntax as rs dblMajorRadius = rs.GetReal("Major radius", 10.0, 1.0, 1000.0) dblMinorRadius = rs.GetReal("Minor radius", 2.0, 0.1, 100.0) intSides = rs.GetInteger("Number of sides", 6, 3, 20) strPoint1 = " w" + str(dblMajorRadius) + ",0,0" strPoint2 = " w" + str(dblMajorRadius + dblMinorRadius) + ",0,0" rs.Command ("_SelNone") rs.Command ("_Polygon _NumSides=" + str(intSides) + " w0,0,0" + strPoint1) rs.Command ("_SelLast") rs.Command ("-_Properties _Object _Name Rail _Enter _Enter") rs.Command ("_SelNone") rs.Command ("_Polygon _NumSides=" + str(intSides) + strPoint1 + strPoint2) rs.Command ("_SelLast") rs.Command ("_Rotate3D w0,0,0 w1,0,0 90") rs.Command ("-_Properties _Object _Name Profile _Enter _Enter") rs.Command ("_SelNone") rs.Command ("-_Sweep1 _SelName Rail _SelName Profile _Enter _Enter _Closed=Yes _Enter") rs.Command ("_SelName Rail") rs.Command ("_SelName Profile") rs.Command ("_Delete")
Next Steps
There are the basics of the Python datastructures, next learn the Python’s script anatomy.