
Useful Python Resources
python.org
jedit.org
http://www.youtube.com/view_play_list?p=EA1FEF17E1E5C0DA
Maya Python for Games and Film: A Complete Reference for
Maya Python and the Maya Python API [Hardcover]
by Adam Mechtley & Ryan Trowbridge
http://www.amazon.com/Maya-Python-Games-Film-Reference/dp/0123785782/ref=sr_1_1?ie=UTF8&qid=1319180791&sr=8-1
Google "python command" ..eg "python
range", "python len"

Variables
A variable is piece of memory that contains data
(value), such as a number or text. The contents of the
memory (value) can change when necessary.
In it's simplest form, a
variable is a box, with a name. These boxes can
contain different types of data (value).
Therefore, a variable is defined as having 3 properties...
- name : a label
to retrieve and modify the value of the variable.
- type :
|
type |
|
definition |
|
example |
|
Python syntax |
|
int (integer)
|
|
whole number
|
|
1, 56, 141,
-6 |
|
fmInt=1 |
|
float
(floating point) |
|
decimal number |
|
3.141, -30.93 |
|
fmFloat=3.141 |
|
string (text) |
|
text
characters |
|
a, bcd, e!? |
|
fmString="fridgemonsters" |
|
list (array)
|
|
collection of
values |
|
all of the
above |
|
fmList=[1,2,3,4] |
- value : the
content of the variable.
Creating a variable is
called "declaring a variable".
Giving a value to a variable is called "assigning a
variable"
In Python, a variable in declared and assigned a value
in the same line.
eg fmFloat=3.141
In other programming languages, the user is required to
define the type of variable. ...type, name and value.
eg float $fmFloat=3.141 or int $myVal=42
Python does not require the user to define the type.
However, it is important you understand that Python is
automatically assigning the type for you, as you
can not mix variables with different types later in your
programme.
#Declaring and assigning a list type. Then using a for
loop to print each element in the list.
listClassList=["chris","malcom","nick","livia"]
for myCount in listClassList:
print myCount
#Declaring and assigning a list
type. Then using a for loop and range function to print
each element in the list.
myChars=["f","r","i","d","g","e"]
for i in range(len(myChars)):
print i
#############################################
Teaching myself via Digital Tutors
#this is a
comment - a line in the code that starts with # is ignored
by Python
"""
this is a blocked out comment - a block begins (line above)
and ends (line below) with """ (3 quotes)
"""
#import the
maya commends into Python
import maya.cmds as mc
#create a default polyCube with
width=1, height=1 and depth=1
mc.polyCube()
#create a polyCube with argument
values (parameters)
mc.polyCube(w=3,h=5,d=8,sd=2,sh=3,sw=5,ch=True)

#select pCube1
mc.select("pCube1")
#scale
pCube1 by 50% in X, Y and Z axis
mc.scale(0.5,0.5,0.5,r=True)
#creating a
cube and bevelling it
cubeToBevel=mc.polyCube(w=10,h=5,d=20)
mc.polyBevel(cubeToBevel,offset=0.2, offsetAsFraction=1,
autoFit=1,segments=1, worldSpace=1, uvAssignment=0,
fillNgons=1, mergeVertices=1, mergeVertexTolerance=.0001,
smoothingAngle=0, miteringAngle=80, angleTolerance=80, ch=1)

#creating and
defining
a text string and concatenating
(appending it with more text)
original = "Fridgemonsters is cool"
myStr = original + "...and we love Python"
print myStr
Variable Type (string, int,
float, list)
#creating and defining an int type variable (integer) and
appending it to a string type
intLife=42
print "the value of intLife is : %d" % intLife
#creating and
defining a float type variable (decimal point) and appending
it to a string type
fPi=3.1415926
print "The value of Pi is %f" % fPi
#Appending an
int and a float type variable to a string type
print "The meaning of Life is %d and the value of Pi is %f"
% (intLife,fPi)
#creating
list type (array) which can contain
different types
myFirstList=["red",21.00,1]
#print the
whole list
print myFirstList
#print
the 1st element on the list
print myFirstList[0]
range() function
range() : (start
value, stop value, increment value)
It is most often used in for loops. The arguments must be
plain integers. If the step argument is omitted, it defaults
to 1.
If the start argument is omitted, it defaults to 0.
#One
argument defined.
#By default, starts counting from 0, incrementing by 1.
Stops at 4
fmRangeList=[range(4)]
print fmRangeList
Result : [0, 1, 2, 3]
#Two arguments defined.
#Starts counting from 1. Stops counting at 5.
#By
default, counting is incremented by 1
fmRangeList=[range(1,5)]
print fmRangeList
Result : [1, 2, 3, 4]
#Three
arguments defined.
#Starts counting from 1. Stops counting at 10.
#Counting
is incremented by 1
fmRangeList=[range(1,10,1)]
print fmRangeList
Result : [1, 2, 3, 4, 5, 6, 7, 8, 9]
#Three
arguments defined.
#Starts counting from 1. Stops counting at 10.
#Counting
is incremented by 2
fmRangeList=[range(1,10,2)]
print fmRangeList
Result : [1, 3, 5, 7, 9]
#Three
arguments defined.
#Starts counting from 10. Stops counting at 1.
#Counting
is incremented by -1
fmRangeList=[range(10,1,-1)]
print fmRangeList
Result : [10, 9, 8, 7, 6, 5, 4, 3, 2]
for loop
#create
4 polyCubes and move space them 6 units apart on the X axis
for i in range(4):
fmCubeObj=mc.polyCube(w=2,h=2,d=2)
mc.move((6*i),0,0,fmCubeObj,r=True)

#creating a
list (listObjs) and assign all select objects to the list
listObjs=mc.ls(sl=True)
#print
the list
print listObjs
#calculate
the size(length) of the list then print that value
selSize=len(listObjs)
print selSize
"""
range() :
In the example below the for loop
is going to loop from 0 to the stop value (selSize) and
increment by 1
Note : the colon on the end of the for loop and the
indented commands below the for loop
"""
for i in range(0,selSize,1):
print "Object %d" %i
print listObjs[i]
print "done"
#alternative print code to the
example above that prints as one line
for i in range(0,selSize,1):
print "Object %d is : " %(i+1) + listObjs[i]
##################################################
#
#User : Create 4 Polygon Cubes and space them along the X
axis
#then parent them together
#
#Code :
Assigns
selected objects to a list and parents 1st to 2nd, etc
#
##################################################
fmSelList=mc.ls(selection=True)
for i in range(len(fmSelList)-1):
mc.parent(fmSelList[i],fmSelList[i+1])

##################################################
#
#User : Create 4 Polygon Cubes and space them along the X
axis
#
#Code : Assigns selected objects to a list and scale by a
scale factor that
#increments by 0.5 (1,1.5,2,2.5...)
#
##################################################
import maya.cmds as mc
listObjs=mc.ls(sl=True)
selSize=len(listObjs)
for i in range(0,selSize,1):
rescaler = 1+(i*0.5)
mc.scale(rescaler,rescaler,rescaler,listObjs[i],
r=True)

##################################################
#
#Creates 10 polySpheres. Moves each object 3 units in the X
axis and
#alternate objects 5 units in Y axis.
#
##################################################
import maya.cmds as mc
sphereNum=10
for i in range(0,sphereNum,2):
sphere=mc.polySphere()
mc.move(3*i,0,0,sphere[0])
sphere=mc.polySphere()
mc.move(3*(i+1),5,0,sphere[0])

##################################################
#
#Create a polyPipe and select all the faces around the
outside
#
##################################################
import maya.cmds as mc
#create a polyPipe
pipeGear=mc.polyPipe(r=6,h=5,t=1.5)
#get the value for Subdivisions
Axis (face around the circumference (default 20)
intSA=mc.getAttr(pipeGear[1]+".subdivisionsAxis")
"""
the faces around the outside edge are numbered 40 - 59
the range function requires a start value (40) and stop
value (60).. See below
calculate the start face id number (40)
"""
intStartVal=intSA*2
#calculate the stop value : end
face id number (default 59)
intStopVal=(intSA*3)
#deselect everything
mc.select(deselect=True)
#select all the faces around the
outside edge
for i in range(intStartVal,intStopVal,1):
mc.select(pipeGear[0]+".f[%d]" %i, add=True)

##################################################
#
#Create a polyPipe and select alternate faces around the
outside.
#Extrude the selected faces by 2.5.
#
# Explain here how the pipeGear[0] and pipeGear[1]
works here
#
##################################################
import maya.cmds as mc
pipeGear=mc.polyPipe(r=6,h=5,t=1.5)
intSA=mc.getAttr(pipeGear[1]+".subdivisionsAxis")
intStartVal=intSA*2
intStopVal=(intSA*3)
mc.select(clear=True)
#select alternate faces around the
outside edge
#notice incremental count is 2
for i in range(intStartVal,intStopVal,2):
mc.select(pipeGear[0]+".f[%d]" % i, add=True)
#extrude selected faces 2.5 in the
local Z Axis
mc.polyExtrudeFacet(ltz=2.5)
#deselect everything
mc.select(deselect=True)

#######################################################
#
#Open a Prompt window for User to input number of
#required teeth then creates the gear.
#
#######################################################
import maya.cmds as mc
pdStatus=mc.promptDialog(message="Input number of
teeth", button="OK")
# pdStatus will return either "OK" or
"dimiss"
print pdStatus
if pdStatus == "OK":
numTeeth=mc.promptDialog(query=True, text=True)
#convert Unicode (text) to an int (integer) value
numTeeth=int(numTeeth)
pipeGear=mc.polyPipe(r=1,h=0.5,t=0.25, sa=numTeeth*2)
intSA=mc.getAttr(pipeGear[1]+".subdivisionsAxis")
intStartVal=intSA*2
intStopVal=(intSA*3)
mc.select(clear=True)
#select alternate faces around the outside edge
#notice incremental count is 2
for i in range(intStartVal,intStopVal,2):
mc.select(pipeGear[0]+".f[%d]" % i, add=True)
#extrude selected faces 0.5 in the
local Z Axis
mc.polyExtrudeFacet(ltz=0.5)
#deselect everything
mc.select(deselect=True)

#######################################################
#######################################################
#
# Randomiser Tool
#
#######################################################
import maya.cmds as mc
import random
selList=mc.ls(selection=True)
for eachObj in selList:
rangeX=random.randint(-10,10)
rangeZ=random.randint(-10,10)
mc.setAttr(eachObj + ".translateX", rangeX)
mc.setAttr(eachObj + ".translateZ", rangeZ)

#######################################################
#list the functions in the random
class
help(random)
#######################################################
#
# Randomiser Window with User Input
#
#######################################################
import maya.cmds as mc
import random
# function to randomise selected
objects translate value
def fmRand():
selList=mc.ls(selection=True)
#query the 3 value input by the
User into fmRangeFieldGrp
rangeX=mc.floatFieldGrp(fmRangeFieldGrp,query=True,value1=True)
rangeY=mc.floatFieldGrp(fmRangeFieldGrp,query=True,value2=True)
rangeZ=mc.floatFieldGrp(fmRangeFieldGrp,query=True,value3=True)
for eachObj in selList:
valX=random.randint(-rangeX,rangeX)
valY=random.randint(-rangeY,rangeY)
valZ=random.randint(-rangeZ,rangeZ)
mc.setAttr(eachObj + ".translateX", valX)
mc.setAttr(eachObj + ".translateY", valY)
mc.setAttr(eachObj + ".translateZ", valZ)
#function end
#Define Window and Buttons/Fields
#Check if the window is already
exists.
#If it does, Delete it..!!
if mc.window("fmRandWin", exists=True):
mc.deleteUI("fmRandWin",window=True)
if mc.window(window,
exists=True):
mc.deleteUI( window,
window=True )
window = mc.window(title="fmRandomiser",
wh=(200,100))
mc.paneLayout()
mc.button()
mc.showWindow( window )
#Create a Window and assign it to
memory (fmRanWin)
fmRandWin=mc.window(title="fmRandomiser", wh=(300,200))
#Default column layout in window
mc.columnLayout(adjustableColumn=True)
#Create a button with a label
mc.button(label="Randomise Objs", command="fmRand()")
#Use input values for..
#Text label (instructions to User)
mc.text(label="Set X Y Z Range Values")
fmRangeFieldGrp=mc.floatFieldGrp(numberOfFields=3)
#Launch the Window
mc.showWindow(fmRandWin)
#######################################################
#
# while loop
#
#######################################################
i=0
while(i<10):
print i
i+=1
#while loop with if/else statement and
break
i=0
while(i<10):
print i
if i==5:
break
else:
i+=1
#######################################################
#
#while loop through the frmaes on the TimeLine
#
#######################################################
import maya.cmds as mc
startFrame=mc.playbackOptions(query=True,minTime=True)
endFrame=mc.playbackOptions(query=True,maxTime=True)
currentFrame=startFrame
while(currentFrame<endFrame):
print "The current frame is %d" % currentFrame
mc.currentTime(currentFrame)
currentFrame+=1
#######################################################
#
#while loop through the frames on the TimeLine
#
#######################################################
import maya.cmds as mc
startFrame=mc.playbackOptions(query=True,minTime=True)
endFrame=mc.playbackOptions(query=True,maxTime=True)
currentFrame=startFrame
while(currentFrame<endFrame):
print "The current frame is %d" % currentFrame
mc.currentTime(currentFrame)
currentFrame+=1
#######################################################
#
#while loop through the frames
on the TimeLine and set
#keyframes.
#
#######################################################
Dimport
maya.cmds as mc
startFrame=mc.playbackOptions(query=True,minTime=True)
endFrame=mc.playbackOptions(query=True,maxTime=True)
currentFrame=startFrame
target="pCube"
while(currentFrame<endFrame):
print "The current frame is %d" % currentFrame
mc.currentTime(currentFrame)
currentFrame+=1
###############################################
#
# Chapter 22 - 26
#
###############################################
import maya.cmds as mc





