4.2. Python Basics
GH-Python and Python Basics
Variables
Variables are used to hold information (containers) in order to read, write, modify or process it. Variables are equivalent to parameters in GH.
Variables in Python can be:
-
Value-type: represent information such as integer numbers, decimal numbers, strings of characters and boolean states.
-
Reference-type: can hold any type of data such as surfaces, curves and points.
# Variable declaration
var = 10 # Integer
var = 20.0 # Float Numbers
var = "20" # String within quotes
var = true # Boolean
# Good practice to declare a boolean
bool = true
bool = false
bool = varBool
Python is Case-Sensitive: myVar is not the same as Myvar.
Good practice to use Camel Case: The first letter of an identifier is lowercase and the first letter of each subsequent word is capitalized. Example: myVar, varPt
Some words cannot be used because are reserved for other purposes:
and, exec, not, assert, finally, or, break, for, pass, class, from, print, continue, global, raise, def, if, return, del, import, try, elif, in, while, else, is, with, except, lambda, yield.
Numbers
Integer
Whole number as for example 1, -1 or 12512
# addition
add = 5 + 3
print add
Floats
Decimal number as for example 0.1, 59.4 or -2478.36
# Addition
add = 0.5 + 0.3
print add == 0.8 # Result = False
# IMPORTANT check precision issues // value can be rounded with --> round()
# Division
div = 4/3
print div
# Multiplication, subtraction and exponent
print 5 * 5
print 10 - 3
print 5 ** 5
# Modulus
print 9 % 3 # returns the reminder between this two numbers, in this case 0
print 9 % 4 # the reminder is 1
Order of operations
- Parentheses
- exponent
- Multiplication
- Division
- Addition
- Subtraction
# Change the order of the operations
print 15 + 5 * 5
print (15 + 5) * 5
Strings
String are Arrays.
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
# Strings
word = "Hello"
print word
# Adding Strings
geo = "Plane "
num = "123"
plane = geo + num
print plane
# Indexing
word = "Hello"
print word[1] # It will print letter "e"
print word[-1] # It will print last letter "d" starting from the end
# Slicing
word = "Hello"
print word[0:2] # [start:stop] It will print Hel
print word[1:] # Will start from position 1 until the end
print word[:2] # Will start from beginning until index 2
# Formatting
srf = "Srf is at {}".format(234)
print plane # It will print "Srf is at 234"
# Casting
xyz = 123
print "Point is at" + str(xyz) # convert numbers into string
List and Tuples
A list is simply a container to store items in an ordered manner such as numbers, strings or geometry.
In Grasshopper if a component returns more than one items, it will be a list or a data tree.
Tuples use round brackets intead of squared.
# The simplest method to create a list is an empty list with []
emptyList = []
print emptyList
# List
lst = [1,2,3,4,5,6,7,8,"Hello"] # Lists can contain different Data Types
print lst
# Range
print range(5) # It will return [0,1,2,3,4]
# Indexing
print lst[4] # It will return number 5
print lst[-1] # It will return "Hello"
lst[2] = "Point"
print lst # It will print [1,2,"Point",4,5,6,7,8,"Hello"]
# Slicing
print lst [2:5] # It will return ["Point",4,5,6]
# Copy a list
lstCopy = lst[:]
print lstCopy
# Adding Items
lst.append(254)
print lst # It will add 254 at the end [1,2,"Point",4,5,6,7,8,"Hello",254]
# Remove Items
lst.pop()
print lst # It will remove last item [1,2,"Point",4,5,6,7,8,"Hello"]
lst.pop(0) # It will remove first item [2,"Point",4,5,6,7,8,"Hello",254]
# Insert Items
lst.insert(1,5) # It will insert the item 5 under index 1
print lst
# Sort Items
lst.sort() # Sort all items by order and by type
# Tuples
tuple = (1,2,3,4,5) # round brackets
print tuple
Comparison Operators
We use comparison operators to compare one value to another. For example, if you want to compare the length of two curves or the area of different surfaces.
Before we start with comparison operators lets quickly have a look into Booleans:
Most objects have a boolean state, so we can check if an object is True or False. If an object is empty, zero, or none, it will return False.
# Booleans
T = True
F = False
print T,F #It will return True, False
# We can also cast Booleans
print bool (0) # It will return a False
print bool (5) # It will return a True
# Comparison Operators
x = 1
y = 2
print x == y # Iqual to, It will return False
print x != y # Not iqual to, It will return True
print x > y # Greater than, It will return False
print x < y # Smaller than, It will return True
print x <= y # Smaller than or equal to, It will return True
print x >= y # Smaller than, It will return False
Conditionals
Comparison operators can be used in several ways, most commonly in “if statements” and loops.
An “if statement” is written by using the if keyword:
# IF
a = 15
b = 60
if b > a:
print ("b is greater than a")
The Elif keyword says that “if the previous conditions were not true, then try this condition”.
# ELIF
a = 15
b = 60
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
The Else keyword catches anything which isn’t caught by the preceding conditions.
# ELSE
a = 15
b = 60
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Comparing Booleans
Boolean comparation with logical operators AND and OR.
# Comparing Booleans
area = 150
volume = 200
# Logical AND Operator
print area > 100 and volume > 150 # True
# Logical OR Operator
print area > 100 or volume < 50 # True
# Logical NOT Operator
print not area == 120 # True
For Loop
Performs a single or set of instructions for every item in the list. It execute an instruction repeatedly until a certain condition is met.
There are two different types of loopig in Python: For loop and While loop
# For loop
numbers = [0,1,2,3,4] # List of numbers to iterate
lst = [] # Empty list where to store the iterated items from For Loop
for var in numbers:
lst.append(var)
print lst # It will print [0,1,2,3,4]
lst2 = []
for x in numbers:
if x > 2:
lst2.append (x)
print lst2 # It will print [3,4]
While Loop
The While loop will loop until the condition is false
# While loop
var = 0
lst = []
while var < 5:
lst.append(var)
var += 1
print lst
Nested Loop
Nesting loops is basically adding one or more loops inside of another loop.
points = [0,1,2,3,4,5]
# Nest Loop
for x in points:
for y in points:
print (x,y)
Custom Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
You can define a function by using the def keyword.
# Functions
def my_function():
print("Hello, this is a function")
# To call a function, use the function name followed by parenthesis
my_function()