Title: CS1315: Introduction to Media Computation
1Python Mechanics
- Save program in
- C\100\xxx.py
- In Command Prompt window,
- import xxx
- Execute a function by xxx.yyyy()
- Program syntax
- var .
- def func1(arg1, arg2,..)
- for var in range(min,max)
- if (cond)
2What if we want a function drawS() to draw a
square of different sizes ?
def drawSquare(myTurtle) myTurtle.forward(100
) myTurtle.right(90)
def drawSquare(myTurtle, sideLength)
myTurtle.forward(sideLength)
myTurtle.right(90)
3LAB 3 Write drawCircle()
def drawORings(ttt) ttt.goto(0,0)
ttt.color(blue) drawCircle(ttt)
ttt.goto(150,0) ttt.color(black)
drawCircle(ttt) ttt.goto(300,0)
ttt.color(red) drawCircle(ttt) def
drawCircle(t) t.down() t.circle(100)
t.up()
def drawORings(ttt) drawCircle(ttt,blue,
0,0) drawCircle(ttt,black, 150,0)
drawCircle(ttt,red, 300,0) drawCircle(ttt,
drawCircle(ttt, def drawCircle(t,tColor, tX,
tY) t.goto(tX,tY) t.color(tColor)
t.down() t.circle(100) t.up()
4Random Walk
import random def randNext(curX, curY)
nextX curX - 50 100random.random()
nextY curY - 50 100random.random()
return nextX, nextY def drawRandom(myT, nX, nY,
n) for i in range(0,n) (cX,cY)
(nX, nY) (nX, nY) randNext(cX, cY)
myT.goto(nX, nY)
5Random Walk with Boundary
def drawRandom(myT, nextX, nextY, n) wn
myT.Screen() myH wn.window_height() myW
wn.window_width() for i in range(0,n)
(curX,curY) (nextX, nextY) (nextX,
nextY) randNext(curX, curY) if nextX lt
-myW/2 nextX -myW3/4 if nextX gt
myW/2 nextX myW3/4 if nextY lt
-myH/2 nextY -myH3/4 if nextY gt
myH/2 nextY myH3/4
myT.goto(nextX, nextY)
6 Pictorial view of how if works
if (expression)
false
true
next indented block
else Statements
7Conditional
if a gt b c0 else c20
if (condition) statements else
statements
if a gt b if x y c0 else
c-4 else c20
if (condition) else statements
if (condition) statements else
statements
8if..else
- Use random numbers to compute an approximation of
pi - Simulation of a special game of darts
- Randomly place darts on the board
- pi can be computed by keeping track of the number
of darts that land on the board
9Dart Board
10Selection Statements
- Ask a question (Boolean Expression)
- Based on the answer, perform a task
11Monte Carlo Simulation
import random import math def montePi(numDarts)
inCircle 0 for i in range(0,
numDarts) x random.random() y
random.random() d math.sqrt(x2 y2)
if d lt 1 inCircle inCircle
1 pi inCircle/numDarts 4 return pi
12Complete Program
import random import math import turtle def
showMontePi(numDarts) wn turtle.Screen()
dartT turtle.Turtle() wn.setworldcoordinat
es(-2,-2,2,2) dartT.up()
dartT.goto(-1,0) dartT.down()
dartT.goto(1,0) dartT.up()
dartT.goto(0,1) dartT.down()
dartT.goto(0,-1) circle 0
dartT.up()
for i in range(numDarts) x
random.random() y random.random()
d math.sqrt(x2 y2)
dartT.goto(x,y) if d lt 1
circle circle 1
dartT.color("blue") else
dartT.color("red)
dartT.dot() pi circle/numDarts 4
wn.exitonclick() return pi
13Figure 2.14