Computational Programming with Python

Similar documents
Computational Mathematics with Python

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Fundamentals: Expressions and Assignment

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Introduction to Engineering gii

COSC 490 Computational Topology

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Scientific Computing using Python

Essentials for the TI-83+

Introduction to Python Practical 1

ERTH3021 Exploration and Mining Geophysics

Episode 1 Using the Interpreter

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Expressions and Variables

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Our Strategy for Learning Fortran 90

Scientific Computing: Lecture 1

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Command Line and Python Introduction. Jennifer Helsby, Eric Potash Computation for Public Policy Lecture 2: January 7, 2016

Python: common syntax

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

2.0 MATLAB Fundamentals

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Python Programming Exercises 1

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

JME Language Reference Manual

Introduction to Scientific Computing with Python, part two.

Programming Fundamentals and Python

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Lists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists

Introduction to Programming

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction to Matlab

Variables, expressions and statements

Lab1: Use of Word and Excel

Introduction to Python, Cplex and Gurobi

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

Research Computing with Python, Lecture 1

ü 1.1 Getting Started

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

CGF Lecture 2 Numbers

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Choose the file menu, and select Open. Input to be typed at the Maple prompt. Output from Maple. An important tip.

Graphics calculator instructions

What is MATLAB and howtostart it up?

Introduction to MATLAB

Algorithms and Programming I. Lecture#12 Spring 2015

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

Sequence Types FEB

An SM tutorial for programming and plotting

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Lecture 2: Intro to Java

Programming in Python 3

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Semester 2, 2018: Lab 1

CSE/Math 485 Matlab Tutorial and Demo

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

CPS122 Lecture: From Python to Java

The Python interpreter

A Simple Syntax-Directed Translator

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

2.2 Syntax Definition

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS Advanced Unix Tools & Scripting

Computational Modelling 102 (Scientific Programming) Tutorials

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Fun with functions! Built-in and user-defined functions

AMS 27L LAB #2 Winter 2009

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

9. Elementary Algebraic and Transcendental Scalar Functions

Scientific Python. 1 of 10 23/11/ :00

1. Register an account on: using your Oxford address

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Phys Techniques of Radio Astronomy Part 1: Python Programming

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Java Bytecode (binary file)

Physics 514 Basic Python Intro

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Fundamental of Programming (C)

Downloaded from Chapter 2. Functions

What advantages has it?

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

Transcription:

Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis 2017

Numerical Analysis, Lund University, 2017 2 Why Python? Python is... Free and open source It is a scripting language - an interpreted not a compiled language It is object oriented with modern exception handling, dynamic typing etc. It has plenty of libraries among others the scientific ones: linear algebra; visualisation tools: plotting, image analysis; differential equations solving; symbolic computations; statistics ; etc. It has possible usages: Scientific computing, scripting, web sites, text parsing, data mining,...

Numerical Analysis, Lund University, 2017 3 Premisses We work with a Python version 3.0. We use an IPython shell We use the work environment Spyder We work (later) with the IPython notebook. We start our programs with the line endedchars from scipy import *

Numerical Analysis, Lund University, 2017 4 Course Book Scientific Computing with Python 3 Claus Führer, Jan Erik Solem, Olivier Verdier December 2016 www.packtpub.com/

Numerical Analysis, Lund University, 2017 5 Examples Python may be used in interactive mode (executed in an IPython shell) chars In [2]: x = 3 chars In [3]: y = 5 chars In [4]: print (x + y) chars 8 Note: chars In [2]: is the prompt string of the IPython shell. It counts the statements. In the more basic Python shell the prompt string is >>>.

Numerical Analysis, Lund University, 2017 6 Examples: Linear Algebra Let us solve ( ) 1 2 x = 3 4 ( ) 2 1 chars In [ 5]: from scipy. linalg import solve chars In [6]: M = array ([[ 1., 2.], chars [3., 4.]]) chars In [7]: V = array ([2., 1.]) chars In [8]: x = solve (M, V) chars In [9]: print (x) chars [-3. 2.5] Note: A line can be continued on the next line without any continuation symbol as long as parentheses or brackets are not closed.

Numerical Analysis, Lund University, 2017 7 More examples Computing e iπ and 2 100 : chars In [10 ]: print ( exp (1j*pi )) # should return -1 chars (-1+1. 22460635382e - 16j ) chars In [11 ]: print (2** 100 ) chars 1267650600228229401496703205376 Note: Everything following # is treated as a comment. Computing ζ(x) = 1 k=1 k with ζ(2) = x π2 6 gives chars In [ 12 ]: import scipy. special chars In [13 ]: scipy. special. zeta (2., 1) # x = 2 chars 1. 6449340668482266 chars In [14 ]: pi **2/6 chars 1. 6449340668482264

Numerical Analysis, Lund University, 2017 8 Numbers A number may be an integer, a real number or a complex number. The usual operations are + and - addition and substraction * and / multiplication and division ** power chars 2 **( 2+2) # 16 chars 1j **2 # -1

Numerical Analysis, Lund University, 2017 9 Strings Strings are lists of characters, enclosed by simple or double quotes: chars valid string chars " string with double quotes "

Numerical Analysis, Lund University, 2017 9 Strings Strings are lists of characters, enclosed by simple or double quotes: chars valid string chars " string with double quotes " You may also use triple quotes for strings including multiple lines: chars "\" " This is chars a long, chars long string "\" "

Numerical Analysis, Lund University, 2017 10 Variable Variables A variable is a reference to an object. An object may have several references. One uses the assignment operator = to assign a value to a variable. Example chars x = [3, 4] # a list object is created chars y = x # this object is now referenced by x and by y chars del x # we delete one of the references chars del y # all references are deleted : the object is deleted

Numerical Analysis, Lund University, 2017 11 Concept: Lists Lists A Python list is an ordered list of objects, enclosed in square brackets. One accesses elements of a list using zero-based indices inside square brackets.

Numerical Analysis, Lund University, 2017 12 List Examples Example chars L1 = [1, 2] chars L1[0] # 1 chars L1[1] # 2 chars L1[ 2] # raises IndexError chars chars L2 = [ a, 1, [3, 4]] chars L2[0] # a chars L2[2][0] # 3 chars chars L2[-1] # last element : [3,4] chars L2[- 2] # second to last : 1

Numerical Analysis, Lund University, 2017 13 List Utilities range(n) can be used to fill list with n elements, starting with zero: endedchars list ( range (5)) # [0, 1, 2, 3, 4]

Numerical Analysis, Lund University, 2017 13 List Utilities range(n) can be used to fill list with n elements, starting with zero: endedchars list ( range (5)) # [0, 1, 2, 3, 4] len(l) gives the length of a list: endedchars len ([ a, 1, 2, 34 ]) # returns 4

Numerical Analysis, Lund University, 2017 13 List Utilities range(n) can be used to fill list with n elements, starting with zero: endedchars list ( range (5)) # [0, 1, 2, 3, 4] len(l) gives the length of a list: endedchars len ([ a, 1, 2, 34 ]) # returns 4 Use append to append an element to a list: endedchars L = [ a, b, c ] endedchars L[-1] # c endedchars L. append ( d ) endedchars L # L is now [ a, b, c, d ] endedchars L[-1] # d

Numerical Analysis, Lund University, 2017 14 List Comprehension A convenient way to build up lists is to use the list comprehension construct, possibly with a conditional inside. Definition The syntax of a list comprehension is chars [<expr > for <variable > in <list >] Example chars L = [2, 3, 10, 1, 5] chars L2 = [x*2 for x in L] # [4, 6, 20, 2, 10] chars L3 = [ x* 2 for x in L if 4 < x <= 10] # [ 20, 10]

Numerical Analysis, Lund University, 2017 15 List Comprehension in Mathematics Mathematical Notation This is very close to the mathematical notation for sets. Compare: L 2 = {2x; x L} and chars L2 = [ 2* x for x in L] One big difference though is that lists are ordered while sets aren t.

Numerical Analysis, Lund University, 2017 16 Operations on Lists Adding two lists concatenates (sammanfogar) them: endedchars L1 = [1, 2] endedchars L2 = [3, 4] endedchars L = L1 + L2 # [1, 2, 3, 4]

Numerical Analysis, Lund University, 2017 16 Operations on Lists Adding two lists concatenates (sammanfogar) them: endedchars L1 = [1, 2] endedchars L2 = [3, 4] endedchars L = L1 + L2 # [1, 2, 3, 4] Logically, multiplying a list with an integer concatenates the list with itself several times: n*l is equivalent to L + L + + L. }{{} n times endedchars L = [1, 2] endedchars 3 * L # [1, 2, 1, 2, 1, 2] (To multiply each element by c, we use arrays instead of lists.)

Numerical Analysis, Lund University, 2017 17 for loops for loop A for loop allows to loop through a list using an index variable. This variable takes succesively the values of the elements in the list.

Numerical Analysis, Lund University, 2017 17 for loops for loop A for loop allows to loop through a list using an index variable. This variable takes succesively the values of the elements in the list. Example chars L = [1, 2, 10] chars for s in L: chars print ( s * 2) # output : 2 4 20

Numerical Analysis, Lund University, 2017 18 Repeating a Task One typical use of the for loop is to repeat a certain task a fixed number of times: chars n = 30 chars for i in range (n): chars do_ something # this gets executed n times

Numerical Analysis, Lund University, 2017 19 Indentation The part to be repeated in the for loop has to be properly indented: chars for elt in my_list : chars do_ something () chars something_ else () chars etc chars print (" loop finished ") # outside the for block

Numerical Analysis, Lund University, 2017 19 Indentation The part to be repeated in the for loop has to be properly indented: chars for elt in my_list : chars do_ something () chars something_ else () chars etc chars print (" loop finished ") # outside the for block Note: In contrast to other programming languages, the indentation in Python is mandatory. Many other kinds of Python structures also have to be indented, we will cover this when introducing them.

Numerical Analysis, Lund University, 2017 20 Elementary Plotting We first make the central visualization tool in Python available: chars from pylab import * Then we generate two lists chars x_list = list ( range ( 100 )) # the first hundred numbers chars y_list =[ sqrt ( x) for x in xlist ] And then we make a graph chars plot ( x_list, y_list, o ) chars title ( My first plot ) chars xlabel ( x ) chars ylabel ( Square root of x ) chars show ()

Elementary Plotting Numerical Analysis, Lund University, 2017 21

Numerical Analysis, Lund University, 2017 22 How to run a piece of code There are two phases in Python programming: 1. Writing the code 2. Executing (running) it For Task 2, one needs to give the code to the Python interpreter which reads the code and figures out what to do with it. Short snippets of code can be written directly in the interpreter and executed interactively. We use the interpreter IPython which has extra features. For writing a larger program, one generally uses a text editor which can highlight code in a good way. There are also development suites which bundle the interpreter, editor and other things into the same program.

Numerical Analysis, Lund University, 2017 23 Spyder Example of a development environment, Spyder

Numerical Analysis, Lund University, 2017 24 On our computers The computers in the computer room should have Python and Spyder installed under Windows. You should set up Spyder according to the instructions at http://www.maths.lth.se/na/nahelp/

Numerical Analysis, Lund University, 2017 25 On your computer To install Python and additional necessary libraries for this course, follow the instructions at http://www.maths.lth.se/na/nahelp/

Numerical Analysis, Lund University, 2017 26 IPython IPython is an enhanced Python interpreter. You can launch it as a stand-alone application, but it is also embedded in Spyder. Some notes on usage: To execute the contents of a file named myscript.py just write run myscript in IPython or use the green "run" arrow in the Spyder toolbar. Use the arrow keys to visit previous commands and Use the tabulation key to auto-complete commands and names To get help on an object just type? after it and then return When you want to quit, write exit()

Numerical Analysis, Lund University, 2017 27 Code Examples in the Lecture Summing and multiplying in loops Summing up the numbers from 1 to n Finding all integers less than 100 which can be divided by 7 Summing up all integers less than 100 which can be divided by 7 Plotting a circle Note the operators % and == in Python for division with rest and for comparing two numbers. These will discussed later in more detail.