Python 101


The Basics

We'll start by quickly outlining some key concepts of programming Throughout, we'll be conforming to "PEP8" coding standards, which is the preferred style for python

Read more about PEP8 standards

Variables

As we write our code and scripts, we will need to move data around and manipulate it. We do this by storing data in variables. Variables can be "assigned" and "edited".

Variables are all written using "snake case". This means when you write them, they should:

  • be all lower case
  • have each word separated by an underscore

They should also be appropriately named to make your code easy to read. Avoid simplistic variables like "x" or "y" unless they make sense (like iterating through texture pixels)

Integer

A counter of objects would use an "integer" - this is a whole number (e.g 1,2,3,4 etc)

# Start with 4
number_of_bananas = 4
print number_of_bananas

# Now lets remove 2 from the variable
number_of_bananas = number_of_bananas - 2
print number_of_bananas

Float

A "float" is any number that contains a decimal point (it's short for "floating point")

# Start with set distance
distance = 2.4
print distance

# Now lets multiply by 2
distance = distance * 2
print distance

Strings and string slicing

String variables are basically any value that contains letters, such as words, node names, file paths, URLs etc

fruit = 'banana'
print fruit

# We can query the number of characters in a string
print len(fruit)

# We can also strip the string. This is called "string slicing"
# Here we cull the string one character from the left
print fruit[1:]

# Here we strip one character from the right
# We need use a -1 as we are going backwards from the end
print fruit[:-1]

# And we cna actually do both
print fruit[1:-1]

# And to get just the first character
print fruit[:1]

Lists

Lists (or arrays) are a collection of other variables. You can have a list of integers, a list of strings or, in python, you can mix and match (although it can get messy so tread carefully)

# To create an empty python list
shopping_list = list()

# Add an item to the list
shopping_list.append('bananas')
shopping_list.append('oranges')
shopping_list.append('apples')
shopping_list.append('bread')

# Print the list
print shopping_list


# To create a list with some values
# Note that each value is separated by a comma!
shopping_list = ['bananas', 'oranges', 'apples', 'bread']

# Print the list
print shopping_list

We can query the list in a few ways

shopping_list = ['bananas', 'oranges', 'apples', 'bread']

# Print the first element
print shopping_list[0]

# Print the number of items in the list
print len(shopping_list)

# Print the last element by querying the length
print shopping_list[len(shopping_list)-1]

# The slicing also works on lists
# Remove the first element
print shopping_list[1:]

# Remove the last element
print shopping_list[:-1]

FOR loops

# We can use FOR loops to iterate over a list:
# Create a list to iterate over
shopping_list = ['bananas', 'oranges', 'apples', 'bread']

for item in shopping_list:
    print item
	
	
	
# We can also use a FOR loop to 'count' up to a certain value:
# Note that the second number (10) means "keep going while we're below this number"
# ... so the last value printed here will be 9
for num in range(0, 10):
    print num
	
	
# The range function can take an optional 3rd argument, which is the increment step size
# So to increase by 2 each time:
for num in range(0, 10, 2):
    print num
	
	
# As we go through a FOR loop, we can pass variables through and update them
# Here, "value" gets added to at each iteration, and the final value is printed at the end
value = 0
for num in range(0, 10, 2):
    # += is shorthand for "add value on the right to the value on the left"
    value += num
print value

IF Statements

An IF statement only executes the code block if the condition meets the criteria given

IF statements use logical operators to determine criteria

# A equals B
a == b

# A does not equal B
a != b

# A is less than B
a < b

# A is greater than B
a > b

# A is less than or equal to B
a <= b

# A is greater than or equal to B
a >= b

Lets look at this is action

# Only print the value if the number is greater than 4
for num in range(0, 10):
    if num > 4:
        print num
		
# We can use the 'and' keyword to chain multiple criteria together:
for num in range(0, 10):
    if num > 4 and num < 8:
        print num
		
# Lets add another!
for num in range(0, 10):
    if num > 4 and num < 8 and num != 6:
        print num
		
# But don't go crazy! 
# If you have more than a couple, consider using multiple IF statements to help keep things readable

Functions

A function is a small collection of code that is

# Basic syntax of a function
def function_name():
    # Do some stuff
    return None

Functions take parameters

A comment defining what the function does is called a docstring and has a particular syntax

def function_name(arg1, arg2):
    """Function to do awesome stuff
    """
    return None

When written like this, the docstring can be queried in code:

print function_name.__doc__

Methods

A method is syntactically very similar to a function (in that it can take arguments, return a value etc) but it must be called on an object

Here we make a simple method called "create" in our "Car" class (see below for Classes)

class Car():
    def create(self):
        self.car = pm.polyCube()

And we call the method by first instantiating an instance of the class

car = Car()
car.create()

Parameters vs Arguments

Most people tend to use the terms parameter and argument interchangeably. Which is almost OK because in conversation it's known what you meant, but technically that's incorrect.

A parameter is the value defined in your function or method. Here, "valueA" and "valueB" are parameters:

def my_function(valueA, valueB):
	return None

However, the arguments are the data that is passed in to the function when it's called. Here, the arguments are "r'C:\renders'" and "0.05":

def my_function(valueA, valueB):
	return None
	
my_function(r'C:\renders', 0.05)

We can think of these as almost being opposites of each other, like a throw and catch. The argument is "thrown" to the function and "caught" in the parameter"

It's unlikely you will ever get called out on it (like if you mixed up using "imply" and "infer"), but it's worth pointing out that they ARE different.

Classes

Classes form the foundation of Object Oriented Programming (OOP). They bucket together related methods and variables (also called "fields" in the context of a class).

You create an Instance of a class, and each instance can have unique properties.

As an example, think about constructing a "Car" class. This would need: Fields/Properties

  • Make
  • Model
  • Color
  • FuelLevel Methods
  • Start()
  • Stop()
  • Refuel
class Car():
    
    def __init__(self):
        self.make = 'Honda'
        self.model = 'Pilot'
        self.color = 'red'
        self.fuel_level = 100
        
    def Start(self):
        print 'Starting the car'
        
    def Stop(self):
        print 'Stopping the car'
        
    def Refuel(self):
        print 'Refuelling'

What's going here?

Firstly, let's look at the def _init_(self): line:

  • def : this is the keyword used to create a function
  • _init_ : this is a python built-in method of a class object that is "initialized" when you create the instance
  • self : each instance of a class has knowledge of "itself", and can pass data around. This "self" is the current instance of the class

Lets try creating an instance of this class and manipulating it

# Create a single instance of Car, and print two properties
car1 = Car()
print car1.make, car1.model
#// Result: Honda Pilot

# We can change the values of a class instance property after the instance has been created
car1.model = 'CR-V'

# Printing the same properties as before now yields different results
print car1.make, car1.model
#// Result: Honda CR-V

String Formatting

We can manipulate the printing of strings to make the output more readable

my_item = 'banana'

# To just print a value
print my_item

# We can print out simply using commas, like so
print 'I need a', my_item

# We can use a %s syntax to have more control (%s is used to insert a STRING variable)
# We add the %s in the string, then add a % in front of the variable
print 'I need a %s from the store' %my_item

# Printing integers
number_of_bananas = 4

# Simple print
print number_of_bananas

# For integers, we use %i to insert the variable into our string formatting
print 'I need to buy %i items' %number_of_bananas

# To add multiple variables, we put them all into brackets
# But only ONE % sign, at the front of the brackets, is needed
print 'I need to buy %i %s' %(number_of_bananas, my_item)


# Printing floats
distance = 145.89375012
print distance

# Print floats using "%f"
print 'Distance = %f' %distance

# Control the decimal places using the following syntax
print 'Distance = %.2f' %distance

Generators

def generate_fruit():
    for fruit in ['apple', 'banana', 'orange']:
        yield fruit
        print '- I LOVE FRUIT -'
    
for fruit in generate_fruit():
    print fruit
	

Importing Other Packages

The real power of Python comes into play when importing other packages. There are thousands (according to the Python Package Index, current count is 173,474 python packages available), but some example are:

Built-in packages (these ship with Python as standard):

  • os : this lets you query and manipulate file paths and data on disk
  • random : random number module
  • shutil : shell utilities, letting you manipulate the file system in a nicer way than native os can
  • xml : xml parsing and writing
  • re : regular expressions, letting you run string based pattern matching
  • subprocess : lets you run operations through the command shell

Available for install (using managers such as "pip"):

  • PIL : Python Image Library, a fullt fledged image manipulation package (other options are Imagemagick and OpenImageIO)
  • moviepy : wraps the core functionality of ffmpeg and adds some cool features, letting you read, manipulate and writing video files
  • pygame : make fun games using Python
  • pywin32 : access to the win32 API, letting you read and manpulate items such as Word docs and Excel spreadsheets
  • beautifulsoup : web-scraping package, letting you get data from web pages with minimal effort
  • numpy : a collection of high level mathematical operations
  • tensorflow : machine learning package that has fast become the standard for learning how ML works
import random
print random.uniform(0, 1)

Trawling Directories Using os.walk

The "walk" function in the os.package allows us to recursively propagate directories and get the paths of all files found

import os

# os.walk "yields" a 3 element tuple, so we can act on each result as it comes in
for (root, dirs, files) in os.walk(r'C:\renders\output'): 
    # each of the returned values is a list
    # As the "root" value changes as the directories are propagated, we can build our full path
    for file_name in files:
        file_path = os.path.join(root, file_name)
        print file_path
        
  
"""
// Result: (note that we have recursively gone through two layers of directories)
C:\renders\output\fruit\apple.jpeg
C:\renders\output\fruit\banana.jpeg
C:\renders\output\fruit\grapes.jpeg
C:\renders\output\fruit\orange.jpeg
C:\renders\output\fruit\pineapple.jpeg
C:\renders\output\vehicles\boat.jpeg
C:\renders\output\vehicles\car.jpeg
C:\renders\output\vehicles\plane.jpeg
C:\renders\output\vehicles\sapcecraft.jpeg
C:\renders\output\vehicles\train.jpeg
"""
        

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.