Python Programming, bridging course 2011

Similar documents
The current topic: Python. Announcements. Python. Python

CIS192: Python Programming

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Sunpy Python for Solar Physics Juan Carlos Martínez Oliveros

CIS192 Python Programming. Robert Rand. August 27, 2015

Senthil Kumaran S

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

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

Introduction to Python

Introduction to Python. Didzis Gosko

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Table of Contents EVALUATION COPY

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

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

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

And Parallelism. Parallelism in Prolog. OR Parallelism

Python for Non-programmers

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

CS Advanced Unix Tools & Scripting

Python for Earth Scientists

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

ENGR 102 Engineering Lab I - Computation

Introduction to Python

CSI33 Data Structures

Programming in Python 3

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

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

CS1 Lecture 3 Jan. 22, 2018

Introduction to Python (All the Basic Stuff)

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Pace University. Fundamental Concepts of CS121 1

LECTURE 1. Getting Started with Python

ActiveNET. #202, Manjeeraa Plaza, Ameerpet, HYD

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Programming for Engineers in Python. Autumn

Introduction to Bioinformatics

CS1 Lecture 3 Jan. 18, 2019

Basic Python 3 Programming (Theory & Practical)

Python for C programmers

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Python. Department of Computer Science And Engineering. European University Cyprus

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd

Programming for Engineers in Python. Recitation 1

ERTH3021 Exploration and Mining Geophysics

Scientific Computing using Python

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Introduction to Python

Python Input, output and variables

Beyond Blocks: Python Session #1

Physics 514 Basic Python Intro

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Computer Lab 1: Introduction to Python

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Accelerating Information Technology Innovation

Scientific Computing: Lecture 1

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Introduction to Python. Prof. Steven Ludtke

Topological Invariants with Z2Pack. Topological Matter School 2016, Donostia

Introduction to Python Part 1

Chapter 2 Getting Started with Python

CS Exam 2 Name: Your Grading TA: This exam has 7 pages including the title page. Please check to make sure all pages are included.

18.1. CS 102 Unit 18. Python. Mark Redekopp

A. Python Crash Course

Some material adapted from Upenn cmpe391 slides and other sources

Python Tutorial. CSE 3461: Computer Networking

Day 15: Science Code in Python

Introduction to Python - Part I CNV Lab

CS Programming Languages: Python

Key Differences Between Python and Java

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

The SciPy Stack. Jay Summet

C: How to Program. Week /Mar/05

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

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

Introduction to VTK and Python. Filip Malmberg Uppsala universitet

a b c d a b c d e 5 e 7

python 01 September 16, 2016

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Research Computing with Python, Lecture 1

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

ARTIFICIAL INTELLIGENCE AND PYTHON

The Pyth Language. Administrivia

CS 1301 Exam 1 Fall 2009

Rapid Application Development with

Contents. Lezione 3. Reference sources. Contents

Python Class-Lesson1 Instructor: Yao

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

Introduction to Python, Cplex and Gurobi

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

SOFT 161. Class Meeting 1.6

Introduction to Python Part 2

Transcription:

Python Programming, bridging course 2011

About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead.

Online Python resources http://www.python.org/ http://docs.python.org/ http://en.wikipedia.org/wiki/python_(programming_language) Tutorials: http://www.poromenos.org/tutorials/python http://www.it.uu.se/edu/course/homepage/progbrygg/ht11/python/tutorial1.py http://www.it.uu.se/edu/course/homepage/progbrygg/ht11/python/tutorial2.py http://www.it.uu.se/edu/course/homepage/progbrygg/ht11/python/tutorial3.py

Books If you want to know more: Python Essential Reference, D. Beazley, 2009 - manual-like, few examples, concise Dive Into Python, M. Pilgrim, 2004 - popular but a little old Core Python Programming, W. Chun, 2006 Python programmering, E. Lindblad, 2006 - in Swedish, easy to read

Examination Complete the assignments for passing grade For grades 4 & 5 you have to write the exam

Python General purpose high-level programming language Designed by Dutch programmer Guido Van Rossum who released the first version in 1991 Managed by Python Software Foundation. There is an active community that contributes to Python's development

Lecture outline Example program Some general remarks about Python Python: Basic statements Code partitioning Fundamental data types

Script example Demonstrate how to get input from the command line how to call a math function like sin(x) how to work with variables how to print text and numbers

The code File hw.py: #!/usr/bin/env python # load system and math module: import sys, math # extract the 1st command-line argument: r = float(sys.argv[1]) s = math.sin(r) print "Hello, World! sin(" + str(r) + ")=" + str(s) Make the file executable (on Unix): chmod a+rx hw.py

Running the example All computer languages intros start with a program that prints "Hello, World!" to the screen Engineering extension: read a number, compute its sine value, and print out The script, called hw.py, should be run like this: python hw.py 3.4 or just (Unix)./hw.py 3.4 Output: Hello, World! sin(3.4)=-0.255541102027

Comments The first line specifies the interpreter of the script (here the first python program in your path) python hw.py 1.4 # first line is not treated as comment./hw.py 1.4 # first line is used to specify an interpreter Even simple scripts must load modules: import sys, math Numbers and strings are two different types: r = sys.argv[1] # r is string s = math.sin(float(r)) # sin expects number, not string r # s becomes a floating-point number

Programming languages Application: batch, script, applications, web, database, numerical, education... Paradigms: imperative/declarative, objectoriented... Other differentiations: dynamic/static type checking, expressiveness, speed, compiled/interpreted, high-/lowlevel... http://en.wikipedia.org/wiki/programming_language

Important aspects outside language Available libraries Programming tools Supported platforms Integration with other components Documentation Community PR

Compiled vs interpreted languages In some way the code we write must be translated to machine code. Alternative 1: When you've finished programming you run a compiler to do the translation (compiling), and a resulting binary file containing the machine code is acquired. Examples: C, Fortran. Alternative 2: An interpretator do the translation (interpretation) when the program is executed. You say you run your script code directly. Examples: Python, Perl, Ruby. Not entirely true, and the two alternatives are converging.

Are scripts compiled? Are Python scripts compiled? Yes and no, depending on how you see it Python first compiles the script into bytecode The bytecode is then interpreted No linking with libraries; libraries are imported dynamically when needed It appears as there is no compilation Quick development: just edit the script and run! (no time-consuming compilation and linking) Extensive error checking at run time

Python benefits Concise Readable Portable Many language elements Extensive standard library Easy to integrate with C/C++

Python drawbacks Execution speed Multi-threading not very good

Python popularity Open source commits according to ohloh.net

History of Python 1991, First source code release to alt.sources 1994, v1.0 2000, v2.0, garbage collection 2008, v3.0, many redundant commands are removed, increased coherency, broke backward compatibility

Python tasks Internet applications, for example via HTTP, FTP, SMTP and CGI. Control program for components written in low level languages, glue together building blocks. Portable programs Database programming. Database server is the limiting factor, not the client. Not suitable: time critical modules, safety critical systems

Python interpreter You can also run the interpreter without a program file, and instead use Python in command line mode: >>> print "Hello World!" Hello World! >>> import math >>> 73 - math.sqrt(52) 65.788897449072024 >>> _ - 2 63.788897449072024 _ stores the last result (not available in scripts)

Basic statements in Python Control statements - controlling execution flow Conditional: if, elif, else - Determines whether a code block should be executed or not. Loop: for, while - Iterates over a list - Executes a code block many times.

If-statements if a < b: print "a is smaller than b" elif a == b: print "a is equal to b" else: print "a is greater than b" No parenthesis needed in the conditional statement. No braces to denote code blocks. It's specified by the indentation. Multiple choices are handled with 'elif', there isn't any 'switch' as in some languages, as redundant features are avoided.

For-loops Executes a code block many times for each iterated element for x in range(3): print "x: " + str(x) >python test.py x: 0 x: 1 x: 2 >

For-loops With an extra code line in the loop: import math for x in range(3): print "x: " + str(x), print "sin(x): " + str(math.sin(x)) >python test.py x: 0 sin(x): 0.0 x: 1 sin(x): 0.841470984808 x: 2 sin(x): 0.909297426826 >

For-loop formats For-loop in Python: for i in range(start,stop,inc):... for j in range(stop):... generates: i = start, start+inc, start+2*inc,..., stop-1 j = 0, 1, 2,..., stop-1

Nested for-loops For-loops can be inside other for-loops in any number of steps for x in range(2): for y in range(2): for z in range(2): print x,y,z >python test.py 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 >

Code partitioning Plain script Functions Classes Modules

Defining a function import math def myfunc(y): if y >= 0.0: return y*5*math.exp(-y) else: return 0.0 # alternative way of calling module functions # (gives more math-like syntax in this example): from math import * def myfunc(y): if y >= 0.0: return y*5*exp(-y) else: return 0.0

Modules A module is corresponding to a file Example: # file: div.py def divide(a,b): q = a/b r = a - q*b return(q,r) to use in another file: import div a, b = div.divide(c, d)

Classes Classes bundle a set of objects and a set of functions. class Message: def init (self, astring): self.text = astring def printit(self): print self.text More about classes in a later lecture

Data type classes Numeric types: int, long, float, complex, bool Sequence types: str, unicode, list, tuple, xrange Mapping types: dict Set types: set, frozen set None type: type(none) Each class share the basic means of accessing elements.

Numeric types Booleans Integers, 32-bit signed Long integers Floating-point numbers, 64-bit, IEEE 754 Complex numbers Implicitly defined by how the number is written.

Strings Creation, no explicit typing >>> a = "Hello World" Indexing >>> a[:5] 'Hello' >>> a[6:] 'World' >>> a[4:7] 'o W' >>> Concatenation >>> a + " adding some text" 'Hello World adding some text'

Strings Single- and double-quoted strings work in the same way s1 = "some string" s2 = some string Triple-quoted strings can be multi line with embedded newlines: text = """ large portions of a text can be conveniently placed inside triple-quoted strings (newlines are preserved)""" Raw strings, where backslash is backslash: s3 = r \(\s+\.\d+\) # with ordinary string (must quote backslash): s3 = \\(\\s+\\.\\d+\\)

Two other sequences List: a = [1,2,3, four ] Tuple: b = (1,2,3, four ) Lists are slower but dynamic, tuples are faster but static. Indexed in the same way as strings.

Important libraries NumPy - multi-dimensional arrays and functions related to these SciPy - built using NumPy, integration, optimization, interpolation, linear algebra, statistics matplotlib - histograms, power spectra, bar charts, errorcharts, scatterplots

Assignment Calculating the largest eigenvalue and the corresponding eigenvector Test different ways of doing matrix multiplication Create a graphical user interface (GUI) for the algorithm

Python Editors/IDEs IDLE coming with the installation Free: Emacs, Wing 101 (Windows) Commercial: Wing, Komodo

Tips Python command prompt good for learning and checking small things. When you work on something you want to save in the end, I suggest coding directly into script files. Good code should be saved, and it forces you to think deeper about your problem and not just randomly trying different things out.

Exploring objects id(), type(), dir(), help() >>> p = 4 >>> id(p) 30222660 >>> type(p) <type 'int'> >>> dir(p) [' abs ', ' add '... >>> help(p) Help on int object:...