Python By: Ben Blake, Andrew Dzambo, Paul Flanagan.

18
Python Python By: Ben Blake, Andrew Dzambo, Paul By: Ben Blake, Andrew Dzambo, Paul Flanagan Flanagan

Transcript of Python By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Page 1: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

PythonPython

By: Ben Blake, Andrew Dzambo, Paul By: Ben Blake, Andrew Dzambo, Paul FlanaganFlanagan

Page 2: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

SpacingSpacing CommentsComments HeaderHeader Consistency with variables – keep it simpleConsistency with variables – keep it simple Set all variables equal to zero initiallySet all variables equal to zero initially Notes on changes to code – version controlNotes on changes to code – version control Good formatting example: Good formatting example:

http://www.personal.psu.edu/amd5554/resources/documented_code.pdf

General Programming General Programming TipsTips

Page 3: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Declaring variables – don't need to create variable Declaring variables – don't need to create variable initiallyinitially

Indenting in loops – no end statementIndenting in loops – no end statement Capitalization matters – Temp, temp, tEmp, TEMP are Capitalization matters – Temp, temp, tEmp, TEMP are

all different variablesall different variables

Python BasicsPython Basics

Page 4: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Mathematical expressions are the sameMathematical expressions are the same + Addition+ Addition - Subtraction- Subtraction * Multiplication* Multiplication / Division/ Division ** Exponentiation** Exponentiation 9.8E-8 = 9.8 * (10 ** (-8))9.8E-8 = 9.8 * (10 ** (-8))

Numerical ArithmeticNumerical Arithmetic

Page 5: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Built-in functionsBuilt-in functions float, int, max, min, absfloat, int, max, min, abs

Imported functionsImported functions sin, cos, tan, asin, acos, atan, log (natural log), log10 (base sin, cos, tan, asin, acos, atan, log (natural log), log10 (base

10 log), exp, sqrt, pi, e10 log), exp, sqrt, pi, e Trigonometric functions work exclusively in radiansTrigonometric functions work exclusively in radians

k = m.cos(a * m.pi / 180.0)k = m.cos(a * m.pi / 180.0) degrad = m.pi / 180.0degrad = m.pi / 180.0 k = m.cos(a * degrad)k = m.cos(a * degrad)

Math FunctionsMath Functions

Page 6: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Some commands/functions need to be imported in order Some commands/functions need to be imported in order to be usedto be used

Some libraries that can be imported: math, numpy, Some libraries that can be imported: math, numpy, pylabpylab

Different ways to importDifferent ways to import from math import cos, sin, acos, pifrom math import cos, sin, acos, pi import mathimport math

k = math.cos(a * m.pi / 180.0)k = math.cos(a * m.pi / 180.0) import math as mimport math as m

k = m.cos(a * m.pi / 180.0)k = m.cos(a * m.pi / 180.0)

ImportingImporting

Page 7: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Linecount += 1Linecount += 1 ==> ==> linecount = linecount + 1 linecount = linecount + 1 Average /= linecount ==>Average /= linecount ==> average = average / average = average /

linecountlinecount Balance -= payment ==>Balance -= payment ==> balance = balance – balance = balance –

paymentpayment Population *= growth ==>Population *= growth ==> population = population * population = population *

growth growth

Shortcut OperatorsShortcut Operators

Page 8: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Need to distinguish between read-only (input) files and Need to distinguish between read-only (input) files and writeable (output) fileswriteable (output) files

““r” = read-only, “w” = writeabler” = read-only, “w” = writeable infile = open(“weather.csv”, “r”)infile = open(“weather.csv”, “r”) outfile = open(“pressure.txt”, “w”)outfile = open(“pressure.txt”, “w”)

Input/OutputInput/Output

Page 9: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Reading input filesReading input files vap_list = infile.readlines()vap_list = infile.readlines() for vaporpressure in vap_list:for vaporpressure in vap_list:

Print statementsPrint statements Print >> outfile, x, y, vaporpressurePrint >> outfile, x, y, vaporpressure If a number immediately follows the %, it is the width (in If a number immediately follows the %, it is the width (in

spaces) of the field in which the object will be writtenspaces) of the field in which the object will be written Print ‘%4f’ % x, ‘%4f’ % y Print ‘%4f’ % x, ‘%4f’ % y this will print x and y as floating this will print x and y as floating

point numbers over 4 spaces point numbers over 4 spaces

Using Input/Output FilesUsing Input/Output Files

Page 10: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Types: for, if, while loopsTypes: for, if, while loops Indenting denotes code is in loopIndenting denotes code is in loop To close loop, unindent the next lineTo close loop, unindent the next line Example of a simple loop - counts # of x's in xlistExample of a simple loop - counts # of x's in xlist

for x in xlist:for x in xlist:y += 1y += 1

print yprint y

LoopsLoops

Page 11: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Determinant loop – use when you know how long you Determinant loop – use when you know how long you want the program to runwant the program to run

Similar to the “do loop” in ForTran and C++Similar to the “do loop” in ForTran and C++ Two examples of for loops – can use either an input file Two examples of for loops – can use either an input file

or an arrayor an array

for station in stations:for station in stations:

for k in range(n):for k in range(n):

For LoopsFor Loops

Page 12: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Used to make logical decisionsUsed to make logical decisions Can be imbedded inside for loopsCan be imbedded inside for loops

if logical_expression_1:if logical_expression_1:# do this block when logical_expression_1 is true# do this block when logical_expression_1 is true

elif logical_expression_2:elif logical_expression_2:# do this block when logical_expression_2 is true# do this block when logical_expression_2 is true

else:else:# do this block when neither logical expression above is true # do this block when neither logical expression above is true

If LoopsIf Loops

Page 13: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Comparisons of one variable to another or to a constant Comparisons of one variable to another or to a constant using comparison operatorsusing comparison operators

== equals== equals < less than< less than <= less than or equal to<= less than or equal to != not equals!= not equals > greater than> greater than >= greater than or equal to>= greater than or equal to

Logical Expressions in Logical Expressions in PythonPython

Page 14: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Indeterminant loop – use when duration of loop is Indeterminant loop – use when duration of loop is unknownunknown

Can be imbedded inside for loopsCan be imbedded inside for loops General while loop structureGeneral while loop structure

while logical_expression:while logical_expression:# statements to run as long as logical_expression stays true# statements to run as long as logical_expression stays true

While LoopsWhile Loops

Page 15: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

Can use to terminate a loop or part of a specific loop if a Can use to terminate a loop or part of a specific loop if a statement becomes truestatement becomes true

Example of how break statement is usedExample of how break statement is used

x = 0x = 0

for x in xlist:for x in xlist:if x >= 40:if x >= 40:

x += 1x += 1

breakbreak

else:else:x += 1x += 1

Break StatementBreak Statement

Page 16: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

• Collection of strings, floating point numbers, or integers Collection of strings, floating point numbers, or integers listed in some orderlisted in some order

• Arrays are special form of list in which all elements are Arrays are special form of list in which all elements are of same data typeof same data type

• Numeric Python module (numpy) is used to work with Numeric Python module (numpy) is used to work with arraysarrays

ListsLists

Page 17: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

• List – create a defined list-type objectList – create a defined list-type object• x = list([4.0, ‘Hypsometric’, 34])x = list([4.0, ‘Hypsometric’, 34])

• Range – returns list of integers in Range – returns list of integers in specified range – important in for loopsspecified range – important in for loops• range(4) returns [0, 1, 2, 3]range(4) returns [0, 1, 2, 3]• range (2,4) returns [2, 3]range (2,4) returns [2, 3]

• Len – counts how many numbers are in Len – counts how many numbers are in a lista list• len(range(2,4)) produces a value of 2len(range(2,4)) produces a value of 2

• Sum – adds up the numbers in a listSum – adds up the numbers in a list

List OperatorsList Operators

Page 18: Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.

• Input files consists of strings which can Input files consists of strings which can be split into component strings and then be split into component strings and then converted into numbersconverted into numbers

• Split method is used to break strings Split method is used to break strings into more useful componentsinto more useful components

• Default separator is a blank space, but Default separator is a blank space, but separators can be anything, such separators can be anything, such as , : ; / -as , : ; / -

• Line splitting most useful when done Line splitting most useful when done inside a loop inside a loop • Line = “32, 32.4, 36.8, Freezing Points”Line = “32, 32.4, 36.8, Freezing Points”• q = float(line.split(“,”)[2]) = 36.8q = float(line.split(“,”)[2]) = 36.8

Line SplittingLine Splitting