Introduction to Python Basics

37
© 2011 ANSYS, Inc. November 29, 2012 1 Python Basics

description

python language basics

Transcript of Introduction to Python Basics

  • 2011 ANSYS, Inc. November 29, 20121

    Python Basics

  • 2011 ANSYS, Inc. November 29, 20122

    What is Python

    Python Programming

    Python console External to WB

    Python Command Window in WB

    Outline

  • 2011 ANSYS, Inc. November 29, 20123

    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

    What is Python?

  • 2011 ANSYS, Inc. November 29, 20124

    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

    Recommended References

  • 2011 ANSYS, Inc. November 29, 20125

    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)

    Python Editors

  • 2011 ANSYS, Inc. November 29, 20126

    You can install Python on your machine or use the IronPythonversion 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

    Python console External to WB

    You can also just drag and drop the ipy.exe file to a standard command prompt!

  • 2011 ANSYS, Inc. November 29, 20127

    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.

    Python Command Line (CLI)

  • 2011 ANSYS, Inc. November 29, 20128

    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

    Writing Python Programs

  • 2011 ANSYS, Inc. November 29, 20129

    Python Programming

  • 2011 ANSYS, Inc. November 29, 201210

    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

    Variables

    Using a good editor helps a lot!

  • 2011 ANSYS, Inc. November 29, 201211

    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

    Text after # is ignored in a single line Syntax # 2: Comment

    Text between pairs is ignored

    Case-sensitivity 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

    Syntax

  • 2011 ANSYS, Inc. November 29, 201212

    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

    Operators

  • 2011 ANSYS, Inc. November 29, 201213

    If-Else conditional

    Variations if,

    if...else,

    elif,

    nested if

    Conditions Boolean or non-zero

    String Comparison

    Complex comparison

    Flow Control

    !

    Indentation:The level of indentation determines the end of a conditionColon:Required at the end of compound statement headers

  • 2011 ANSYS, Inc. November 29, 201214

    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

    Flow Control (2)

  • 2011 ANSYS, Inc. November 29, 201215

    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

    Flow Control (3)

  • 2011 ANSYS, Inc. November 29, 201216

    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.

    Functions

  • 2011 ANSYS, Inc. November 29, 201217

    Python supports four different numerical types: int, float, long, complex

    Change number explicitly from one type to another int(x) float(x)

    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

    Numbers

  • 2011 ANSYS, Inc. November 29, 201218

    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

    Strings

  • 2011 ANSYS, Inc. November 29, 201219

    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

    String Formatting

  • 2011 ANSYS, Inc. November 29, 201220

    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 Lists respond to the + and * operators much like

    strings

    Built-in List Functions & Methods len(), max(), min(), sort(), reverse(), append(), remove(),

    Lists

  • 2011 ANSYS, Inc. November 29, 201221

    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

    Syntax: Each key is separated from its value by a colon (:) Items are separated by commas whole thing is enclosed in curly braces

    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()

    Dictionaries

  • 2011 ANSYS, Inc. November 29, 201222

    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:

    A property is any valid variable type Methods:

    Methods follow the same rules as functions

    Classes and Objects

    class: Person

    property: name

    property: age

    name = Mary

    age = 30

    name = John

    age = 55

    name = Susan

    age = 22

    # Propertiesperson.name = MarynewPerson = person.childnewPerson.name = John

    # Methodsperson.Talk()person.Relocate( New York )

  • 2011 ANSYS, Inc. November 29, 201223

    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

    Defining a Class

  • 2011 ANSYS, Inc. November 29, 201224

    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

    Modules

  • 2011 ANSYS, Inc. November 29, 201225

    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 )

    Useful Python modules

  • 2011 ANSYS, Inc. November 29, 201226

    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.

    Typical Exceptions: 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.

    Exceptions

  • 2011 ANSYS, Inc. November 29, 201227

    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 Writing text to files is very similar. The only difference is the 'w' parameter.f = open('my_file.txt','w')

    f.write(text)

    Appending to files It is possible to add text to an existing file, too.f = open('my_file.txt','a)

    f.write(text)

    Closing filesf.close()

    File Operations

  • 2011 ANSYS, Inc. November 29, 201228

    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')

    File Operations (2)

  • 2011 ANSYS, Inc. November 29, 201229

    Python Command Window in WB

    1

    2

    3

  • 2011 ANSYS, Inc. November 29, 201230

    Command Window supports:

    Command completion Command history Keyboard shortcuts for cursor navigation and editing

    Command Window

  • 2011 ANSYS, Inc. November 29, 201231

    Project & Data Model Concepts

  • 2011 ANSYS, Inc. November 29, 201232

    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.

  • 2011 ANSYS, Inc. November 29, 201233

    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.

  • 2011 ANSYS, Inc. November 29, 201234

    Project & Data Model Concepts (4)

    Component Data Container: Data unique to an individual component, and the services to manage and manipulate it.

  • 2011 ANSYS, Inc. November 29, 201235

    Project & Data Model Concepts (5)

    Data Entity:A data structure defined within a data container. A data container often has several data entities.

  • 2011 ANSYS, Inc. November 29, 201236

    Project & Data Model Concepts (6)

  • 2011 ANSYS, Inc. November 29, 201237

    Try out

    Record a journal from WB and using any text editor, extract the user inputs to the top

    Replay the journal file