Data Types and Variables

Now that we know how to setup and run Python scripts, we can start learning how to write Python scripts.

Variables

The most common concept in almost all scripting and programming languages is the variable. A variable is a storage container for some type of data:

Figure 10 - Variables

Variables allow us to store data in order to use it later. Variables, sometimes called identifiers, must start with a non-numeric character or underscore (_), may contain letters, numbers, underscores (_). Identifiers are case sensitive. It is always a good idea to name your variables with descriptive names so your code is easy to read.

Legal variable names

  • joint_count
  • button1
  • teeth_geometry
  • _particle_effect

Illegal variable names

  • finger.nail
  • 4vertexEdgeId
  • cluster-handle

Python is a dynamically typed language. This means that a variable can hold one type of value for a while and then can hold another type later.

x = 5
x = 'Now x holds a string'

Not all languages allow you to do this. For example, in MEL, you have to declare a variable as an integer and then that variable can only hold an integer. This is what is known as a statically typed language.

Numbers and Math

There are 5 different types of number representions in Python: integers, long integers, floating-point, octal/hex, and complex numbers. The two representations that you will work with the most are integers and floating-point literals. Integers are numbers without a decimal point. Floating-point numbers are numeric values with a decimal point.

Integers

  • 43
  • -9234
  • 6

Floating-point

  • 1.324
  • -23.5325
  • 6.2

Python supports all the math operators that you would want to use on these numbers.

x = 4 + 5          # Addition
y = x – 8          # Subtraction
y = y * 2.2        # Multiplication
z = y / 1.2        # Division
z = y // 3         # Floor division
z = z ** 4         # Power
z = -z             # Negation
a = 10 % 3         # Modulus (division remainder)
x += 2             # Addition and store the result back in x, same as x = x + 2
x -= 2             # Subtraction and store the result back in x
x *= 2             # Multiplication and store the result back in x
x /= 2             # Division and store the result back in x

Notice in some of these statements, I use the same variable on both the right and left side of the assignment operator (=). In most programming languages, the right side is evaluated first and then the result is stored in the variable on the left. So in the statement y = y * 2.2, the expression y * 2.2 is evaluated using the current value of y, in this case 1, and then the result (1 * 2.2) = 2.2 is stored in the variable y.

Math operators have a precedence of operation. That is, some operators always execute before others even when in the same expression. For example the following two lines give different results:

print((5 + 3.2) * 2)
16.4
print(6 + 3.2 * 2)
12.4

Multiplication and division always get evaluated before addition and subtraction. However, you can control which expressions get evaluated first by using parentheses. Inner most parentheses always get evaluated first.

3 * (54 / ((2 + 7) * 3)) – 4
3 * (54 / (9 * 3)) – 4
3 * (54 / 27) – 4
3 * 2 – 4
6 – 4
2

When you mix integers and floating-point values, the result will always turn into a floating-point:

4 * 3.1
# Result: 12.4 #

However, you can explicitly turn an int to a float or a float to an int.

int(4 * 3.1)
# Result: 12 #
float(12)
# Result: 12.0 #

Strings

Strings are text values. You can specify strings in single, double or triple quotes.

'This is a string'                           # Single quotes
"This is also a string"                      # Double quotes
"""This string can span multiple lines"""    # Triple quotes

Single and double quoted strings are the same. The main thing to keep in mind when using strings are escape sequences. Escape sequences are characters with special meaning. To specify an escape code, you use the backslash character followed by a character code. For example, a tab is specified as ‘\t’, a new line is specified as ‘\n’. You have to be mindful whenever escape sequences are involved because they can lead to a lot of errors and frustration. For example, in Windows, paths are written using the backslash: (e.x. C:\tools\new). If you save this path into a string, you get unexpected results:

print("C:\tools\new")
C:	ools
Ew

Python reads the backslashes as an escape sequence. It thinks the ‘\t’ is a tab and the ‘\n’ is a new line. To get the expected results, you either use escaped backslashes or a raw string:

print("C:\\tools\\new")
C:\tools\new
print(r"C:\tools\new")
C:\tools\new

The easiest thing to do in this case is to always use forward slashes for paths because Python will find the right file whether on Windows or not.

You can concatenate strings together with the + operator.

x = 'I am '
y = '25 years old.'
print(x + y)
I am 25 years old.

However, you cannot add a string and a number.

x = 'I am '
y = 25
print('I am ' + y)
# Error: cannot concatenate 'str' and 'int' objects
# Traceback (most recent call last):
#   File "", line 3, in
# TypeError: cannot concatenate 'str' and 'int' objects #

Python will throw an error saying you cannot concatenate a string and an integer. You can fix this in a couple different ways. One way is to convert the integer to a string.

x = 'I am '
y = 25
print('I am ' + str(y))
I am 25

The better way is to use string formatting.

String Formatting

String formatting allows you to code multiple string substitutions in a compact way. You use string formatting with the format function available on all strings.

x = 'I am'
y = '32 years old.'
print('{0} {1}'.format(x, y))
I am 32 years old.
y = 32
print('I am {0} years old.'.format(y))
I am 32 years old.

The format function allows you do automatically convert multiple variables into a string. The numbers within the curly braces represent the index of argument within the format function.

'{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
'{}, {}, {}'.format('a', 'b', 'c')  # Python 2.7+ only
'a, b, c'
'{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
'{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
'{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

You can also use the format function to control decimal precision, string alignment, as well as adding zero-padding to strings. To read more about string formatting, visit the documentation.

You can also format strings with the % operator.

x = 'I am '
y = '25 years old.'
print('%s%s’ % (x, y))
I am 25 years old.
x = 'I am '
y = 25
print('%s%d’ % (x, y))
I am 25

To use the % operator, you provide a format string on the left of the % operator and the values you want to print on the right of the % operator. Different types of values have different format codes. Common codes include:

  • %s – string
  • %d, %i – integer
  • %f – floating-point

In the second example above, ‘%s%d’ % (x, y) contains two format codes, a string followed by an integer. On the right side of the % operator, we need to specify a value for each of the format codes in the order they appear in the format string. String formatting not only lets us code in a more compact way, it also lets us format values for output:

print('%03d' % 5)
005
print('%+03d' % 6)
+06
print('%+03d' % -4)
-04
print('%.5f' % 4.4242353534)
4.42424

Like the format method, the % operator allows us to specify decimal precision, how many spaces a number should be printed with, whether to include the sign, etc. This is especially useful when printing out large tables of data. To read more about the % operator in string formatting, visit the documentation.

String Methods

Methods are chunks of code that perform some type of operation. We will learn more about methods, also known as functions, in more detail later on, but now is a good time to introduce you to the syntax of calling a method. We call a method using the dot operator (.):

object.method()

An object is an instance of a particular type. For example, we could have a string object.

x = 'This is a string.'    # x is a string object
y = 'Another string.'      # y is another string object

When we read the code, some_object.some_method(), we say we are calling the method named some_method from the object called some_object. Most objects have many callable methods. The format method described in the previous section is a string method. Below are some of the methods found in string objects:

x = 'This is my example string.'
print(x.lower())
this is my example string.
print(x.upper())
THIS IS MY EXAMPLE STRING.
print(x.replace('my', 'your'))
This is your example string.
print(x.title())
This Is My Example String.
print(x.endswith('ng.'))
True
print(x.endswith('exam'))
False

Some of the methods have arguments in the parentheses. Many methods allow you to pass in values to perform operations based on the arguments. For example x.replace(‘my’, ‘your’) will return a copy of string x with all of the ‘my’ instances replaced with ‘your’. To view a list of the available string methods, visit the documentation.

There are many methods available for many different types of objects and there is no need to memorize them. You will begin to memorize them after using them a lot. You can find help documentation for all objects with the help command.

help(str)

The help command will print out the documentation associated with an object, class, or function.

Lists

Lists are sequences or arrays of data. Lists allow us to use organized groups of data in our scripts.

list_of_lights = ['keyLight', 'rimLight', 'backLight', 'fillLight']
print(list_of_lights[0])     # print the first element
keyLight
print(list_of_lights[2])     # print the third element
backLight
print list_of_lights[3])     # print the fourth element
fillLight
print(list_of_lights[-1])    # print the last element
fillLight
print(list_of_lights[0:2])   # print the first through second elements
['keyLight', 'rimLight']
print(len(list_of_lights))   # print the length of the list
4

We can access elements in a list with a numeric index. The indices start at index 0 and increment with each value in the list. We can also access subsets of lists with slicing

print(list_of_lights[0:2], list_of_lights[:3], list_of_lights[:-1])
['keyLight', 'rimLight'] ['keyLight', 'rimLight', 'backLight'] ['keyLight', 'rimLight', 'backLight']
list_of_lights[0:2] = ['newLight', 'greenLight']
print(list_of_light)
['newLight', 'greenLight', 'backLight', 'fillLight']

When an index is negative, it counts from the end of the list back. Lists can also contain mixed types of data including other lists.

my_list = [3, 'food', [another_list, 4 * 2, 'dog'], 80.3]
print(my_list[2][1])
8

When you try to access an element that does not exist, Python will throw an error.

print(my_list[34])
# Error: list index out of range
# Traceback (most recent call last):
#   File "", line 1, in 
# IndexError: list index out of range #

Lists, like strings, have their own set of methods available.

list_of_lights = ['keyLight', 'rimLight', 'backLight', 'fillLight']
list_of_lights.sort()
print(list_of_lights)
['backLight', 'fillLight', 'keyLight', 'rimLight']
list_of_lights.reverse()
print(list_of_lights)
['rimLight', 'keyLight', 'fillLight', 'backLight']
list_of_lights.append('newLight')
print list_of_lights
['rimLight', 'keyLight', 'fillLight', 'backLight', 'newLight']

This concept of indexing is not unique to lists. We can actually access strings the same way.

x = 'Eat your vegetables'
print(x[0:6])
Eat yo
print(x[:-9])
Eat your v
print(x[5:])
our vegetables
print(x.find('veg'))
9
print(x.split('e'))
['Eat your v', 'g', 'tabl', 's']

You can think of strings as lists of characters. The main difference is strings cannot be edited in place with indices. For example, the following is illegal.

x[4] = 't'
# Error: 'str' object does not support item assignment
# Traceback (most recent call last):
#   File "", line 1, in
# TypeError: 'str' object does not support item assignment #

Strings are what are known as immutable objects. Once they are created, they cannot be changed. Lists on the other hand are mutable objects, meaning they can change internally.

Tuples

Tuples are the same as lists except they are immutable. They cannot be changed once created.

my_tuple = (5, 4.2, 'cat')
my_tuple[1] = 3
# Error: 'tuple' object does not support item assignment
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: 'tuple' object does not support item assignment #

What is the purpose of tuples? There are aspects of Python that use or return tuples. I’d say 99.9% of the time, you’ll be using lists. Just be aware that you cannot change a tuple when one eventually pops up.

Dictionaries

Dictionaries are like lists except their elements do not have to be accessed with numeric indices. Dictionaries are a type of look-up table or hash map. They are useful in storing unordered types of data.

characters = {'male': ['Derrick', 'Chad', 'Ryan'], 'female': ['Olivia', 'Sarah', 'Zoe']}
print(characters['male'])
['Derrick', 'Chad', 'Ryan']
print(characters['female'])
['Olivia', 'Sarah', 'Zoe']

# Same functionality, different syntax:
characters = dict(male=['Derrick', 'Chad', 'Ryan'], female=['Olivia', 'Sarah', 'Zoe'])
print(characters['male'])
['Derrick', 'Chad', 'Ryan']
print(characters['female'])
['Olivia', 'Sarah', 'Zoe']

# Some methods of dictionaries
print(characters.keys())
['male', 'female']
print(characters.values())
[['Derrick', 'Chad', 'Ryan'], ['Olivia', 'Sarah', 'Zoe']]
print('male' in characters.keys())
True
print('clown' in characters.keys())
False
# Elements can be added on the fly
characters['alien'] = ['ET', 'Alf']
characters[6] = 4.5

Booleans and Comparing Values

In many of your programs, you’ll need to determine the relationship between variables such as if values are equal or if a value is greater than or less than another. These comparisons return a boolean value. A boolean value is simply True or False. You have already seen these values returned in a few of the previous examples.

x == y  # tests if x is equal to y
x != y  # tests if x does not equal y
x > y   # tests if x is greater than y
x < y   # tests if x is less than y
x >= y  # tests if x is greater than or equal to y
x <= y  # tests if x is less than or equal to y
x = 4.3
y = 2
5 == 5, 5 == 8, x == y, x == 4.3
(True, False, False, True)
x <= y, x > y, x == y + 2.3, x >= 93
(False, True, True, False)
a = 'alpha'
b = 'beta'
a > b, a == 'alpha', a < b
(False, True, True)

The following values are also considered False:

''           # Empty strings
[]           # Empty lists
{}           # Empty dictionaries
0            # 0 valued numbers
None         # An empty value

The following values are considered True:

'text'       # Strings with any characters
[2, 3]       # Lists with elements
{3 : 4.5}    # Dictionaries with elements
2.3          # Non-zero numbers

2 thoughts on “Data Types and Variables”

Sindre June 9, 2015 at 3:14 pm

In the last example regarding booleans, why does the string “beta” evaluate as larger than “alpha”? I would have assumed the opposite would be true since alpha consists of 5 characters whereas beta is 4. How are strings compared in a boolean outside of exact matches?

Chad June 20, 2015 at 11:13 am

Python doesn’t use string length to compare strings, it uses the alphanumeric order. a comes before b so alpha is less than beta.

Leave A Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

<code> For inline code.
[sourcecode] For multiline code.