introduction to python - louisiana state university2016/09/03  · 3/9/2016 introduction to python...

42
3/9/2016 Introduction to Python Introduction to Python Kathryn Traxler CCT [email protected] 3/9/2016 1

Upload: others

Post on 05-Jul-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

IntroductiontoPython

KathrynTraxlerCCT

[email protected]

3/9/2016 1

Page 2: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

IntroductionPython is a dynamic programming language: executes at runtime many common behaviors that other languages might perform during compilation.

Why would you use python?

Open source code and libraries;

Plenty of useful modules to satisfy varying tasks;

Faster to code in, shorter development time;

Portable across various platforms.

2

Page 3: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Introduction(cont.d)

• WhyyouwouldnotusePython• Sloweratruntime• Modulescanbetaxingonmemory• Moduleobjectscanbeopaqueand• taxingtodiginto

3

Page 4: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Installation

• Downloadfromeither:• http://www.python.org• AnacondaPythonfrom• https://www.continuum.io/downloads

4

Page 5: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

PythononLONIandLSUHPC

• PythonisavailableonQueenbee2andtheLSUHPCmachines.UseSoftEnvaslearnedintheHPCEnvironmenttrainingtoaddPython.

• AnacondaPythonisavailableonQueenbee2,SMIC&Philip

5

Page 6: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

TousepythononHPCMachines

• YoumustloadPython• http://www.hpc.lsu.edu/training/weekly-materials/2016-Spring/HPC_UserEnv_Spring_2016_session_1.pdf

• atcommandlineprompttoseeallmodules:moduleavail

6

Page 7: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

MoretousePython

• tolistallcurrentlyloadedmodulesforuser:modulelist

• toloadamodule:moduleloadpython

7

Page 8: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Displaychangesloadingamodulemakesmoduledisppython

8

Page 9: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Toautomaticallyloadmodulesonlogin• Edityour.modulesfile(VERY,VERYcarefully)• Originalfile

9

Page 10: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Editing.module

10

Page 11: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

RunningPython

• InteractivePython• AwaytousePythonfromthePythoninterpreter’scommandprompt

• Eachlinetypedisinterpretedwhenthecarriagereturn(return)keyispressed

• Outputisimmediatetoscreen

11

Page 12: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

RunningPython

• RunningPythonbyexecutingtextfiles• UsingatexteditorcreateatextfileofPythonstatements

• Savethefileusingtheformat:filename.py• Executeusingthecommand:

• pythonfilename.py

12

Page 13: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

LogintoQB2

13

Page 14: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

InterpretedPython

14

Page 15: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Pythonassignmentstatements

15

Page 16: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

MorePython

• CreateaPythonfile.• Openatexteditor(onQB2orSM2usenanoorvimonWindowsnotepad,MacTextEdit,vim,nano)

16

Page 17: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Executefile1.py

17

Page 18: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Trythese

• z=6,print(z),z=12,print(z)• a=‘Hello’(astringofcharacters-indexedat0)• b=‘Student’• print(a,b),b=‘Bob’,print(a,b)• x=z+7=3• print(x)

18

Page 19: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

PythonProgramming• statements: each statement contains one instruction that your

computer will follow/execute i.e. print(“Test”)

• variables: a data container (memory location) that allows you to save data throughout the execution of the program

• unlike C or Java you just type in a variable name, an assignment operator (‘=‘) and the value to store in the container.

• the python statement example: “miles = 200” is readof as “the variable miles is assigned the value of 200” miles is a numeric value

19

Page 20: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Comments• Usethenumber,poundorhashsign(#)forasinglelinecomment

• Youcanmakemultipleonelinecommentsusingahashsignatthebeginningofeach

• Multiplelinecommentswithtriplequotesatthebeginningofthefirstlineandtheendofthelastline

20

Page 21: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Comments

21

“””thisisamultiplelinecomment.Astringisanarrayindexedatzero(0).z=‘apple’aisinlocation[0]pisinlocation[1],etc.“””

Page 22: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

VariableNames• Rules to follow in creating variable names

• Names should start with underscore or letter

• Must contain only letters, numbers or underscores

• Can be one letter to any length (should indicate what it holds)

• Must not be the same as any commands or reserved keywords

• Are case sensitive

• example: data1 and Data1 and dAta1 are three different variable names!

22

Page 23: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

PythonOperators• Arithmetic:+,-,/,*,//,%,**• Assignment:=,+=,-=,/=,*/• Comparison:<,>,<=,>=,==,!=• Logical:and,or,not• Membership• Identity• Bitwise

23

Page 24: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

PrecedenceofOperators• Exponents• Unary• Multiplication,Division,Modulo,FloorDivision• Addition,Subtraction• Bitwise• Comparison• Assignment• Identity• Membership• Logical

24

Page 25: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

MultipleUsageofOperators• z = x + y adds the numerical contents of x and y and puts the sum into z

• x = “python “

• y = “statements “

• z = x + y;

• print(z) gives:

• python statements

• Remember context

25

Page 26: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

FlowControl• IfStatements• Basedonawhetherornotaconditionistrueexecuteonesegmentofstatementsoranother

• example:• a=2• ifa==2:• print(“TodayisTuesday”)

• LetstryafewifinPython

26

Page 27: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

If-else• age=35• ifage>=35:• print(“Youareoldenoughtorunforpresident.”)• else:• print(“Youarenotoldenoughtorunforpresident.”)

27

Page 28: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

If-else

28

age=35ifage>=35:print(“Youareoldenoughtorunforpresident”)else:print(“Youarenotoldenoughtorunforpresident”)

TryitintheinterpreteroraPythonfile(.py)

Page 29: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Loops

• Loopsareflowcontrolitemsthatallowyoutodothesameactionmultipletimes

• forloopscountagivennumberoftimestheyiterate

• whileloopscontinueuntilaconditionalstatementbecomesfalse

29

Page 30: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

ForLoopsfor x in range(0, 3): print "We're on time %d" % (x)

this loop prints We’re on time 0We’re on time 1We’re on time 2

30

Page 31: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

WhileLoopstemperature = 115 while temperature > 112: # first while loop code print(temperature) temperature = temperature - 1

print('The tea is cool enough.’)

prints out:

115114113The tea is cool enough.

31

Page 32: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Functions

• Tocreateafunctionyouprecedeitbydef• formatis:deffun_name():

32

defsay_hi():print(“Hi!”)

say_hi()

Page 33: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

33

Tryitthencreateasay_hi.pyfilewiththesametextinandexecuteitHint:pythonsay_hi.py

Page 34: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Functionwithparameter

34

def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear " + person + ".") print("Happy Birthday to you!")

happyBirthday('Emily')

Tryitthencreateasay_hi.pyfilewiththesametextinandexecuteitHint:pythonsay_hi.py

Page 35: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Lists• Adatatypedthatholdsanorderedcollectionofitemsofthesameordifferenttypes

• list_name=[item1,item2,item3,item4]• animals=[lions,tigers,bears,hawks,dolphins]• names=[Kathy,Isaac,Katie,Kristie]• Kathyisindexedat0soifIjustwanttoprintit

• print(names[0])

35

Page 36: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Lists• names=[Kathy,Isaac,Katie,Kristie]• names.append(‘Brennen’)• names.extend(‘Bryson’,Clayton’)• print(names)• names.insert(1,’Ashlynn’)• some_names=names[0:2]• sorted_names=sorted(names)

36

Page 37: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Programtoinputdata

37

#Thisprogramsayshelloandasksforanameprint(“HelloWorld”)print(“Whatisyourname?”)Name=input()print(“Itisgoodtomeetyou“+Name)print(“Thelengthofyournameis“)print(len(Name))print(“Whatisyourage?”)age=input()print(“Youwillbe“+str(int(age)+1))+inayear.”)

Page 38: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

Programtodownloadafile

38

import requests

res= requests.get("http://www.gutenberg.org/cache/epub/1112/pg1112.txt") type(res) res.status_code == requests.codes.ok len(res.text) print(res.text[:250])

Page 39: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

IntroductiontoPython3/9/2016

WithErrorchecking

39

import requests

res= requests.get("http://www.gutenberg.org/cache/epub/1/pg1112.txt") try: res.raise_for_status() except Exception as exc: print("There was a problem: %s " % (exc)) type(res) len(res.text) print(res.text[:250])

Page 40: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

PythonpackagesforHPC

• SciPy-systemofopen-sourcesoftwareformathematics,science,andengineering.Inparticular,thesearesomeofthecorepackages:Python,NumPy,SciPylibrary,pandas,Matplotlib

• http://www.scipy.org• Possibleotherpackagesdependingonyourdiscipline

40

Page 41: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Python

• https://sites.google.com/site/allendowney/• ThinkPythonanexcellentfreebookonlearningPython.

• AutomatetheBoringStuffwithPython:PracticalprogrammingforthebeginnerbyAlSweigart

41

Page 42: Introduction to Python - Louisiana State University2016/09/03  · 3/9/2016 Introduction to Python Introduction (cont.d) • Why you would not use Python • Slower at runtime •

3/9/2016 IntroductiontoPython

Requests

• http://docs.python-requests.org/en/latest/user/install/#install

• RequestsisanApache2LicensedHTTPlibrarywritteninPythonforhumanbeings

42