phy224 practical physics i pth r ipython review lecture 1

51
PHY224 Practical Physics I Python Review Lecture 1 Sept. 16-17, 2013 Summary Python objects Lists and arrays Input (raw_input) and output Control Structures: iterations References M H. Goldwasser, D. Letscher: Object-oriented programming in Python, Pearson 2008 G. Daniell and J. Flynn: School of Physics and Astronomy, University of Southampton (Computing Module for PHYS2022) - used by permission Eric Jones: Introduction to Scientific Computing with Python: Enthought SciPy 2007 Conference, CalTech. Scipy: http://www.scipy.org/

Upload: others

Post on 12-Sep-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHY224 Practical Physics I Pth R iPython Review Lecture 1

PHY224 Practical Physics I Python Review

Lecture 1 Sept. 16-17, 2013

Summary Python objects Lists and arrays

Input (raw_input) and output Control Structures: iterations

References M H. Goldwasser, D. Letscher: Object-oriented programming in Python, Pearson 2008 G. Daniell and J. Flynn: School of Physics and Astronomy, University of Southampton (Computing Module for PHYS2022) - used by permission

Eric Jones: Introduction to Scientific Computing with Python: Enthought SciPy 2007 Conference, CalTech. Scipy: http://www.scipy.org/

Page 2: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Some definitions Python is a scripting language Scripts are files containing expressions and program statements.

Scripts control other programs

Python is an interpreted language: Expressions may be evaluated and statements may be executed: - at a Python prompt, or - from a .py file.

Python is a compiled language: -a .py file may be compiled into Python bytecode. Python is an object oriented language

Page 3: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Objects in Python: everything!

Whenever you come across something in Python and you ask: "What is this?" Your first correct answer is: "an object“

Python objects have a value. Python objects are containers of attributes (attributes are also objects !). Methods: objects which are callable.

All Python objects also have a type and an id.

Page 4: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A note about code blocks in Python

• Flow of execution in a Python program is controlled by indention.

Indention must be consistent. Four spaces are recommended. • Indention instead of punctuation makes Python one of the most

readable programming languages.

Page 5: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: numbers

Python Shell vs. IDLE Use Python as a calculator: (1+1+2+3+5)*5 – 24/3 9**2 Insert a comment: the interpreter ignores everything from # to the end of line # this is a comment Integer vs. floating point numbers: try: 7.0/4.0 7/4

Page 6: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: numbers

Integer division: unexpected behavior. How to avoid integer division: -Make use of Python’s future division: in Python 3.0 onwards, the division operator will return a floating point number

At the Python prompt do this: 15/6 from __future__ import division 15/6 If you want to use the from __future__import division feature,

it would normally be included at the beginning of the program

Page 7: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: numbers

- If you mix integer and floating point numbers, they are all converted to floating point: test it: 34+1.0 - You can convert from integer to float and back, but conversion to integers is done by truncating towards zero. Try: float(1) int(2.71828) int(-3.14159) Another way of avoiding the problem of integer division is to ensure that at least one number (numerator or denominator) is of type float: float(15)/6

Page 8: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: assignments, strings and types

You can assign values to variables: x=3 means “assign the value 3 to the variable called x” What is the meaning of: x = x*x Try this and explain how Python evaluated your statements: x = 4 x = x+1 print x

Page 9: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Strings are always enclosed in single or double quotes: a =‘eggs’ print a Concatenating strings: use the + operator b = ‘eggs,’+ ’’ + ’toast and bacon’ print b Duplicate strings: by multiplying them by a number: c =‘eggs,’*4 print c The split() method will separate a string where it finds white space.

A Python Primer: assignments, strings and types

Page 10: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: assignments, strings and types

Type of a variables: attribute used by the encoding scheme You can ask what type a variable is and you can print its value. Do this at the Python prompt: a=1; b=1.0; c=‘1.0’ type(a) type(b) type(c)

Page 11: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A Python Primer: complex numbers

Python supports complex numbers, written as 3+5j Examples: do this at the Python Shell: d=3+5j type(d) d.real # real part d.imag # imaginary part abs(d) # absolute value e=1+1j print d*e # multiplying two complex numbers # this was an output statement

Page 12: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The object-oriented paradigm

We design classes to take advantage of similarities in the way we represent and interact with objects. Objects drawn from the same class support a common set of methods. A method that changes the state of an object from a class is called mutator.

Page 13: PHY224 Practical Physics I Pth R iPython Review Lecture 1

About classes

Classes are templates for creating your own custom objects. Think of a class as a blueprint. You can create lots of objects from that blueprint - known technically as instances. All instances will share the same properties class TheClass: This is the class definition header pass This is the class body •This is the simplest possible class definition •The first line is the class definition header

•All the following indented lines are the class body.

Page 14: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Example. At the Python shell, try:

class Duck: color = 'brown' wings = 2 duck1 = Duck() duck1.color duck1.wings

All members of the Duck class will share the same class attributes and their values.

Class body consists of attributes

Page 15: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The list sequence class

How to create a list a: The assignment statement creates an empty list(): a = list()

a is called identifier (it is an object)

Lists are mutable sequences. You can: - add, - remove, - replace elements from a list.

Page 16: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Which objects can be elements in lists?

Numeric types: int - 32 bit signed integers: 5, -273, 29979325, etc. float - 64 bit IEEE-754 floating point numbers: 3.14159, 0.125, -0.324 long - infinite precision signed integers complex - 128 bit complex numbers: 3+4j

Strings: Character strings, literals syntax: put it under quote signs (simple or double): ‘purple’ or “purple”

Tuples: Immutable list-type sequences syntax: use round brackets. Example: skyBlue = (136, 207, 236)

Page 17: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Constructing a list

Lists are enclosed by square brackets. String elements are put under quotation marks. At the Python shell, do this: a = list()

a = [42, 23, 'OK'] # This is list a, predefined as: a = list()

a[1] # Indexing starts at zero a[-1] # Explain this!

a[1:] # returns a slice of the original list

len(a) # returns the length of list a (how many elements)

Page 18: PHY224 Practical Physics I Pth R iPython Review Lecture 1

General object-oriented syntax:

object.method(parameters)

Page 19: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The append method: a.append(‘apple’)

object method parameter Quotation marks on parameter denote a string. Try: a.append(apple)

What happens?

The list class

Page 20: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Try: a[1]

a[1] = 2**31

What happened to parameter [1] from your list a?

The list class: indexing, replacing an element

How many elements are in list a? Use the len(a) command:

len(a)

Page 21: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The remove method: a.remove(‘OK’)

The extend method adds the content of another list (otherlist)at the end of the current list: a.extend(otherlist)

‘otherlist’ is another list that had to be pre-defined

The list class

Page 22: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Independent work 1: a) Add the following objects to list a: 2.0, 3+4j, (42, 23, 'OK'), [1,2,3] Check the type of each object; use: type(object)

b) Remove the second item from list a c) Construct another list b of your choice and extend list a

by list b.

The list class

Page 23: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The range() function

In scientific calculations we often want to loop over a list of numbers, indices, etc. There is a function in Python called range(n) which will output a list of n integers from 0 to (n -1). Try the following examples, using the Python shell: range(10) range(1,11) range(5,20,2) Do you understand how the function range( ) worked in each case?

Page 24: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Arrays and the use of Numpy

Numpy http://numpy.scipy.org/ is a Python module which uses high performance linear algebra libraries to perform vector and matrix manipulation. Numpy uses the array data structure.

An array is the typical experimental data format to be used in a Python program.

The syntax for creating an array is: array(argument) # argument is usually a list Try this at the Python shell: from numpy import * a = array([0,12,6,8,23,2]) #the argument is a list type (a) #this will give you the type of object a

Page 25: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Arrays and the use of Numpy Numpy provides the command arange(), in analogy with range(): Try this with the Python shell: b = arange(5) b c = arange(0.1, 1.0, 0.2) c b+c b*c print b*c sin(b) Explain how arange() and the algebraic manipulation of arrays worked

Page 26: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Arrays and the use of Numpy

The following functions create arrays of zeros or ones. Run them and try to understand the output in terms of input arguments: zeros(7, int)

ones(5, int)

Page 27: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Numeric types

int - 32 bit signed integers, float - 64 bit IEEE-754 floating point numbers, long - infinite precision signed integers, complex - 128 bit complex numbers, Numeric data type bool - boolean values True or False. Numeric operators: division

At the Python Shell, try: 9/4 9.0/4.0 9%4

The modulo operator ("%") evaluates to the remainder of two integers. This is a very problematic operator.

Page 28: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Numeric operators: try them all!

x + y sum of x and y x – y difference of x and y x * y product of x and y x / y quotient of x and y x // y integral quotient of x and y -x x negated +x x unchanged x ** y x to the power y Trigonometric and logarithmic functions are included in the math module. There are many advanced math packages available (FFT, linear algebra, etc.).

Page 29: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Augmented assignments: try them!

x += y same as x = x + y x -= y same as x = x - y x *= y same as x = x * y x /= y same as x = x / y x //= y same as x = x // y x **= y same as x = x ** y

Page 30: PHY224 Practical Physics I Pth R iPython Review Lecture 1

A word about True and False

The Boolean or logical data type has one of two values: True or False, intended to represent the truth values of logic. Truth Value:

That which is not False is True Truth Value Equivalence: That which is not equivalent to False is equivalent to True

Literals True and False are instances of the bool class in Python

Basic logical operators are: not, and, or, ==, !=

Page 31: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Logical operators

At the Python Shell, thy the following:

True and True

True and False

True or False

not True

True and not False

Page 32: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Numeric operators: comparison

< strictly less than <= less than or equal > strictly greater than >= greater than or equal == equal value (equivalency) != not equal

All comparison operations result in True or False Boolean values. Try them all, with numerical values:

Page 33: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Input and Output

Computer programs involve interaction with the user, called input and output. When working in an interactive session, there is no distinction between programmer and the user. The output can write data to files, can send plots to printer or prints things on the screen. The input() function is used to gather input from the user.

Page 34: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Input and Output Example : Open VIDLE (Python interactive interpreter) using the

desktop shortcut. Try this: a=input (“Please give a number: “)

b=input (“And another: “)

print “The sum of these numbers is: “, a+b

Page 35: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The print command is the simplest form for generating output. It is called standard output. This command accepts several arguments, separated by commas. It prints the arguments separated by spaces.

Input and Output

Page 36: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Input and Output

input () can read only numbers (integers and floats). If we need to read a string (word or sentence) from the keyboard, then we should use the raw_input () function: Example: Type: age=int(raw_input(‘What is your age? ‘)) print ‘Soon you will be’, age +1 Let’s change the code a little bit: age=int(raw_input(‘What is your age? ‘)) print ‘Soon you will be’ + age +1

Page 37: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Input and Output: What happened?

Our attempt to incorrectly concatenate a string and a number failed because they are different types of objects. String concatenation is the operation of joining two character strings end to end. Note that the error message clearly indicated not only the type of error, but also the file location and the line in the code where the error occurred.

age=int(raw_input(‘What is your age? ‘)) print ‘Soon you will be’ + age +1

Page 38: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Input and Output Independent work 2 1) Modify the previous example, so that it reads and multiplies three numbers.

2) Write a program that asks the user to enter a temperature in Fahrenheit (f) and reports the equivalent temperature in Celsius (c). You may use the formula: for doing the conversion.

)32(95

−= fc

Previous Example a=input (“Please give a number: “) b=input (“And another: “) print “The sum of these numbers is: “, a+b

Page 39: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Iterations

for loops

for loops are used when you want to repeat something a fixed number of times. The for statement ends with a colon (:). The syntax is: for identifier in sequence: body

The block of code that follows the for command line is called the body of the loop.

Page 40: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: for loops

fruits = ['banana', 'apple', 'mango'] for fruit in fruits: print 'Current fruit :', fruit print “Good Bye!”

Iterating by Sequence Index fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print 'Current fruit :', fruits[index] print “Good Bye!”

We used the len() built-in function, which provides the total number of elements in the list, as well as the range() built-in function to give us the actual sequence to iterate over.

Page 41: PHY224 Practical Physics I Pth R iPython Review Lecture 1

1) Use a for loop to iterate over a range to produce a simple table of the first ten positive integers, their squares and cubes.

2) Create a list a with four floating point numbers. Next, create an empty list b=[ ]. Run through the elements of a, using a for loop, successively appending the exponential of each element of a to b. Note: you may need to import the math module first.

Control structures: Iterations Independent work 3

Page 42: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Iterations while loops In a while loop, you keep performing a sequence of instructions (the loop body), always checking beforehand that some condition is true. Typically the condition is true at the beginning of looping but after going around the loop a number of times, the condition becomes false. The interpreter skips the instructions inside the loop and moves on with the program. If the condition is false when you first reach the while loop, the instructions in the body are never executed. The syntax is: while condition: body (statements executed if the condition is true)

Page 43: PHY224 Practical Physics I Pth R iPython Review Lecture 1

count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"

Control structures: while loops

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.

Page 44: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Let’s calculate the factorial of 9 How to build the program? Work in VIDLE You need to run an index (number < 10) Initialize the calculation (write the first value of factorial, index) Run the index from 1 to 9 by writing a while loop. Print index, factorial

Control structures: Iterations: while loops Independent work 4

Run the factorial code. Check it with your TA if something doesn’t work. Save the file on your memory stick (we shall use it later). Do not forget the extension .py

Page 45: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Iterations: while loops

Let’s calculate the factorial of 9: fac = 1 i = 1 while i<10: fac=fac*i print i, fac i=i+1

Page 46: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Let’s have some fun! Try a game written in VPython by Ruth Chabay and Bruce Sherwood from North Carolina State University. You’ll find it by opening the “2nd Yr Lab Files” folder from the Desktop. The file is hanoi.py

Page 47: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Conditionals (if statements)

The if statement allows us to specify one or more instructions that are to be executed ONLY when a certain condition is true. This is a very valuable tool as it allows execution to vary depending upon values that are not known until the program is running. Syntax is: if condition: body (statements executed only if condition is true) If the condition evaluates to True, the body is executed; if the condition evaluates to False, the body is bypassed. The condition can be an arbitrary expression that evaluates to a Boolean.

Page 48: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Conditionals (if statements)

Let’s work on the following comparison test using a conditional statement Example for x in range(20): if x%9 == 0: print x, ‘is divisible by 9’ elif x%3 == 0: print x, ‘is divisible by 3’ Predict the output that results when the code is executed. What the elif command did?

Page 49: PHY224 Practical Physics I Pth R iPython Review Lecture 1

The fascinating π First identified as a constant by builders of the Great Pyramids in Egypt (2550-2500 B.C.): 1760 cubits around the base; height of 280 cubits yield a ratio 1760/280 = 6.2857=2x3.1428 That the ratio of the circumference to the diameter of a circle is the same for all circles, and that it is slightly more than 3, was known to ancient Egyptian, Babylonian, Indian and Greek geometers. Archimedes (287–212 BC) was the first to estimate π rigorously. The series we shall use today was first found around 1400 by the Hindu mathematician and astronomer Madhava of Sangamagrama who evaluated π with 13 decimal places.

Page 50: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Independent Project

We shall write a program to approximate the mathematical constant π using the following approximation up to n terms, for some n: Start by writing down the general expression of a series term. Run the program for n = 20, 100 and 1000. What do you notice? Save your function under a different name than pi which is a dedicated math module.

+−+−= ............

71

51

31

114π

Page 51: PHY224 Practical Physics I Pth R iPython Review Lecture 1

Control structures: Examples Here is how the Python program to calculate π looks like: pi=0.0 # intial value for k in range(0,n): # n is your number term = (-1)**k * 1.0/(2*k+1) # a code variation would be: # term = 1.0/(2*k+1) # if k%2 = =1: # term = - term pi+ = 4*term #pi+= means each term is #added to the previous one print pi