Python Basics

Datatypes

Data Type Description Examples
Integers Whole Numbers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers Numbers with decimal point -1.25, -1.0, –0.5, 0.0, 0.5, 1.0, 1.25
Strings Ordered sequence of characters ‘a’, ‘aa’, ‘aaa’, ‘Hello!’, ‘11 cats’
List Ordered sequence of objects [10, “Hello”, 20.3]
Dictonary Unordered key : value pairs {“MyKey” : “Value”}
Tuples Ordered immutable sequence of objects (10, “Hello, 20.3)
Set Unordered collection of unique objects {“a”, “b”}
Bool Logical value indicating True or False True / False

Variables

You can name a variable anything as long as it obeys the following rules:

Example:

    >>> spam = 'Hello'
    >>> spam
    'Hello'

Operators

Operators Operation Example
** Exponent 2 ** 3 = 8
% Modulus/Remaider 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4

Comparison Operators

a = 3 b = 4

Operators Operation Example
> If the value of left operand is greater than the value of right operand, the condition becomes true (a > b) -> False
< If the value of left operand is less than the value of right operand, the condition becomes true. (a < b) -> True
== If the values of two operands are equal, then the condition becomes true. (a == b) -> False
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) -> False
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) -> True
!= If values of two operands are not equal, then condition becomes true. (a != b) -> True

If - elif - else statements

Definition:

if my_condition is equal a value:
    execute some code
elif my_other_condition is equal another value:
    execute something different
else:
    do something else

While loop

Definition:

while some_boolean_condition:
    do something
else:
    do something different

Example:

break_condition = 0
while break_condition < 10:
    break_condition = break_condition + 1
    print(break_condition)
else:
    print("out of while loop")

For loop

mylist = [1,2,3,4,5,6,7,8,9,10]
for item in mylist:
    print(item)
for i in range(0, 10, 2):
    print(i)
for letter in "Python":
    print("current letter: ", letter)
d = {"k1":1, "k2":2, "k3":3}
for item in d:
    print(item)
print(len(pets))
print(list(range(len(pets))))

for index in range(0,len(pets)):
    print(index, pets[index])
for p,x in enumerate(pets):
    print(p, x)
while True:
    print('Who are you?')
    name = input()
    if name != 'Joe':
        continue
    print('Hello, Joe. What is the password? (It is a fish.)')
    password = input()
    if password == 'swordfish':
        break
print('Access granted.')

Lists

>>> spam = ['cat', 'bat', 3, 'elephant']

>>> spam
['cat', 'bat', 'rat', 'elephant']

>>> len(spam)
4
>>> spam = ['cat', 'bat', 3, 'elephant']

>>> spam[2]
'2'

>>> spam[-1]
'elephant'
>>> spam = ['cat', 'bat', 3, 'elephant']
>>> spam[0:4]
['cat', 'bat', 3, 'elephant']

>>> spam[1:3]
['bat', 3]

>>> spam[:2]
['cat', 'bat']
>>> spam = spam + ['add new item']
>>> spam
['cat', 'bat', 3, 'elephant', 'add new item']
>>> spam = ['cat', 'bat', 3, 'elephant']
>>> spam.append('append me!')

>>> spam
['cat', 'bat', 3, 'elephant', 'append me!']

Dictionaries

Definition:

>>> my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'} 

>>> my_dict
{'key1': 'value1', 'key2': 'value2', 'key3':'value3'} 

>>> my_dict['key1']
'value1'

Example:

>>> prices_lookup = {'apples': 2.99, 'oranges': 1.89}

>>> prices_lookup['apples']
2.99
>>> key = {'color': 'pink', 'age': 22}
>>> for k in key.keys():
>>>     print(k)

color
age
>>> value = {'color': 'pink', 'age': 22}
>>> for v in value.values():
>>>     print(v)

pink
22
>>> item = {'color': 'pink', 'age': 22}
>>> for i in item.items():
>>>     print(i)

('color', 'pink')
('age', 22)

Functions

Definition:

def name_of_function(name):
    do something

Example:

>>> def print_hello():
>>>     print("Hello")

>>> print_hello()
Hello
>>> def run_check(num,low,high):
>>>     if num in range(low,high):
>>>         print (f"{num} is in the range between {low} and {high}")
        
>>> run_check(5,2,7)
5 is in the range between 2 and 7

When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:

Example:

>>> import math
>>> def vol(rad=5):
>>>    V = 4/3 * math.pi* rad**3 
>>>    return V

>>> vol()
523.5987755982989

Example:

>>> def latin(word):
>>>     first_letter = word[0] 
>>>     if first_letter in "aeiou":
>>>         pig_word = word + "ay"
>>>     else:
>>>         pig_word = word[1:] + first_letter + "ay"        
>>>     return pig_word

>>> latin("apple")
'appleay'

Classes

Dataclasses are python classes but are suited for storing data objects. This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.

self

__init__()

Example:

>>> class Vehicle():
>>>     def __init__(self, colour, nb_wheels, name):
>>>         self.colour = colour
>>>         self.nb_wheels = nb_wheels
>>>         self.name = name
>>> vehicle_1 = Vehicle("blue", 2, "bike")
>>> vehicle_2 = Vehicle("red", 4, "car")

>>> print("This is a " + vehicle_1.colour + " " + vehicle_1.name + " with ", vehicle_1.nb_wheels, " " + "wheels")
This is a blue bike with  2  wheels
>>> print("This is a " + vehicle_2.colour + " " + vehicle_2.name + " with " + str(vehicle_2.nb_wheels) + " " + "wheels")
This is a red car with 4 wheels

Example:

>>> class Rectangle:
>>>    def __init__(self, length, breadth, unit_cost=0):
>>>        self.length = length
>>>        self.breadth = breadth
>>>        self.unit_cost = unit_cost
>>>    def get_area(self):
>>>        return self.length * self.breadth
>>>    def calculate_cost(self):
>>>        area = self.get_area()
>>>        return area * self.unit_cost
>>> r = Rectangle(160, 120, 2000)
>>> print("Area of Rectangle: %s sq units" % (r.get_area()))

Area of Rectangle: 19200 sq units

Import

>>> import math
>>> print(math.pi)

3.141592653589793
>>> from math import pi 
>>> print(pi) 

3.141592653589793

In Grasshopper, COMPAS is imported from within a GhPython component. To verify that everything is working properly, simply create a GhPython component on your Grasshopper canvas, paste the following script and hit OK

import compas

from compas.datastructures import Mesh
from compas_ghpython.artists import MeshArtist
mesh = Mesh.from_obj(compas.get('faces.obj'))

artist = MeshArtist(mesh)

a = artist.draw_mesh()