# Python Intro #02 | Function – Random Walk

### Contents

- Random Walk
- Initial Setup
- Loop

- Function
- Concept
- Declaration/ Arguments / Return
- Usage

- Practice – Multiple Random Walks
- Random walk with function
- Initial Setup
- Loop

### Random Walk

#### Initial Setup

import rhinoscriptsyntax as rs import random import math points = [] point = rs.AddPoint(0,0,0) points.append(point)

#### Loop

for i in range(x): theta = (random.random()-0.5)*math.pi*2 point = rs.CopyObject(point) rs.MoveObject(point,[math.cos(theta)*y,math.sin(theta)*y,0]) points.append(point)

### Function

#### Concept

Function is the advanced feature in programming and is useful to make scripts more smart. Function is similar to the function in mathematics, it needs a couple of arguments (0 argument is also possible), and return several values as result.

Function is something like components in Grasshopper. They have some inputs and outputs. Arguments are inputs and Returns are output.

#### Declaration / Arguments / Return

The syntax to define functions is following:

def <function name>(<arguments>): ... return <value to return>

Following is the simplest example of function:

def addition(s,t): f = s+t return f

#### Usage

Using function is very easy. Following is a example to use previous function:

def addition(s,t): return s+t a = addition(x,y)

### Practice – Multiple Random Walks

#### Random Walk with Function

import rhinoscriptsyntax as rs import random import math points = [] point = rs.AddPoint(0,0,0) points.append(point) def moveRandom(pt, range): theta = (random.random()-0.5)*math.pi*2 returnPt = rs.CopyObject(pt) rs.MoveObject(returnPt,[math.cos(theta)*y,math.sin(theta)*y,0]) return returnPt for i in range(x): newPt = moveRandom(point, y) point = newPt points.append(newPt) a=rs.AddPolyline(points)

#### Multiple Random Walk

import rhinoscriptsyntax as rs import random import math def moveRandom(pt, range): theta = (random.random()-0.5)*math.pi*2 returnPt = rs.CopyObject(pt) rs.MoveObject(returnPt,[math.cos(theta)*y,math.sin(theta)*y,0]) return returnPt listOfPoints = [] for j in range(10): points = [] point = rs.AddPoint(0,0,0) points.append(point) for i in range(x): newPt = moveRandom(point, y) point = newPt points.append(newPt) listOfPoints.append(points) listOfPolylines = [] for j in range(10): pl = rs.AddPolyline(listOfPoints[j]) listOfPolylines.append(pl) a = listOfPoints