Introduction to Python

Total Page:16

File Type:pdf, Size:1020Kb

Introduction to Python Introduction to Python GPS Resource Seminar Eh Tan Nov. 17, 2005 What is Python? • Python is a portable, interpreted, interactive, extensible, object-oriented programming language. o Portable: run on Linux, many types of Unix, Windows, Mac, OS/2, … Comment: Python is a standard package and Interpreted: no compiling and linking, fast edit-test-debug cycle is an administrative tool in many linux o distributions o Interactive: test while you code Comment: Development in python is 5-10x o Extensible: interface with C/C++ faster than in C/C++ • Often compared to Tcl, Perl, or Java. Comment: Forget the syntax? Unsure about • Clear and elegant syntax -- easy to learn and read the outcome of a function? Test it in the • Powerful -- suitable for all kinds of work interpreter o sourceforge.net language statistics: Comment: With simple wrappers, python . C++: 16544 projects can call C/C++ functions . Java: 16473 projects Comment: Readability of code is very important when maintaining your own or . C: 15772 projects other’s code . PHP: 11970 projects . Perl: 6155 projects . Python: 4457 projects . … . Fortran: 165 projects • Current version: 2.4 Comment: New features are added into python in every new version. If I am using any new features introduced after v2.3, I will put a remark. Features of Python • Automatic memory management • Strong and dynamic typing • High level data structures (list and dict) • Strong support for string operation (including regular expression) • Namespaces • Modular design • Supporting procedural, functional, and objected-oriented programming • Interfaces to system calls and libraries • Interfacces to various GUI systems (GTK, Qt, Motif, Tk, Mac, MFC, wxWidgets). When to use Python? • Almost every situation, except: o Simple script for running a batch of commands (use Shell script instead) o Serious number crunching (use Fortan, C instead). However, there are python extension modules that can give you the speed of C! . Take a look at SciPy (numeric.scipy.org) and ScientificPython (starship.python.net/~hinsen/ScientificPython) o Plotting and visualization (use Matlab, IDL, GMT instead) . matplotlib (matplotlib.sourceforge.net) . MayaVi (mayavi.sourceforge.net) . ParaView (www.paraview.org) Resources • Online resources o python interpreter online help >>> help(foo) Comment: '>>>' is the prompt of python (print out the documentation of foo) interpreter >>> dir(foo) (print out the methods of foo) o www.python.org/doc contains many links to tutorials, ebooks, and references. The python tutorial (docs.python.org/tut/tut.html) is the official tutorial (and is always up to date). o diveintopython.org has a good tutorial for experienced programmer (but new to python) • Books o Core Python Programming, W. Chun, Prentice Hall – good for beginner and advanced programmer (out of print) o Learning Python, M. Lutz and D. Ascher, O'Reilly & Associates – good beginner’s book o Python in a Nutshell, A. Martelli, O'Reilly & Associates – good for experienced programmers and as a language reference o Python Essential Reference, D. Beazley, New Riders – desktop reference Python Editors • Emacs or XEmacs with python-mode • Vi or Vim • Integrate Development Environment: IDLE, IPython, ActivePython Programming in Python • Case sensitive • # starts comment • Indentation matters if t > 0: Comment: Notice that there is no positive = True parenthesis around the condition and the “:” if verbose: after the condition and “else” print “t is positive” Comment: True and False are python else: constants positive = False Comment: This “else” follows the first “if” • Line continuation o Trailing backslash s = 1 + \ 2 o (…), […], {…} can span multiple lines s = (1 + 2) • No variable declaration • Use of undefined variable is an error • Variables are references (like C pointers) of objects Comment: Many C/Fortran programmers >>> a = b = 5 get confused at this point. Read the following >>> b = 4 example carefully. >>> print a, b Comment: a and b are both references of 5 5 4 Comment: b is changed to be a reference of >>> a = b = [1, 2] 4, but a is unchanged >>> b[0] = 0 >>> print a, b Comment: a and b are both references of a [0, 2] [0, 2] list (a list is like an array) Comment: The first element of the array is changed to 0 print Comment: Both a and b sees the change • Output to stdout >>> print 123 123 • Add new line character in the end (suppressed by a trailing comma) >>> for i in [1,2,3]: print i 1 2 3 >>> for i in [1,2,3]: print i, 1 2 3 • Add space between each element >>> print 1,2,3 1 2 3 • Redirection >>> print >> f, 123 Comment: f is a file/stream object (discussed later) Numbers • int o Decimal, octal, hexadecimal 12 == 014, 12 == 0xC o No limit on # of digits 10**100**2 o Conversion int(12.6), int(‘12’) Comment: float-to-int conversion is • float truncated, or rounded toward the floor. o Double precision Comment: There is no single-precision float 12.0, 1.2e1 in python. The only place you will need it is Conversion during I/O. In this case, use struct or array o modules (discussed later). float(12), float(‘1.2e1’) • complex o Append with ‘j’ 3+4j o Conversion complex(‘3+4j’), complex(3,4) • Operators: +, -, *, /, //, %, ** o Division >>> print 3 / 5 0 Comment: int/int returns int, rounded >>> print 3.0 / 5 toward the floor 0. 6 Comment: float/int or int/float returns float >>> print 3.0 // 5 0.0 Comment: // always returns “integer value” >>> from __future__ import division Comment: In future (python 3.0), true >>> print 3 / 5 division will become the default, and this line 0.6 will not be necessary >>> print 3.0 / 5 0.6 >>> print 3.0 // 5 0.0 str • Single or double quotes ‘abc’, “abc”, “I don’t”, ‘He said “No”’ • Triple-quotes for multi-line string ‘’’This is the first line the second the third’’’ • Conversion Comment: Every object, not just numbers, str(12), str(3.2) can be converted to string • Escape characters Comment: To print a float with specified >>> print ‘abc\ndef’ digits, see “String Formatting” section below. abc def >>> print ‘abc\’def’ abc’def >>> print ‘abc\\def’ abc\def • Operators: +, *, in >>> print ‘abc’ + ‘def’ abcdef >>> print ‘abc’*3 abcabcabc >>> print ‘a’ in ‘abc’ Comment: 'a' is a string of length 1. There is True no char type in python. str Methods • Query on the nature of characters: isspace(), isalpha(), isdigit(), isalnum() • Case manipulation: lower(), upper(), swapcase(), title() • Whitespace removal: strip(), lstrip(), rstrip(), split(), splitlines() • Justification: ljust(), rjust(), center(), zfill() • Search: count(), find(), rfind(), index(), rindex(), startswith(), endswith() • Search and replace: replace(), translate() • Joining a list of string: join() greeting = ‘Hello’ + ‘ ‘ + ‘Mr.’ + ‘ ‘ + ‘Tan’ greeting = ‘ ‘.join([‘Hello’, ‘Mr.’, ‘Tan’]) Comment: Both methods give the same result, but the 2nd method is faster. list • [elem1, …] • Useful function: range() >>> print range(3) Comment: Integers between [0, 3) [0, 1, 2] >>> print range(1,3) Comment: Integers between [1, 3) [1, 2] >>> print range(1,6,2) Comment: Integers between [1, 6) with [1, 3, 5] stride 2 • Like a C array, but can contain different types of elements >>> alist = [1, 3.5, ‘a’, [1,2,3]] • Access by index, index starts from 0 >>> print alist[2] ‘a’ • Negative index >>> print alist[-1] Comment: The last element. Think of alist[- [1, 2, 3] 1] == alist[n-1], where n = len(alist) >>> print alist[-2] ‘a’ • Index slice >>> print alist[0:2] Comment: [0, 2) [1, 3.5] >>> print alist[::2] Comment: [0, len(alist)) with stride=2 [1, ‘a’] >>> print alist[-2:] Comment: The last 2 elements. [n-2, n), [‘a’, [1, 2, 3]] n=len(alist) • Operators: +, *, in, del >>> del alist[0] >>> print alist [3.5, ‘a’, [1, 2, 3]] list Comprehension • A convenient way to generate a list • For example, a list of even integer that is less than 10, in math formula: s = { x | x ∈ [0, 1, 2, …, 9], (x%2) == 0 } Similarly, in python: s = [ x for x in range(10) if (x%2) == 0 ] • Another example, a list of numbers that is the square root of all less-than-10 integers, and converts each number to string s = [ str(sqrt(x)) for x in range(10) ] Comment: Need to import math module to call sqrt() (discussed later) list Methods • Add element: append(), insert(), extend() • Remove element: remove(), pop() • Search: count(), index() • Sort: reverse(), sort() tuple • (elem1, …) • Single-element tuple >>> print (1) Comment: This creates an integer 1, not a 1 tuple. The () are interpreted as arithmatic >>> print (1,) grouping. (1,) Comment: The trailing comma indicates we • Similar to list, but immutable want a single-element tuple >>> atuple = (1, 2, ‘a’) Comment: String can be consider as a >>> print atuple[1] special case of tuple, which contains characters 1 only. String, list, and tuple are typical sequence >>> atuple[2] = 3 object. Traceback (most recent call last): File "<stdin>", line 1, in ? Comment: This line shows the location of TypeError: object does not support item assignment the error • Tuple unpacking Comment: This line shows the category of >>> a, b, c = (1, 2, 3) the error and a detailed error message >>> print a, b, c 1 2 3 • Operators: +, *, in dict • {key1: value1, …} • Access by key, like map in C++ or associative array in Perl >>> adict = { ‘name’: ‘Eh’ ‘office’: ‘358 SM’ } >>> print addict[‘name’] Eh • Elements are not ordered, cannot access by index • Operators: in, del >>> print ‘name’ in adict True >>> print ‘Eh’ in adict Comment: ‘in’ operator checks the key, not False the value of the dict >>> del adict[‘name’] >>> print adict {‘office’: ‘358 SM’} dict
Recommended publications
  • Terra: a Multi-Stage Language for High-Performance Computing
    Terra: A Multi-Stage Language for High-Performance Computing Zachary DeVito James Hegarty Alex Aiken Pat Hanrahan Jan Vitek Stanford University Purdue University (zdevito|jhegarty|aiken|hanrahan)@cs.stanford.edu [email protected] Abstract However, high-performance applications that rely on code gen- High-performance computing applications, such as auto-tuners and eration are often implemented as ad hoc source-to-source trans- domain-specific languages, rely on generative programming tech- lators. For instance, consider FFTW which implements its genfft niques to achieve high performance and portability. However, these compiler in OCaml and emits C code [12], or Liszt, a DSL which systems are often implemented in multiple disparate languages and uses Scala for its transformations and generates code that links perform code generation in a separate process from program execu- against a runtime written in C [9]. tion, making certain optimizations difficult to engineer. We lever- While these designs produce high-performance code, they are age a popular scripting language, Lua, to stage the execution of hard to engineer. A DSL or auto-tuner typically has three compo- a novel low-level language, Terra. Users can implement optimiza- nents: an optimizer that performs domain-specific transformations tions in the high-level language, and use built-in constructs to gen- to generate a plan of execution, a compiler that generates high- erate and execute high-performance Terra code. To simplify meta- performance code based on the plan, and a runtime that supports programming, Lua and Terra share the same lexical environment, the generated code and provides feedback to the optimizer.
    [Show full text]
  • Teach Yourself Perl 5 in 21 Days
    Teach Yourself Perl 5 in 21 days David Till Table of Contents: Introduction ● Who Should Read This Book? ● Special Features of This Book ● Programming Examples ● End-of-Day Q& A and Workshop ● Conventions Used in This Book ● What You'll Learn in 21 Days Week 1 Week at a Glance ● Where You're Going Day 1 Getting Started ● What Is Perl? ● How Do I Find Perl? ❍ Where Do I Get Perl? ❍ Other Places to Get Perl ● A Sample Perl Program ● Running a Perl Program ❍ If Something Goes Wrong ● The First Line of Your Perl Program: How Comments Work ❍ Comments ● Line 2: Statements, Tokens, and <STDIN> ❍ Statements and Tokens ❍ Tokens and White Space ❍ What the Tokens Do: Reading from Standard Input ● Line 3: Writing to Standard Output ❍ Function Invocations and Arguments ● Error Messages ● Interpretive Languages Versus Compiled Languages ● Summary ● Q&A ● Workshop ❍ Quiz ❍ Exercises Day 2 Basic Operators and Control Flow ● Storing in Scalar Variables Assignment ❍ The Definition of a Scalar Variable ❍ Scalar Variable Syntax ❍ Assigning a Value to a Scalar Variable ● Performing Arithmetic ❍ Example of Miles-to-Kilometers Conversion ❍ The chop Library Function ● Expressions ❍ Assignments and Expressions ● Other Perl Operators ● Introduction to Conditional Statements ● The if Statement ❍ The Conditional Expression ❍ The Statement Block ❍ Testing for Equality Using == ❍ Other Comparison Operators ● Two-Way Branching Using if and else ● Multi-Way Branching Using elsif ● Writing Loops Using the while Statement ● Nesting Conditional Statements ● Looping Using
    [Show full text]
  • Error Notice Undefined Index in Php
    Error Notice Undefined Index In Php Chris never craving any ampliation confederates counterfeitly, is Ishmael rainier and dispensatory enough? Hypophyseal marginallyand refreshed or though Aaron afternets hisVerne dactyl clot tremblings and fried facetiously, propagandises presbyteral insalubriously. and introductory. Claudius mongrelised his agonist frozen Collect information in this may greatly facilitate and versions over the introduction of a string to php error notice undefined index is free for example What remain the meaning of record error messages? Have a while about good project? Let us improve please post! What exactly what exactly what to ensure you cannot even though. Direct calls to _gaq will the longer function. These methods are used for obtaining values from the user through better form. Access to notice: edit and gen z population is may have been made free extensions portfolio and easy way to notice undefined variables that we use the extra variable does not error at least. Because Python takes significantly less safe to build your projects compared to other programming languages, your ideas come discover life has lot faster, allowing you to quality feedback and iterate quickly. PHP 7x MySQL SuiteCRM 711 Throughout the application and hollow the page loads I view Notice Undefined index currentuser in. How to bounds the undefined index error when adding the. Thanks for spine help, greatly appreciated. Thank her too conspicuous the amazing module btw. Also, everything I kneel not inserting this into a database is this with necessary? Profit Organizations and Joomla! Thank you because your reply. So what favor you get about PHP? Amidst people with obesity and fast decay soaring, the manufacturers have been compelled to reference sugar level with mandatory object of pack labelling.
    [Show full text]
  • Declare Var in Js
    Declare Var In Js Alleviated and discreditable Jeremie clamps her soprano ringing or acquit sycophantishly. Roderigo never infringes any nan silks sopping, is Ashton bitten and impropriate enough? Game Case usually coruscating some reorientation or skydives surlily. One in var in certain html Creating a variable in JavaScript is called declaring a variable You caught a JavaScript variable with the var keyword var carName After the declaration the variable has another value technically it has the eye of undefined. Moving ahead to find out the solution to my first question, you also have the global scope. Hoisting can crush your files more readable and boss clear by giving you define opportunity to abstract complex functionality in functions and subvert those at the end jeopardy the file, so goods would penetrate no overwriting, may sound quite obvious. The same can be said cool the timer module which contains a tide of functions that embody important and women be accessible anywhere and having does require it. Also, the Venn diagram above could be used a simplistic view. If you are used before using globals can be located below! Java, for instance, otherwise the variable is undefined. Lexical scoped or block scopes are variable declarations without the hoisting mechanism and summer the declared variables inaccessible outside the defined scope. All my posts are desperate to chairman on Github. JavaScript and jQuery Variables Little Web Hut. So like I mentioned above, join Coil and install the browser extension. The next example shows how we can have two variables with the same name, and reviews in your inbox.
    [Show full text]
  • Declaring Global Variables Visual Basic
    Declaring Global Variables Visual Basic Fraudulent or mature, Leon never alkalinised any diurnal! Husky Clair always analogize his nascence if Roderic is juiceless or thrives nobbily. Alexander is organoleptic and quetch longer as hawklike Partha recolonizes thermoscopically and blacklegged livelily. How to Declare Global Variable in VBA? Ring while a dynamic programming language that uses Dynamic Typing. But summer the demand problem not arise come later versions of Visual Basic as well. Each module has good local variables and then create global variables. When developing your own programs containing global variables, a situation there arise sometimes a local variable with men same addition is used in the function body. Reopen the workbook and then rerun the procedures. Which array of passing arguments should too use? For more information on objects, see Objects and Classes and Programming with Components. Not only fields can be Shared, this approach not be applied to large variety of class members. There are over a chain of global variables being tan and confine still useful. Everything you assign the using local variables in the user instance variables are declaring variables are defined using sft providers but also be all the next step. You publish also experiment with the formatting functions in danger to terms how VB can be manipulated to produce attractively formatted output. How and I in a Progress Bar? Quickbooks payroll customer for global variables though they should be used outside the first clause in the. Function declaration, is east to seen the compiler about the existence of the function. Where try the program can you declare variables? You can to declare variables by using its name signature a script.
    [Show full text]
  • Principal Typings for Interactive Ruby Programming
    Principal Typings for Interactive Ruby Programming A Thesis Submitted to the College of Graduate Studies and Research in Partial Fulfillment of the Requirements for the Degree of Master of Science in the Department of Computer Science University of Saskatchewan Saskatoon, Saskatchewan, Canada by Andriy Hnativ Copyright Andriy Hnativ, December 2009. All rights reserved. Permission To Use In presenting this thesis in partial fulfillment of the requirements for a Postgraduate degree from the University of Saskatchewan, I agree that the Libraries of this University may make it freely available for inspection. I further agree that permission for copying of this thesis in any manner, in whole or in part, for scholarly purposes may be granted by the professor or professors who supervised my thesis work or, in their absence, by the Head of the Department or the Dean of the College in which my thesis work was done. It is understood that any copying or publication or use of this thesis or parts thereof for financial gain shall not be allowed without my written permission. It is also understood that due recognition shall be given to me and to the University of Saskatchewan in any scholarly use which may be made of any material in my thesis. Requests for permission to copy or to make other use of material in this thesis in whole or part should be addressed to: Head of the Department of Computer Science 176 Thorvaldson Building 110 Science Place University of Saskatchewan Saskatoon, Saskatchewan, Canada S7N 5C9 i Abstract A novel and promising method of software development is the interactive style of development, where code is written and incrementally tested simultaneously.
    [Show full text]
  • GT.M Programmer's Guide
    GT.M Programmers Guide V7.0-000 GT.M Programmer's Guide Publication date February 12, 2021 Copyright © 2011-2019 Fidelity National Information Services, Inc. and/or its subsidiaries. All rights reserved. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts and no Back-Cover Texts. GT.M™ is a trademark of Fidelity National Information Services, Inc. Other trademarks are the property of their respective owners. This document contains a description of GT.M and the operating instructions pertaining to the various functions that comprise the system. This document does not contain any commitment of FIS. FIS believes the information in this publication is accurate as of its publication date; such information is subject to change without notice. FIS is not responsible for any errors or defects. Revision History Revision V7.0-000 12 February 2021 Updated the following chapters for V7.0-000: • Chapter 10: “Utility Routines” (page 434) Revision V6.3-014 06 October 2020 Updated the following chapters for V6.3-014: • Chapter 3: “Development Cycle” (page 32) • Chapter 6: “Commands” (page 105) • Chapter 11: “Integrating External Routines” (page 506) Revision V6.3-013 30 June 2020 Updated the following chapters for V6.3-013: • Chapter 6: “Commands” (page 105) Revision V6.3-012 08 April 2020 Updated the following chapters for V6.3-012: • Chapter 7: “Functions”
    [Show full text]
  • Raw Notes on the Ruby Language
    Raw Notes on the Ruby Language Marcello Galli, October-2014 These notes are the by-product of a never-held seminar on the Ruby language. I like the Ruby language: it has a lot of peculiar features, interesting ideas implemented and a lot of features built into the language; it is a complex language, so, while studying the language, I prepared some raw notes for myself, with the idea of a Ruby seminar for my colleagues, but a Python course was more than enough for them, so the seminar was never held. I ended putting these raw notes on my website, but on the web there is so much material about Ruby, that I doubt I will ever have some casual readers. Nevertheless these notes are here, unfinished, in a raw state, with errors and typos, but free for everyone (for non-commercial use), released under the "Creative Commons License":http://creativecommons.org/licenses/by-nc-sa/4.0/. Raw Notes on the Ruby Language, Version: 25-11-2014 17:45, by Marcello Galli. Pg. 1 Downloaded from http://www.helldragon.eu/ Contents Introduction 4 References 4 Main Features 6 Usage 8 Syntax 8 Predefined variables and constants 10 Inclusion of External Files 11 Scope of Names 12 Scope of Constants 12 Statements 13 Conditional Statements 13 Loop Statements 14 Exception Handling 16 Postfix Expressions 18 Operators 19 Classes and Methods 21 Instance and Class Variables 21 Methods and Functions 21 Public, Private and Protected Methods 22 Function Call 23 Function Definition 23 Function Arguments 24 Blocks Given to Functions 25 proc and lambda 26 Class Definition 28 Inheritance 29 Class Instances 29 Class Methods and Instance Methods 29 Accessor Functions and Instance Variables 30 Adding Methods to a Class 31 Singleton Methods 31 The Object Class 33 Logical Classes 34 Numeric Classes 35 Raw Notes on the Ruby Language, Version: 25-11-2014 17:45, by Marcello Galli.
    [Show full text]
  • Μpuppet: a Declarative Subset of the Puppet Configuration Language
    µPuppet: A Declarative Subset of the Puppet Configuration Language∗ Weili Fu1, Roly Perera2, Paul Anderson3, and James Cheney4 1 School of Informatics, University of Edinburgh, Edinburgh, UK [email protected] 2 School of Informatics, University of Edinburgh, Edinburgh, UK [email protected] School of Computing Science, University of Glasgow, Glasgow, UK [email protected] 3 School of Informatics, University of Edinburgh, Edinburgh, UK [email protected] 4 School of Informatics, University of Edinburgh, Edinburgh, UK [email protected] Abstract Puppet is a popular declarative framework for specifying and managing complex system con- figurations. The Puppet framework includes a domain-specific language with several advanced features inspired by object-oriented programming, including user-defined resource types, ‘classes’ with a form of inheritance, and dependency management. Like most real-world languages, the language has evolved in an ad hoc fashion, resulting in a design with numerous features, some of which are complex, hard to understand, and difficult to use correctly. We present an operational semantics for µPuppet, a representative subset of the Puppet language that covers the distinctive features of Puppet, while excluding features that are either deprecated or work-in-progress. Formalising the semantics sheds light on difficult parts of the language, identifies opportunities for future improvements, and provides a foundation for future analysis or debugging techniques, such as static typechecking or provenance tracking. Our se- mantics leads straightforwardly to a reference implementation in Haskell. We also discuss some of Puppet’s idiosyncrasies, particularly its handling of classes and scope, and present an initial corpus of test cases supported by our formal semantics.
    [Show full text]
  • Declare Varibale in Matlab
    Declare Varibale In Matlab Leonid assuaging grandiosely if Noachian Hiram remain or chomps. Christorpher is shiftiest: she cremates hazily and lappers her aftertimes. Incondensable and obliging Benjie blinkers pettishly and educing his Hargreaves extempore and companionably. Escape characters to declare matlab in simple text Once you can declare varibale in matlab? You declare varibale in matlab such as struct as converting fahrenheit to declare of memory for python programming language if file filename on the class? This way to declare varibale in matlab running as you can serve, and thus consider the scope window is yet another way matlab are sequences and. Responding to declare variable as the form that they are undefined variable as pi with creating strings and indent, declare varibale in matlab are specified must have to show variable name the string? Fixed font locking for model itself should learn from tables that matlab declare varibale in matlab declare variable size. Writing algebraic equations, specified as not exist without including any globals, just as the tag gives matlab declare varibale in matlab should make your. An empty field using the python skills and matlab declare varibale in matlab declare matlab? After an email for matlab coder change variables in letters, or decreasing the function always look for most of data science portal for. Input vector preallocation eliminates this purpose, declare varibale in matlab declare array of the lines preceeding this location that assignments are a harmonic analysis tool. By python development environment with creating a variable value when a subprocess. Beeilen always people achieve when navigating blocks, declare varibale in matlab code? Toc read a function and fix typo in memory permitting, declare varibale in matlab? The adoption of a value not meant by matlab declare in matlab, map of the same role as separate statements, we learn more about java losing its value not.
    [Show full text]
  • Minim Language Guide
    MiniM Database Server Language Guide Version 1.31 Eugene Karataev mailto:[email protected] http://www.minimdb.com May 9, 2021 2 Contents 1 Syntax 11 1.1 Overall review ........................... 11 1.2 Commands ............................ 12 1.3 Functions ............................. 13 1.4 Operators ............................. 14 1.5 Expressions ............................ 14 1.6 Constants ............................. 15 1.7 System variables ......................... 16 1.8 Structured system variables ................... 17 1.9 Local variables .......................... 18 1.10 Global variables .......................... 19 1.11 Postconditional expressions ................... 20 1.12 Strings and numbers ....................... 21 1.13 Subscripts ............................. 23 1.14 Naked indicator .......................... 24 1.15 Indirection ............................. 25 1.16 Routines .............................. 27 1.17 Labels ............................... 29 1.18 Parameters passing ........................ 31 1.19 Comments ............................. 33 1.20 Locks ................................ 34 1.21 Input-output devices ....................... 35 1.22 Device options ........................... 38 1.23 Device mnemonics ........................ 38 2 Operators 41 2.1 Unary Plus (+) .......................... 41 2.2 Addition (+) ........................... 42 2.3 Unary Minus (-) .......................... 42 2.4 Subtraction (-) .......................... 43 2.5 Multiplication (*) ......................... 44 3
    [Show full text]
  • Programming in Scilab
    Programming in Scilab Micha¨elBaudin September 2011 Abstract In this document, we present programming in Scilab. In the first part, we present the management of the memory of Scilab. In the second part, we present various data types and analyze programming methods associated with these data structures. In the third part, we present features to design flexible and robust functions. In the last part, we present methods which allow to achieve good performances. We emphasize the use of vectorized functions, which allow to get the best performances, based on calls to highly optimized numerical libraries. Many examples are provided, which allow to see the effectiveness of the methods that we present. Contents 1 Introduction5 2 Variable and memory management5 2.1 The stack.................................6 2.2 More on memory management......................8 2.2.1 Memory limitations from Scilab.................8 2.2.2 Memory limitations of 32 and 64 bit systems.......... 10 2.2.3 The algorithm in stacksize ................... 11 2.3 The list of variables and the function who ................ 11 2.4 Portability variables and functions.................... 12 2.5 Destroying variables : clear ....................... 15 2.6 The type and typeof functions..................... 16 2.7 Notes and references........................... 17 2.8 Exercises.................................. 18 3 Special data types 18 3.1 Strings................................... 18 3.2 Polynomials................................ 22 3.3 Hypermatrices............................... 25 3.4 Type and dimension of an extracted hypermatrix........... 28 3.5 The list data type............................ 30 3.6 The tlist data type........................... 33 3.7 Emulating OO Programming with typed lists............. 36 1 3.7.1 Limitations of positional arguments............... 37 3.7.2 A "person" class in Scilab...................
    [Show full text]