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

Similar documents
CME 193: Introduction to Scientific Python Lecture 1: Introduction

CS1 Lecture 3 Jan. 22, 2018

Python Programming Exercises 1

CS1 Lecture 3 Jan. 18, 2019

CIS192: Python Programming

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

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

CIS192 Python Programming. Robert Rand. August 27, 2015

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Fundamentals of Programming (Python) Getting Started with Programming

Programming for Engineers in Python. Autumn

Introduction to Python (All the Basic Stuff)

Programming for Engineers in Python. Recitation 1

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

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

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

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

CS 112: Intro to Comp Prog

Beyond Blocks: Python Session #1

Variable and Data Type I

Getting Started with Python

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

Variable and Data Type I

CS 1301 Exam 1 Fall 2009

CS1 Lecture 2 Jan. 16, 2019

Python for Non-programmers

Conditional Expressions and Decision Statements

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Control Structures 1 / 17

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

PROGRAMMING FUNDAMENTALS

Variables, expressions and statements

Scientific Computing: Lecture 1

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

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

CS1 Lecture 4 Jan. 24, 2018

CMSC 201 Computer Science I for Majors

CS1 Lecture 5 Jan. 25, 2019

CS 1301 Exam 1 Answers Fall 2009

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

61A Lecture 3. Friday, September 5

CS 115 Lecture 4. More Python; testing software. Neil Moore

Science One CS : Getting Started

Welcome to Bootcamp2015 s documentation!

ENGR (Socolofsky) Week 02 Python scripts

CSCA08 Winter 2018 Week 2: Variables & Functions. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

Lecture 7. Memory in Python

Conditionals and Recursion. Python Part 4

ENGR 101 Engineering Design Workshop

LECTURE 7: STUDENT REQUESTED TOPICS

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

Text Input and Conditionals

CS 111X - Fall Test 1

cs1114 REVIEW of details test closed laptop period

CS1 Lecture 4 Jan. 23, 2019

Senthil Kumaran S

Visualize ComplexCities

Lecture 0. Introduction to Python. Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018

Flow Control: Branches and loops

The Python interpreter

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Python for Earth Scientists

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Lecture 1. Course Overview, Python Basics

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Lecture 3. Functions & Modules

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

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

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Python Programming, bridging course 2011

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

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

Lecture 3. Functions & Modules

An Introduction to Python

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

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

Here n is a variable name. The value of that variable is 176.

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Algorithms and Programming I. Lecture#12 Spring 2015

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

CS1 Lecture 5 Jan. 26, 2018

A. Python Crash Course

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

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Research Computing with Python, Lecture 1

CMSC 201 Fall 2018 Lab 04 While Loops

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

Introduction to Python

Python Tutorial. CSE 3461: Computer Networking

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

Computational Programming with Python

CSC209. Software Tools and Systems Programming.

Introduction to Python

Intro. Scheme Basics. scm> 5 5. scm>

Lecture 1. Types, Expressions, & Variables

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

Transcription:

1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides

2 Course Details When and where: Nvidia Auditorium, 12:50-2:05 Fridays for the first 8 weeks of the quarter Grading: 1 unit, pass/fail Weekly homeworks due each Friday at 12:50 posted on course website: web.stanford.edu/~ermartin/teaching/cme193-winter15/assignments.html Must get at least 70% of homework points to pass Follow the honor code. Discussion with classmates is ok but coding must be individual. Moss will be used. Forums on CourseWork can be used for discussion Office hrs. Huang basement Mon. 9:30-10:30, Wed. 3:15-4:15

3 Homework submission Submit assignments in zipped folder to Coursework Drop Box 3 late days throughout the quarter All assignments will be graded on corn (Stanford FarmShare machines), so make sure your code runs there Submit writeups in pdf format

4 Feedback Course evaluations only help future classes If you want something changed, say so! Talk to me Email Anonymous online survey: https://www.surveymonkey.com/s/nsvjddj

5 Instructor Eileen Martin, PhD student in ICME From Texas (went to UT) Undergrad in math and computational physics Research in seismic imaging and associated computational & mathematical issues

6 Course Overview Getting started with Python Variables and flow control Functions Unit testing Basic data structures (lists, dictionaries, tuples, sets) Working with strings Using data from and writing to files (input/output) Numpy, Scipy, Matplotlib Object-oriented programming Ipython notebooks and visualization tools, Guest Lecture Extras: Cython, exception handling

7 Overview of Python Easy to use object-oriented language Data structures have attributes and methods Typically used as an interpreted language Code is executed step-by-step, lines translated to subroutines Cython (another lecture) gives an option for interpreted or compiled Can be run in interactive mode or with scripts We ll use Python 2 since it s on the corn machines, but it is relatively easy to switch to Python 3

8 Overview Today Python s interactive mode and using scripts Values, types, and variables Keywords, pre-defined operators Modules Flow control

9 Starting Python in interactive mode ssh into corn: ssh X sunetid@corn.stanford.edu Open python in interactive mode: python Type your first command: Hello, world! Get some help with the print function: help() print q Try using the print function to display Hello, world! Quit interactive mode: quit()

10 Create and run a Python script Create and browse to the folder where you want to work, for example: mkdir ~/cme193 mkdir ~/cme193/lecture1 cd ~/cme193/lecture1 Open a new document in your favorite text editor, for example: emacs helloworld.py Put the following line in that file and save it: print( Hello, world! ) Run the script: python helloworld.py

11 Overview Today Python s interactive mode and using scripts Values, types, and variables Keywords, pre-defined operators Modules Flow control

12 Values and types Examples: Value True, False Type 3.14159, -1.4, 2e-4 float bool (boolean) 4, -5, 10000, 0 int (integer) Hello, world! 2+3j, -2e-4+2.5e1j str (string) complex None NoneType indicates absence of a value To check the type of a variable, x, in interactive mode use type(x)

13 First Use of Variables Open up a new script, helloworld2.py Put the following commands in the script and save: a = Hello, world! print(a) print type(a) # print can use keyword or function () syntax a = 12 print(a) print(type(a)) # see how a can easily change types Run the script: python helloworld2.py Note that Python doesn t complain when you suddenly ask a to change types

14 Tips for Using Variables Frequently use variables instead of numbers (easy to modify/understand code) Variables should start with a letter and not be a keyword Choose meaningful variable names, concise & descriptive These codes check if a connected graph can be drawn with no edge crossings in a plane: variable = 4 6 + 4 if variable == 2: print( Planar graph ) face = 4 vert = 4 edge = 6 EulerChar = vert edge + face if EulerChar == 2: print( Planar graph ) f = 4 v = 4 e = 6 ec = v e + f if ec == 2: print( Planar graph )

15 Overview Today Python s interactive mode and using scripts Values, types, and variables Keywords, pre-defined operators Modules Flow control

16 Keywords in Python Some examples that we ll use in the next few weeks: print not or def if, elif, else while for break import from class return More description of keywords: http://www.pythonforbeginners.com/basics/keywords-in-python Testing whether something is a keyword: https://docs.python.org/2/library/keyword.html

17 Statements and Expressions Statements are instructions Python executes var = Hello, world! Expressions are made up of values, operators, and variables (that have assigned values) var + Hello, again! In interactive mode, statements aren t printed out unless they call print, but expressions are echoed When using a script, an expression is not echoed

18 Booleans Expressions: syntax ==!= > >= < <= name equals doesn t equal greater than greater than or equal less than less than or equal example 5 == 5 5!= 5 5 > 4 5 >= 5 5 < 4 5 <= 5 ex. result True False True True False True Basic operators: True and False yields False True or False yields True not True yields False

19 Strings Basic operators that output strings: str + str, str * int, int * str Try accessing subsets of strings: a = Hello, world! print(a[0]) print(a[:3]) print(a[1:3]) print(a[3:])

20 Integers vs. floats Basic operators: + - * / Modulus % Exponential ** If operands of / are integers, Python returns the floor of their quotient by default* If either operand of / is a float, Python returns a float Note the limits of finite precision and max & min values *In Python 3, / always returns the true quotient as a float

21 Overview Today Python s interactive mode and using scripts Values, types, and variables Keywords, pre-defined operators Modules Flow control

22 Modules Python has a lot of extra functionality that must be loaded as needed by importing modules Examples: Numpy, Matplotlib, Scipy For example, if you want to overwrite the default integer division in Python 2 to return the true result, try: >>> from future import division >>> 1/2 0.5 Or you could get more mathematical functionality: >>> import math >>> math.pi 3.141592653589793

23 Overview Today Python s interactive mode and using scripts Values, types, and variables Keywords, pre-defined operators Modules Flow control

24 Flow control These control statements structure a code s logical flow: if, elif, else, for, while, break, continue, pass Each brown control statement determines whether a block of code is executed That block is set apart with an indentation (not spaces). a = 2 statement = (a >= 1) if statement: # If statement is True, execute line below # If statement is False, don t execute it print True statement a -= 1 # No more indention so next line is executed # whether statement is True or False print a

25 If-Elif-Else statements An if-elif-else statement decides whether to execute a block of code one time. These two snippets are logically equivalent: if traffic_light == green : drive() elif traffic_light == yellow : accelerate() else: stop() if traffic_light == green : drive() else: if traffic_light == yellow : accelerate() else: stop() The elif (short for else if) keeps code more compact.

26 For loops A for loop lets us repeat a code block The for loop iterates over some object with data that is organized like a list A common function producing a list of integers is range(n) which yields 0, 1, 2,, n-1 Try this in interactive mode ( means it s waiting for end of code block): # Triangular numbers for i in range(5): print i*(i+1)/2 # outputs 0 1 3 6 10

27 While loops A while loop lets us repeat a code block even when we don t know how many times it needs to be iterated It continues evaluating the code block as long as the statement is true Try this in interactive mode: Beware of infinite loops! # Triangular numbers t = 0 i = 1 while t < 12: print t i += 1 # outputs lots of 0 s # Triangular numbers t = 0 i = 1 while t < 12: print t t += i i += 1 # outputs 0 1 3 6 10 print t # outputs 15

28 Pass pass is nice to use as a placeholder while you re working on code because it does nothing # Checking for prime numbers if n % 2 == 1: pass # implement test for odd numbers later elif n == 2: print n, is prime else: print n, is not prime

29 Break break lets us exit the smallest for or while loop enclosing that line Try this example from Python documentation: # Finding prime numbers for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, equals, x, *, n/x break else: # execute if for loop completed # without finding a factor print n, is prime

30 Continue continue skips the rest of the lines in the smallest enclosing loop and continues with the next iteration # Finding a given letter in a sentence letter_chosen = s sentence = this is a sentence other_chars = 0 for letter in sentence: if letter == letter_chosen: print letter_chosen, found continue other_chars += 1 print There were, other_chars, other characters

31 First assignment Posted on the course website: http://stanford.edu/~ermartin/teaching/cme193-winter15/assignments.html Tips: Online documentation is your friend. Don t hesitate to use it! Stuck? test smaller, simpler statements in interactive mode Build test cases to verify correctness of your code Talk to each other. Use the CourseWork Forums. Come to office hrs. Mon. 9:30-10:30, Wed. 3:15-4:15