Python‎ > ‎

Basic Structure

or y -- if x is false, then y, else x
and y -- if x is false, then x, else y
not x -- if x is false, then True, else False

"not" has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

def toggleVisibility(obj):
cmds.setAttr (obj+'.visibility', 
not cmds.getAttr (obj+'.visibility'))

(Jacob Borsting)


Mel version
if ($blah == 1)
    //do something
else if ($blah == 2)
    //do something else
    //last thing

Python version
if blah == 1:
    #do something
elif blah == 2:
    #do something else
    #last thing

what about an empty if or else?

if (i don't want anything to happen):
    #do something

How do I check if an object exists?

if mc.objExists('myObject'):
    print 'your object already exists!'
    #make myObject

For Loop

MEL Version

for ($s in $sel)

Python Version

for s in sel:

Mel Version

int $i;

for ($i = 0; $i < 4; i++)

Python Version

for i in range(4):

>>> range(-10, -100, -30)
[-10, -40, -70]
In the above range case, the range betw. -10 and -100 is being evaluated by an increment of -30 (



It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.


The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.


The break statement, like in C, breaks out of the smallest enclosing for or while loop.

The continue statement, also borrowed from C, continues with the next iteration of the loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3


Great post on Python eval vs. mel eval by Ryan Trowbridge


Understanding Python with (Fredrik Lundh)

def clickButton(value):
print "Value", value

import pymel.core as pm
with pm.window():
with pm.rowColumnLayout():
pm.button(label="First button", c=pm.Callback(clickButton, "klicked"))

Here you can see how the with statement works. And additionaly you can use the Callback() class to simplify the calling of callbacks. Really cool and much more efficient then in mel. 


Simple Decorator Example (Chris Evans)

Simple Math


Dividing using a normal backslash will return a whole integer.
Therefore 4/2 will be 2, but 1/3 = 0!
To get a decimal number, put a point after one or both of the numbers in the division:
1./3 = 0.333333333
8./3. = 2.666666667


What is the equivalent of MEL rand in Python?

In MEL I can execute this:
float $randomize = rand(0,100);
print $randomize

In python I can execute this:
import random as rand
randomize = rand.uniform(0,100)
print randomize

(from cgtalk)

or, likesay,
random.randint(a, b)  (but this only returns integers! :( )
random.uniform(a, b)  (this returns float vals  ^ - ^ )

(module link here)


teste = raw_input('group name:' ),name=teste)

How to generate the same function using cmds.textField in a window?

Thanks to anyone who can help.

Michiel Duvekot <> Dec 04 06:39PM -0800 ^

import maya.cmds as cmds

def doIt():,name=(cmds.textField('userInput', q=True,

cmds.button(l='group', c='doIt()')

Defining Empty Variables

myString = ''
myList = []
myInt = 0

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)