introduction to python - louisiana state university2016/09/03 · 3/9/2016 introduction to python...
TRANSCRIPT
3/9/2016 IntroductiontoPython
IntroductiontoPython
KathrynTraxlerCCT
3/9/2016 1
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
3/9/2016 IntroductiontoPython
Introduction(cont.d)
• WhyyouwouldnotusePython• Sloweratruntime• Modulescanbetaxingonmemory• Moduleobjectscanbeopaqueand• taxingtodiginto
3
3/9/2016 IntroductiontoPython
Installation
• Downloadfromeither:• http://www.python.org• AnacondaPythonfrom• https://www.continuum.io/downloads
4
3/9/2016 IntroductiontoPython
PythononLONIandLSUHPC
• PythonisavailableonQueenbee2andtheLSUHPCmachines.UseSoftEnvaslearnedintheHPCEnvironmenttrainingtoaddPython.
• AnacondaPythonisavailableonQueenbee2,SMIC&Philip
5
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
3/9/2016 IntroductiontoPython
MoretousePython
• tolistallcurrentlyloadedmodulesforuser:modulelist
• toloadamodule:moduleloadpython
7
IntroductiontoPython3/9/2016
Displaychangesloadingamodulemakesmoduledisppython
8
3/9/2016 IntroductiontoPython
Toautomaticallyloadmodulesonlogin• Edityour.modulesfile(VERY,VERYcarefully)• Originalfile
9
3/9/2016 IntroductiontoPython
Editing.module
10
3/9/2016 IntroductiontoPython
RunningPython
• InteractivePython• AwaytousePythonfromthePythoninterpreter’scommandprompt
• Eachlinetypedisinterpretedwhenthecarriagereturn(return)keyispressed
• Outputisimmediatetoscreen
11
3/9/2016 IntroductiontoPython
RunningPython
• RunningPythonbyexecutingtextfiles• UsingatexteditorcreateatextfileofPythonstatements
• Savethefileusingtheformat:filename.py• Executeusingthecommand:
• pythonfilename.py
12
IntroductiontoPython3/9/2016
LogintoQB2
13
3/9/2016 IntroductiontoPython
InterpretedPython
14
IntroductiontoPython3/9/2016
Pythonassignmentstatements
15
3/9/2016 IntroductiontoPython
MorePython
• CreateaPythonfile.• Openatexteditor(onQB2orSM2usenanoorvimonWindowsnotepad,MacTextEdit,vim,nano)
16
IntroductiontoPython3/9/2016
Executefile1.py
17
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
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
3/9/2016 IntroductiontoPython
Comments• Usethenumber,poundorhashsign(#)forasinglelinecomment
• Youcanmakemultipleonelinecommentsusingahashsignatthebeginningofeach
• Multiplelinecommentswithtriplequotesatthebeginningofthefirstlineandtheendofthelastline
20
IntroductiontoPython3/9/2016
Comments
21
“””thisisamultiplelinecomment.Astringisanarrayindexedatzero(0).z=‘apple’aisinlocation[0]pisinlocation[1],etc.“””
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
3/9/2016 IntroductiontoPython
PythonOperators• Arithmetic:+,-,/,*,//,%,**• Assignment:=,+=,-=,/=,*/• Comparison:<,>,<=,>=,==,!=• Logical:and,or,not• Membership• Identity• Bitwise
23
3/9/2016 IntroductiontoPython
PrecedenceofOperators• Exponents• Unary• Multiplication,Division,Modulo,FloorDivision• Addition,Subtraction• Bitwise• Comparison• Assignment• Identity• Membership• Logical
24
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
3/9/2016 IntroductiontoPython
FlowControl• IfStatements• Basedonawhetherornotaconditionistrueexecuteonesegmentofstatementsoranother
• example:• a=2• ifa==2:• print(“TodayisTuesday”)
• LetstryafewifinPython
26
If-else• age=35• ifage>=35:• print(“Youareoldenoughtorunforpresident.”)• else:• print(“Youarenotoldenoughtorunforpresident.”)
27
IntroductiontoPython3/9/2016
If-else
28
age=35ifage>=35:print(“Youareoldenoughtorunforpresident”)else:print(“Youarenotoldenoughtorunforpresident”)
TryitintheinterpreteroraPythonfile(.py)
3/9/2016 IntroductiontoPython
Loops
• Loopsareflowcontrolitemsthatallowyoutodothesameactionmultipletimes
• forloopscountagivennumberoftimestheyiterate
• whileloopscontinueuntilaconditionalstatementbecomesfalse
29
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
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
3/9/2016 IntroductiontoPython
Functions
• Tocreateafunctionyouprecedeitbydef• formatis:deffun_name():
32
defsay_hi():print(“Hi!”)
say_hi()
33
Tryitthencreateasay_hi.pyfilewiththesametextinandexecuteitHint:pythonsay_hi.py
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
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
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
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.”)
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])
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])
3/9/2016 IntroductiontoPython
PythonpackagesforHPC
• SciPy-systemofopen-sourcesoftwareformathematics,science,andengineering.Inparticular,thesearesomeofthecorepackages:Python,NumPy,SciPylibrary,pandas,Matplotlib
• http://www.scipy.org• Possibleotherpackagesdependingonyourdiscipline
40
3/9/2016 IntroductiontoPython
Python
• https://sites.google.com/site/allendowney/• ThinkPythonanexcellentfreebookonlearningPython.
• AutomatetheBoringStuffwithPython:PracticalprogrammingforthebeginnerbyAlSweigart
41
3/9/2016 IntroductiontoPython
Requests
• http://docs.python-requests.org/en/latest/user/install/#install
• RequestsisanApache2LicensedHTTPlibrarywritteninPythonforhumanbeings
42