Introduction to Python
I already know C/C++ and Java. Why do I need to learn another programming language?
Different languages are best for different things. Python is one of the fastest languages for rapid prototype work. You can develop a complex program in Python faster than in any other language.
Are there any shortcuts for learning a second language?
Excellent question. There definitely are.
Learning your first language is the hardest. There are lots of new concepts to understand. For most people, it is the first time they have to work so strictly with logic and grammar.
The good news is that once you learn the basics of programming, switching to another language is fairly easy. Here is a mnemonic to make it even easier. Finding these 7 things will get you up and running in any new language fairly quickly:
- Comparitor
- Loop
- Output
- Variable
- Editor
- Run
- Sample
| Know the syntax for comparing any two variables or constants. e.g.: if(X>Y), if(X>0 or not Y=0), if(X==Y) | |
| Know one or more methods of looping over code. e.g.: for i in range(10):, while(True):. | |
| Know how to create output. e.g. print("Hello"), print("%s %d\n" % ("Hello", 1)) | |
| Know how to create a variable. e.g. x=0, y=1.0, s ="imastring" | |
| Find at least one editor you can use in your environment and get comfortable with it. Some editors will make your life easy by recognizing your language and highlighting keywords. Some editors are more complicated to learn than others. | |
| Know how to run a program from either the command-line or GUI. | |
| Most importantly - get a working sample of the new language. A small piece of working code will fill in the blanks on syntax, common includes, etc. Just Google for 'Python sample code'. |
Starting Python
Command-line:
C:\Python32\python.exe
>>>
GUI:
Start->All Programs->Python3->IDLE (Python GUI)
Running Python
Interactive mode:
>>>print (‘Hello’)
Running python files:
- Start IDLE (It opens in Interactive Mode.)
- File->New Window (Creates a new editor window.)
- In the editor, type:
print (‘Hello’) - File->Save As
- Desktop/hello.py
- Run->Run Module (or F5) to run.
What is Python
- Interpreted language, as opposed to a compiled language like C++
- Simple to use
- Designed for programmer’s convenience, not the processor’s
- Easy string and list manipulation. e.g.:
>>> x = ‘this is a test’ >>> dir(x) >>> x.split() - Easy scoping rules
- No memory management
- Simplified variable typing
- Extensible – you can create you own C++ libraries to import
- Portable between Windows and Linux
First Program
Create the following program in your IDLE editor:
print (‘Hello’) for i in range(10): print (i)
Press F5 to run
Whitespace Matters
Leading whitespace in Python == {} in C++/Java
Run each of these programs and compare the output:
Program A:
print (‘Hello’) for i in range(10): print (i) print (i * 1000)
Program B:
print (‘Hello’) for i in range(10): print (i) print (i * 1000)
Now change the indentation randomly to see where it breaks
Comparators
Run the following program:
x = 1
if(x < 10):
print (‘success’)
else:
print (‘failure’)
Try changing the second line to the following:
if(x):
if(x == 1):
if(x != 2):
if(x <= 1):
if(not x==2):
if(x == 1 or x == 2):
Looping
These are the three types of loops you will usually use:
Option 1
x = [0,1,1,2,3,5,8,13,21]
for i in x:
print(i)
for i in range(10):
print (i)
Option 2
x = 1
while(x < 10):
print (x)
x = x + 1
Option 3
x = 1
while(1):
print (x)
x = x + 1
if (x>=10):
break
Output
To the screen:
>>>print ("Hello, World")
>>>print (1,2,3)
>>>x = 1
>>>print (x)
>>>print ("Print test: %d %f %s" % (1, 2.0, "s"))
To a file:
>>>f = open("test.txt", "w")
>>>f.write("This is a test\n")
>>>f.close()
Variables
Types include:
- int
- float
- bool
- string
- objects
Type is implied, not specified:
>>>x = 1
>>>type(x) #<-- returns "type 'int'"
>>>y = 1.0
>>>type(y) #<-- returns "type 'float'"
>>>z = "1.0"
>>>type(z) #<-- returns "type 'str'"
Types may be cast
>>>x = 1
>>>y = float(x)
>>>type(y) #<-- returns "type 'float'"
Operations may include variables of different types:
- float + int = float
- float + string = <error>
Editor
You may use any text editor you want for Python. I recommend you use one with 'syntax-highlighting'. This is the feature that changes the color of keywords and variables. Some editors even detect syntax errors in real-time.
IDLE and Notepad++ are installed on windows. Both are good editors. IDLE lets you run programs from the editor, which is convenient. Notepad++ is a more complete editor.
gedit, nano, and vi are installed on Linux. gedit is the easiest to learn if you do not already know the others.
Since whitespace matters in Python, we need to be careful about how it is inserted. I recommend that you adjust your editors to insert four spaces every time you hit the tab rather than inserting a '\t' tab character. The problem is that if you mix tabs and spaces, your program can become impossible to debug. (They look the same to the human eye, but different to the Python interpreter. You will be literally chasing invisible bugs if you mix spaces and tabs.)
- Notepad++: Settings->Preferences...->Language Menu/Tab Settings. Set Tab Size==4. Set "Replace by space" to True.
- gedit: Edit->Preferences->Editor. Set Tab width==4. Set "Insert spaces instead of tabs" to True.
- IDLE: IDLE defaults to 4 spaces, and always replaces tabs with spaces.
Running programs
Python can be run from either a file or from an interpreter. The 'interpreter' is an interactive prompt that lets you enter one line of code at a time. Python's interpreter has a >>> prompt. You can start the python interpreter in Linux or windows by typing python in a command shell.
The interpreter is useful for learning the language and testing small pieces of code. Usually, we will be running code from a file.
Blender has a built-in Python interpreter. You can launch it in any Blender window by hitting "Shift-F4".
Once we get comfortable with Python, we will be using it to manipulate objects in Blender. This is why we care about its built-in interpreter.
Windows command-line. Python files should end in .py, but this is not required. From a command shell, type 'python <filename.py>'. e.g. python hello.py. You may pass additional command-line variables to the program by adding them after the filename, e.g. python hello.py 1 2 3
Linux command-line. You can run exactly the same as with windows: python hello.py 1 2 3 Alternatively, you can make your program executable add this as your first line in the file: #/usr/bin/python This will let you run the program without typing 'python first, e.g. hello.py 1 2 3
Blender command-line. We are used to using Blender in an interactive GUI. With Python, we can create a script that runs Blender for us. The script starts Blender, creates objects, renders images, etc. e.g. blender -b myscene.blend -P hello.py
Sample code
... is all over the place. It is on this page, and there is a lot in today's lab. Also Google for "python sample code"
Python Functions
Run this function to try it out.
def countdown(x):
for i in range (x, 0, -1):
print (i)
countdown(20)
Importing libraries
We can import libraries that other people have written.
Libraries contain functions, classes, variables and libraries.
Start an interactive console and run the following:
>>> import os
>>> dir (os)
>>> os.listdir #<--(says listdir is a function)
>>> os.listdir() #<--(error)
>>> help(os.listdir)
>>> os.__file__
>>> os.__file__() #<--(error)
>>> type(os.__file__)
Style notes. There are two ways you will see to use the import command:
| Method A | Method B |
>>> dir() >>> import sys >>> dir() >>> sys.version |
>>> dir() >>> from sys import * >>> dir() >>> version |
Method A is preferred. It prevents name conflicts. What if two different modules had a variable named version? Method B would return undefinced results.
Finding help
List of all modules available for import:
>>> help(‘modules’)
List of all functions/variables in a library:
>>> import socket >>> dir(socket)
Description of entire library:
>>> help(socket)
Description of a specific function or variable in library:
>>> help(socket.gethostname)
Online reference for Python 3.2:
    http://docs.python.org/py3k/py-modindex.html
The installed documentation has a good intro to python:
Start->All Programs->Python3.2->Python Manuals
->The Python Tutorial
-> An Informal Introduction
Here is the same information online:
    http://docs.python.org/py3k/tutorial/
    Start in Chapter 3: An Informal Introduction to Python
- Run a hello world function: print ("Hello, world") from each of the following Python interpreters:
- Python IDLE interpreter
- Windows command-line interpreter
- Blender Python interpreter
- Create a file named hello.py and run it from the command-line
- Use the range() function to print the odd numbers from 1 to 20.
- The 'string' library lets you perform string manipulation. You need to import string before you use it. Use the string.split() function to split a sentence into individual words.
- The 'math' library includes many common math functions. Use this library to print out the sine and cosine of the degrees from 0 to 90. (NOTE - be sure you use degrees and not radians.)
Python in Blender
Important tips for using Python in Blender:
- You can change to a layout that makes Python easier to work with. On the Info menu bar on the top of the Blender screen, find the droplist that says "Default". This controls the screen layout. Click the icon to the left of the word "Default" and select the "Scripting" layout. This open both a "Text Editor" pane and a "Python Console" pane.
- Click the word "New" in the Text Editor to create your first text script. The default name of the first script is "Text".
- You can save Python scripts directly in your *.blend file. Type code in the Text Editor. It will be saved automatically.
- You can create multiple scripts. Find the droplist control that says "Text" at the bottom of the Text Editor pane. Click the '+' sign to the right of "Text" to create another file. Use the droplist to switch between them.
- You can run scripts by clicking the "Run Script" button in the Text Editor.
- Error messages go to a Windows system console. In the Info bar, click 'Window->Toggle System Console' to see it.
- You can use the Python Console window at the bottom of the screen to test short commands.
- Extremely Important: You can use that 'a' key to select all objects in the scene, then 'Delete' to delete them. You will use this incessantly while you are testing a script.
- You need to import bpy in order to access Blender objects from Python.
These 3 scripts will show you all the Blender-specific commands you need for the Lab:
Create custom Mesh objects:
import bpy
# HOW TO CREATE A POLYGON MESH IN BLENDER
#
# (1) Define the all the vertices in the poly mesh.
# Each vertex is defined by 3 consecutive floats (3-tuples in a list).
coords=[(-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, 1.0 ,-1.0),
(-1.0, 1.0,-1.0), (0.0, 0.0, 1.0)]
# (2) Each face is defined by the indices of its vertices (4-tuples in a list).
# The faes are assumed to be 'quads' (4-sided polygons).
# For triangles, include one vertex in both the first and last position.
faces=[ (2,1,0,3), (0,1,4,0), (1,2,4,1), (2,3,4,2), (3,0,4,3)]
# (3) Create a new type of Mesh object named "PyramidMesh".
pmesh = bpy.data.meshes.new("PyramidMesh")
pmesh.from_pydata(coords,[],faces) # either edges or faces must be empty list []
pmesh.update(calc_edges=True)
# (4) Create an instance of the PyramidMesh named "Pyramid".
ob = bpy.data.objects.new("Pyramid", pmesh)
ob.location = (0,0,2)
ob.scale = (3,3,2)
ob.rotation_euler=(0, 0, 1.2)
# (5) Link the object to the scene
bpy.context.scene.objects.link(ob)
# (6) Create several more PyramidMesh objects just to show that we can
for i in range (5):
ob = bpy.data.objects.new("Pyramid", pmesh)
ob.location = (i*2,10,2)
ob.scale = (1,1,i)
bpy.context.scene.objects.link(ob)
Create Blender primitive objects:
import bpy # Check this webpage for options for the primitives: # http://www.blender.org/documentation/blender_python_api_2_68_release/bpy.ops.mesh.html bpy.ops.mesh.primitive_cube_add(location=(0,0,0)) bpy.ops.mesh.primitive_plane_add(location=(3,0,0)) bpy.ops.mesh.primitive_grid_add(location=(6,0,0), x_subdivisions=40) bpy.ops.mesh.primitive_monkey_add(location=(9,0,0)) bpy.ops.mesh.primitive_torus_add(location=(0,4,0), major_radius=2.0, minor_radius=1.0) bpy.ops.mesh.primitive_uv_sphere_add(location=(4,4,0), segments=20, ring_count=10) # Adding 3D text is a 3-step process: bpy.ops.object.text_add(location=(6,4,0), rotation=(3.14/2,0,0)) textObj = bpy.context.object textObj.data.body="USNA"
Place objects with the Math library:
import bpy
import math
NUM = 100
RADIUS = 50
incr = 2*math.pi / NUM
for i in range(1,NUM):
angle = incr * i
x = RADIUS * (math.cos(angle))
y = RADIUS * (math.sin(angle))
z = 0
bpy.ops.mesh.primitive_cube_add(location=(x,y,z))
bpy.ops.mesh.primitive_cube_add(location=(y,z,x))
bpy.ops.mesh.primitive_cube_add(location=(z,y,x))