Why you must learn Python:
https://www.youtube.com/watch?v=Y8Tko2YC5hA
Why do we teach python version 2, or specifically 2.7?
The majority of digital content creation applications besides Blender have support for Python 2.x series. This is largely due to the fact that Python integration started when Python 3 was not yet released. If one software package would upgrade to Python 3, this can cause compatibility issues with other pipeline elements and other CG applications. After all, most of the challenges in VFX production can be handled with Python 2.x.
At the time of writing, there are no plans in the 3D industry to update to Python 3.
A brief summary of python divergence:
Python 2.6 was the standard when 3.0 was released, but because 3.0 introduced breaking code changes (the code you wrote for 2.7 would not run in 3.0 the core developers continued to release new versions of 2.x while 3.x was developed, and back ported the bugfixes and some new features. As such the latest python 2.7.15 has all the latest bugfixes of python 3.6.5, for example.
Wait-- what’s with three numbers separated by decimals? What’s a “version”?
Don’t panic, this is called “semantic versioning”. Let’s consider the version “2.7.15”.
When you see a version number like “2.7.15” this means that the “Major” (and most important) version number is the first, 2.
Often major version changes can mean fundamental changes to the underlying software, meaning “breaking changes” or, if you’ve written code for a previous version, it no longer works. This is the case for python.
The second number-- 7 in this case-- is the “Minor” version, these are updated more often for smaller changes and usually not breaking changes. Minor version updates often contain new features.
Finally the third number, “15” refers to the “Patch” version number. These are small releases, usually only containing bugfixes or very small changes, not worth examining unless you’re into that sort of thing.
There’s a much bigger writeup with more details here if you are curious. (Available in many languages!)
https://semver.org/
How to learn with these exercises:
Throughout these weeks we are going to be looking at many examples of Python code to teach certain concepts. I would strongly recommend you do NOT simply copy-paste the examples, but type each unique exercise manually. This will help make sure that you notice new features and small changes.
Generally when doing larger examples it is easier to write this into a file and then execute that file in case there are syntax errors or mistakes-- you can correct it without rerunning every single line individually.
Getting started:
This is a handy python 2.7.10 interpreter and console which can be found online. For now, this will be your starting point for all python exercises.
Create a login with your email.
https://repl.it/repls/InexperiencedPristineSampler
On top we have the file input window and below, the interactive interpreter. You can also run this on your local machine if you have python installed.
Python files have a “.py” extension and can be run with python.exe (usually found in C:\Python27)
Next, go through the Settings (Gear shaped) Icon on the lefthand side and set it up to your preference.
On the Files tab (Paper page icon) on the left, you can open a pane that shows your directory structure. I would recommend naming files in an orderly way that you can use to track your progress over the coming weeks. For now let’s make a new file and name it “week1_print.py”
In the editor pane (underneath “main.py” tab, remove any code that may already be there, and type in:
print 'Hello World'
Then press Control+Enter on your keyboard or the large “run >” button on the top of the page.
You should see something like this in the console to the right/below:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
Hello World
Congratulations, you’ve just executed your first program in python!
Let’s try another:
# This line is a comment
print 'The answer to Life and the Universe is :',
# The line below calculates the answer to Life and the Universe
print 7 * 6 # this is also a comment and will be ignored
You should see the calculated answer to life in the interpreter window. As you can see it’s easy to do all the basic math operations in Python.
How about the “#” hash sign? You can also “comment” out code by hitting Control+/ on your keyboard with any amount of text selected. This will comment out all the lines by putting a “#” at the start of the line. This tells Python to ignore the rest of the line. Similarly by using “Tab” or “Shift+Tab” keyboard shortcuts, you can indent or de-indent selected lines, but we’ll get to that later.
Helpful tip – learning shortcut keys for tasks will make you a faster and more effective computer user.
What does “print” mean? There’s no paper here!
Print comes the ancient computing days before screens and monitors were invented. In order to get an output from your computer, you had to tell it to “print” an output onto paper. This terminology has hung around since then.
Now we use “print” to mean, we wish to display something or the output of something (or to evaluate an expression) on the computer screen.
As we complete exercises, I would strongly suggest you do not copy and paste code, but rather type everything manually. Practice makes better, and your finger will use muscle memory to assist you in remembering names.
Quotes, escapes:
Let’s try another: note that we are printing “strings” which are a sequence of letters and any other single characters, like spaces, special characters.
print “Double quoted”
print ‘Single. Feels any different?”
print ‘I said “Archie!”’
print “And he said ‘What?’”
print “And I replied, \“You forgot the parrot!\””
Notice that quotes are interchangeable. But whatever quote you use, single or double, you must open and close in the same order or python’ll get confused. Alternatively in a string you can escape with “\”. To “Escape” means to tell the program that you want it to ignore the following character.
Anything in python can be stored or assigned to a custom name or object of your choosing.
Here we have three different classes of Python objects. The name you assign to them doesn’t matter, but the type of object does.
my_fruit = ‘feijoas’
number_fruit = 5
pi = 3.1416
is_vegetable = False
song = None
They are in represented, as:
- String (a quote enclosed sequence of letters)
- Integer (a round number, positive or negative)
- Float (a more precise, decimal number that can have any feasible number of decimal places, within limit)
- Bool (Either True or False, a way of thinking about on/off, or yes/no)
- None (A generic empty, blank value built into Python)
String Formatting basics:
There are a couple of ways to string format in Python, both which look different but perform the same. You can give them almost any kind of variable and it will be converted into a string at print time.
This first example of formatting is preferred because it’s future compatible with Python 3. “{}” marks where you want the variable to be inserted into the string.
> print ‘my favourite fruits are {}’.format(my_fruit)
my favourite fruits are feijoas
> print ‘Eight plus six is {} which is great’.format(8+6)
Eight plus six is 14 which is great
But if you see something like this, it’s the same thing. “%s” tells Python to make convert into a string here.
> print ‘my favourite fruits are %s’ % my_fruit
my favourite fruits are feijoas
> print ‘Eight plus six is %s which is great’ % (8 + 6)
You can format as many variables as you like:
> weather = 20.4
> time = “12:11pm”
> name = “Jordan”
> print “Hi {}, the time is {} and the temperature is {}”.format(name, time, weather)
Hi Jordan, the time is 12:11pm and the temperature is 20.4
The keys to Self-Guided Exploration:
There are three special python built-in commands that you will find super useful as you begin in python.
What do these do?
type() will take any object and give you the type of that object.
dir() will take any object and give you a list of functions on that object.
help() will take any object and print the “docstring” or documentation which is part of that object. This will help you understand how to make and modify objects in Python.
But wait, how do I run these?
In python you call functions by giving them parentheses like so.
dir()
But you need to give it an “argument” or pass something to it in the call.
dir(object)
An argument is anything which you wish to provide to any function, such as dir() or help().
So for our next exercise, try making each of the three object types I just gave you, and running type(), dir(), and then help() on each of them.
your_fruit = ‘banana’
print type(your_fruit)
print dir(your_fruit)
You should see a whole bunch of strings, but for now, ignore anything that has “_” in it. Towards the bottom you’ll see some names like “title” or “rsplit” or “upper”.
Try some of them like this:
your_fruit = ‘banana’
print dir(your_fruit)
print your_fruit.upper()
print your_fruit.title()
What’s happening here? You’re taking a string object, your_fruit, you are listing the functions it has with dir(), and then calling them one at a time.
So functions can be standalone, and objects can have functions. As you see, Python is flexible and open ended.
For your next exercise, I challenge you to find three things :
- A way to “capitalize” the first letter of a string
- A way to check if a float number is an integer
- A way to check if a string starts with the letter “A”
Raw input:
What if you want to take custom input from the user while the program is running? There is one infrequently used, but indispensable function called raw_input. When the program reaches this function, it will stop and prompt the user, then wait for the user to press enter. Let’s see how it works.
fave = raw_input(‘What is your favourite number?’)
print fave
When you run this program, you should see the interpreter hang or freeze. Click in the window, type in your favorite number, then press the enter key.
You should see your favorite number printed back to you. Python has assigned the input to “fave”. This could be handy!
Let’s move on to the basic math symbols, as found in Python.
+ plus
- minus
/ slash
* asterisk
% percent
< less- than
> greater- than
<= less-than-or-equal
>= greater-than-or-equal
== is-equal-to
I left out the definition of what they do intentionally, let’s try them and experiment.
print ‘Counting IQ’
print ‘Example IQ is’, 80+40
classmates = raw_input(‘How many classmates do you have?’)
print ‘Is this a large class?’, classmates > 15
print ‘The total class IQ’, classmates * 120
print ‘If there were 2 teachers, there would be this many students per teacher’, classmates / 2.0
Be creative and try writing some new lines, using the other mathematical symbols to figure out what they do.
Note : Has any of the math seemed wrong to you? Remember that doing mathematical operations on integers will result in integers, but if you want more accuracy you will need to use float numbers by adding a decimal point or converting a number into a float (more on that later).
For example:
print 3 / 2
May give you an unexpected result!
However, this will give you what you expect.
print 3.0 / 2.0
If any of the numbers are float and not integer, then you’ll get a more accurate result.
Here’s a handy video explaining number types in further detail.
https://www.youtube.com/watch?v=khKv-8q7YmY
Lists:
At this point, you should be comfortable with the basic Python types we have learned so far. Let’s move onto the next type which is a little bit more complicated, it is an object that can contain objects. Python calls this a list. The secret to recognizing a list is the square brackets which are used to open and close a list of objects.
my_list = [1, 2, 3, 4]
Of course, a list can contain any objects. It will remember the order.
shopping_list = [‘feijoas’, ‘passionfruit’, ‘lychees’]
random_list = [3.14, 6, 7, 8, shopping_list, dir, ‘I can keep anything in here!’]
Try printing dir() and help() on one of your list objects to discover more about them.
Here's Socratica demonstrating list objects in Python.
https://www.youtube.com/watch?v=ohCDWZgNIU0
Finally, Dictionaries:
Dictionary objects in Python provide a way of storing data associated with keys. They provide an essential way to organize your data, or make connections from one object to another. Understanding dictionaries well will help you to be a better developer. Although dictionary objects can be created in a few different ways, probably the most common form you will see will involve the squiggly brackets (braces), or { } symbols, as below.
websters = {}
You can instance them with key and value objects separated by a colon with any number of objects; like so.
websters = {‘fruit’: ‘Feijoa’, ‘colour’ : ‘green’, ‘is ripe’ : False}
This is a handy video overview of python dictionaries. Don’t worry if the “for” keyword and loop don’t make sense as we’ll get to it next week.
https://www.youtube.com/watch?v=daefaLgNkw0
Exercises: (Best to save these as separate .py files in your directory)
- Make a program which asks the user for a measurement, and converts to a different measurement
- Make a program that asks the user for a number between 1-10 and prints the name of that number
- Discuss some interesting differences between MEL and Python in the forum 8+6 is 14 which is great 8+6 is 14 which is great 8+6 is 14 which is great 8+6
Importing modules and functions from outside your program:
Python comes with a large standard library of modules, available to import and use. Familiarity with some basic libraries are essential, for example, file system interaction, mathematics, and random functions can all be easily accessed.
The os module:
>>> import os
>>> os.getcwd()
'C:\\Python27'
>>> os.listdir('D:\\DEV\\OnionLogger\\python')
['OnionLogger.py', 'viewer.py', '__init__.py', '__pycache__']
>>> os.listdir(os.getcwd())
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']
>>> os.path.splitext(r'D:\2_CREATIVE\PeskyWabbitProject\JordanBunnies\bunnies1.jpg')
('D:\\2_CREATIVE\\PeskyWabbitProject\\JordanBunnies\\bunnies1', '.jpg')
What’s with the double backslash you may ask? Or the “r” before the string in that last command?
This is a Microsoft Windows only paradigm : The double backslash (\) is unique to the Windows file system as Windows uses the backslash to separate folder names in the directory structure. (Linux and Mac don't do this) however in Python, and as in other languages, the backslash is used to modify the following character, or act as an "escape" as we've already discussed. So in order to use a backslash as-is, you have two options: either put a single lowercase letter "r" before your string – or double up the backslashes, essentially using our backslash to escape itself. Don't be confused, just try it. :-)
So you’ve seen me use os.listdir and os.path.splitext. The os module has many useful functions for getting the size of a file, checking if it exists, and so on. Most of the functions are found both on os and os.path.
You can also import a module or function directly:
>>> from time import ctime
>>> ctime()
'Sun Jan 13 22:18:56 2019'
There is also a cool random function which will come in handy.
>>> import random
>>> random.random()
0.6270435045747289
>>> random.random()
0.0453048333647188
>>> random.random()
0.2502684292405273
As you can see, Python modules have their own structure (and spaces) shown by periods in the path. In the previous example “random” is a function on the module “random”.
If you’re interested in more python modules, this is a good resource to bookmark:
https://pymotw.com/2/
Bonus:
Typing speed effects almost all that you do on the computer. Being able to touch type or type fast will enable you to communicate with colleagues quicker, and even write code faster. How many WPM can you do?
Learn touch typing: https://www.typingclub.com/
Measure your Words-Per-Minute and track your progress: https://10fastfingers.com/