Python Basics
2011 ANSYS, Inc.
November 29, 2012
Outline
What is Python
Python Programming
Python console External to WB
Python Command Window in WB
2011 ANSYS, Inc.
November 29, 2012
What is Python?
Python is a object-oriented, interpreted, and interactive programming language
Python code is interpreted and portable between platforms
Python combines remarkable power with very clear syntax
It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing There are interfaces to many system calls and libraries Python is also used as an extension language for applications written in other languages that need easy-to-use scripting or automation interfaces
IronPython is the Python Workbench uses
IronPython is an implementation of the popular programming language Python for .NET, by Microsoft It brings new possibilities to .NET as well as Python programmers It uses Python 2.6 on .NET 2.0
3 2011 ANSYS, Inc. November 29, 2012
Recommended References
Free materials http://www.python.org/ Python download all formats Tutorial and documentation http://ironpython.codeplex.com/
IronPython studio is free Microsoft SDK that allows you to manage your projects and develop using native windows forms
http://www.tutorialspoint.com/python/index.htm Free book - http://greenteapress.com/thinkpython/thinkCSpy.pdf
Recommended books Learning Python by Mark Lutz and David Ascher Python Pocket Reference by Mark Lutz IronPython in Action by Michael J.Ford and Christian Muirhead
For people wanting to use Iron python to take advantage of the .NET framework
ANSYS 14.5 Help Workbench Scripting Guide
4 2011 ANSYS, Inc. November 29, 2012
Python Editors
Notepad++ Supports several languages (Python, Jscript, XML, ) IDLE Standard Python editor that comes with Python. Good for most small programs.
SPE Advanced non-commercial development environment
Erik Powerful development environment that helps managing big projects with many files, as well as testing and debugging them SharpDevelop Development Environment for .NET (e.g IronPython based custom GUI)
2011 ANSYS, Inc.
November 29, 2012
Python console External to WB
You can install Python on your machine or use the IronPython version installed with ANSYS
Invoke the ipy.exe in command prompt to have a Python console Path: C:\Program Files\ANSYS Inc\v145\commonfiles\IronPython\ipy.exe
!
6
You can also just drag and drop the ipy.exe file to a standard command prompt
November 29, 2012
2011 ANSYS, Inc.
Python Command Line (CLI)
Overview: You can use any Python command from the interactive Python command line: Everything works in exactly the same way as it would in a program. You can define code blocks by writing extra lines:
Tips:
You can leave the command line by Ctrl-Z
(Windows) or Ctrl-D (Linux). The CLI works great as a pocket calculator. Writing code blocks with 2+ lines in the CLI gets painful quickly. From IDLE, you can execute a program in the command line by pressing F5.
2011 ANSYS, Inc. November 29, 2012
Writing Python Programs
Essentials:
All program files should have the extension .py Indentation is a central element of Python syntax, marking code blocks. Code blocks should be indented by spaces/tab. Indentation must not be used for decorative purposes Only one command per line is allowed
Python does not have:
Memory allocation Declaration of variables and types
2011 ANSYS, Inc.
November 29, 2012
Python Programming
2011 ANSYS, Inc.
November 29, 2012
Variables
A variable:
Dont need to be pre declared
As Python scripts are run via an interpreter it will work out for itself the type of information and memory required The name must start with an alphabetic character Can be any length
Variable Types:
Numbers String List Tuple Dictionary
Python doesnt enforce variable types
A variable can change type
Using a good editor helps a lot!
10 2011 ANSYS, Inc. November 29, 2012
Syntax
Colon
Required at the end of compound statement headers (the first
line of an if, while, for, etc.)
Semicolon
Don't terminate all of your statements with a semicolon(;) It is not required unless you're placing more than one
statement on a single line
Whitespace
Important only for the indentation level (i.e. the whitespace at
the very left of your statements). Everywhere else, whitespace is not significant
Comments
Syntax # 1: # Comment
11
Text after # is ignored in a single line Syntax # 2: Comment Text between pairs is ignored Python is case-sensitive Variable names may mix upper- and lower-case Calling code must match the case exactly Python keywords are case-sensitive too
2011 ANSYS, Inc. November 29, 2012
Case-sensitivity
Operators
Arithmetic operators
Add, subtract, multiply, division , modulus, exponent, Floor division
Assignment operators
Simple assignment Multiple assignments to same value Compound assignment
Logical operators
and, or, not
Relational operators
Comparisons return Boolean values Equal to, not equal to Less than, greater than Less than or equal to, greater than or equal to
Membership operators
To test for membership in a sequence, such as strings, lists, or tuples in, not in
Identity Operators
To compare the memory locations of two objects is, is not
12 2011 ANSYS, Inc. November 29, 2012
Flow Control
If-Else conditional
Variations
if, if...else, elif, nested if Conditions Boolean or non-zero String Comparison Complex comparison Indentation: The level of indentation determines the end of a condition Colon: Required at the end of compound statement headers
2011 ANSYS, Inc. November 29, 2012
13
Flow Control (2)
while loop
The while loop continues until the expression
becomes false. The expression has to be a logical expression and must return either a true or a false value
for loop
iterate over the items of any sequence, such as
a list or a string The first item in the sequence is assigned to the iterating variable An alternative way of iterating through each item is by index
14
2011 ANSYS, Inc.
November 29, 2012
Flow Control (3)
break statement
terminates the current loop and resumes
execution at the next statement
continue statement
returns the control to the beginning of the
loop
else statement
executed when the loop has exhausted
iterating the list (for loop) is executed when the condition becomes false (while loop)
pass statement
used when a statement is required
syntactically but you do not want any command or code to execute
15 2011 ANSYS, Inc. November 29, 2012
Functions
Function declaration
begin with the keyword def followed by the function name and parentheses
Input parameters or arguments should be placed within these parentheses
Can have default arguments
The first statement of a function can be an optional statement
the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function,
A return statement with no arguments is the same as
return None.
16 2011 ANSYS, Inc. November 29, 2012
Numbers
Python supports four different numerical types:
int, float, long, complex int(x) float(x)
Change number explicitly from one type to another
Built-in Number Functions
Mathematical Functions
abs(x), min(x1, x2, ..), Trigonometric Functions Import math module to avail these sin(x), acos(x), Random Functions
Mathematical Constants
Import math module to avail these pi, e
17 2011 ANSYS, Inc. November 29, 2012
Strings
Strings are stored as a list of single characters strings Built-in String Methods
len(string) join() split()
String Special Operators
Concatenation (+) Range Slice [ : ] Suppress actual meaning of Escape
characters (r/R) Membership (in, not in)
String and number concatenation
Convert the number to string for
concatenation
18 2011 ANSYS, Inc. November 29, 2012
String Formatting
Variables and strings can be combined, using formatting characters. This works also within a print statement. In both cases, the number of values and formatting characters must be equal.
s = 'Result: %i'%(number) print 'Hello %s!'%('Roger') print (%6.3f/%6.3f)%(a,b)
The formatting characters include:
%i an integer. %4i an integer formatted to length 4. %6.2f a float number with length 6 and 2 after the comma. %10s a right-oriented string with length 10.
Escape characters
Strings may contain also the symbols: \t (tabulator), \n (newline), \r (carriage return),
and \\ (backslash) To read and use a staring containing special characters, use r before string E.g. filePath = rE:\temp # w/o the r, it will be treated as E: *tab] emp
19 2011 ANSYS, Inc. November 29, 2012
Lists
The list is a most versatile datatype available in Python
written as a list of comma-separated values
(items) between square brackets.
Accessing Values in Lists
use the square brackets for slicing along with the
index or indices to obtain value available at that index
List modification
Append elements Delete elements
Basic List Operations
strings
Lists respond to the + and * operators much like
Built-in List Functions & Methods
len(), max(), min(), sort(), reverse(), append(), remove(),
20 2011 ANSYS, Inc. November 29, 2012
Dictionaries
The Dictionary is a container type that can store any number of Python objects, including
other container types Dictionaries consist of pairs (called items) of keys and their corresponding values Also known as associative array or hash table Each key is separated from its value by a colon (:) Items are separated by commas whole thing is enclosed in curly braces
Syntax:
Accessing values
Use square brackets along with the key to obtain its value Trying to access a data item with a key which is not part of the dictionary, gives error
Adding new entries Deleting entries Properties of Dictionary Keys
No duplicate keys allowed Can use strings, numbers, or tuples as dictionary keys Built-in Dictionary Functions & Methods len(), str(), cmp(), dict.copy(), dict.items(), dict.values()
2011 ANSYS, Inc. November 29, 2012
21
Classes and Objects
An object:
Is a complex variable that has:
Data (often called properties) Functions (often called methods) Is an instance of a class A class defines a category of objects Syntax Python uses a dot notation object . property The dot connects the object to its properties and methods No whitespace! Property and method names are case-sensitive! Properties:
class: Person property: name property: age
name = Mary age = 30 name = John age = 55 name = Susan age = 22
# Properties person.name = Mary newPerson = person.child newPerson.name = John
A property is any valid variable type
Methods:
# Methods person.Talk() person.Relocate( New York )
Methods follow the same rules as functions
22 2011 ANSYS, Inc. November 29, 2012
Defining a Class
The class statement creates a new class definition
The name of the class immediately follows the
keyword class followed by a colon
The first method __init__() called class constructor or initialization method Creating an instance objects:
call the class name and pass in whatever
arguments its __init__ method accepts self points to the new object Use self to define properties for your class
23
2011 ANSYS, Inc.
November 29, 2012
Modules
A module is a file containing Python definitions and statements
A module can define functions, classes, and variables You can benefit from different modules by importing them to your code!
import Statement:
Imports a module It is customary but not required to place all import statements at the
beginning of the code
from...import Statement
imports specific attributes from a module into the code
fromimport * Statement
import all names from a module into the current namespace
24
2011 ANSYS, Inc.
November 29, 2012
Useful Python modules
Getting the current time and date:
The time module offers functions for getting the current
time and date.
Finding out what is in a module
The contents of any module can be examined with:
dir( name_of_module ) help( name_of_module )
25
2011 ANSYS, Inc.
November 29, 2012
Exceptions
Exceptions are the Python mechanism to make sure that code do not blow up in the wrong moment, so that important data is saved Except, else and finally:
Whenever the according kind of error occurs within a
try clause, the except code block will be executed. If no exception occurs, the else clause will be executed instead. After any of the two, the code block after finally is executed. else and finally are required for building subtle cleanup operations after an error. In most situations, they are not necessary. ZeroDivisionError When dividing by zero. KeyError A key in a dictionary does not exist. ValueError A type conversion failed. IOError A file could not be opened.
2011 ANSYS, Inc. November 29, 2012
Typical Exceptions:
26
File Operations
Opening files for reading
Text files can be accessed using the open() function. It returns an open file from which its
contents can be extracted as a string. f = open('my_file.txt') text = f.read()
Opening files for writing
f = open('my_file.txt','w') f.write(text)
Writing text to files is very similar. The only difference is the 'w' parameter.
Appending to files
It is possible to add text to an existing file, too.
f = open('my_file.txt','a) f.write(text)
Closing files
f.close()
27 2011 ANSYS, Inc. November 29, 2012
File Operations (2)
Writing directory names in Python
Replace the backslash '\' by a double backslash (because '\' is also used for '\n' and '\t')
f = open('..\\my_file.txt') f = open('C:\\python\\my_file.txt')
Managing file paths, directories etc.
With the os module, we can change to a different directory:
import os os.chdir(''..\\python'') os.path.join(C:\Temp, abc.txt) # path = C:\Temp\abc.txt To get a list with all files: os.listdir(''..\\python'') Function to check whether a file exists: os.path.exists('my_file.txt')
28
2011 ANSYS, Inc.
November 29, 2012
Python Command Window in WB
29
2011 ANSYS, Inc.
November 29, 2012
Command Window
Command Window supports:
Command completion Command history Keyboard shortcuts for cursor navigation and editing
30
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts
31
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts (2)
System: A collection of components that together provide a workflow to achieve an engineering simulation goal. Systems are created from System Templates.
32
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts (3)
Component: A collection of data and a data editor that work together to achieve a CAE-related task. A Component is represented by a Cell in the Workbench Project Schematic.
33
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts (4)
Component Data Container: Data unique to an individual component, and the services to manage and manipulate it.
34
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts (5)
Data Entity: A data structure defined within a data container. A data container often has several data entities.
35
2011 ANSYS, Inc.
November 29, 2012
Project & Data Model Concepts (6)
36
2011 ANSYS, Inc.
November 29, 2012
Try out
Record a journal from WB and using any text editor, extract the user inputs to the top Replay the journal file
37
2011 ANSYS, Inc.
November 29, 2012