id
int64
0
25.6k
text
stringlengths
0
4.59k
9,800
youif youknow how to use computer and the web have never programmed before but have strong desire to learn how are willing to type lot to make the information stick (no copy paste allowedare an experienced programmer and want to play with new language
9,801
web development graphics financial science
9,802
electronic design automation software development education business software government
9,803
created by guido van rossum born jan (netherlandscurrently works at google (since actively maintained by worldwide users (including van rossum
9,804
"hobbyprogramming project interpreter for new scripting language descendant of abc that would appeal to unix/ hackers needed name that was shortuniqueand slightly mysterious so was named python as working title code first published (version the python software foundation was formed more history
9,805
prosuitable for everyday taskstherefore minimizing the amount of time programmer spends on project conoften less efficient than languages such as javacand ++thereforenot good when creating new operating system
9,806
remarkably powerfuldynamicobject-orientedinterpretedhigh-level programming language that is used in wide variety of application domains named after the comedy troupemonty python
9,807
"python is the status quopython is the shiny new thing ' the tried and true blue # is the last major release for xwith statement of extended support is the intended future of the "cleaned uplanguagewith less regard for backwards compatibility lot of third party software doesn' work on yet "well written code will actual...
9,808
run web sites and morebuild test suites for or java code write gui interfaces process large xml data sets control numbercrunching code on supercomputers make commercial application scriptable by embedding the python interpreter inside it image from "head first pythonbook by paul berry
9,809
www python org follow the easy online installation instructionsacademicautomatically with certain operating systems ( mac and linuxinstalled alongside software applications that incorporate its scripting functionality ( esri arcgis
9,810
all major operating systems windows linux/unix os/ mac amiga and operating systems on mobile devices
9,811
simplicity and ease of understanding programs look neat and clean has few unnecessary symbols straightforward english names instead of the cryptic syntax common in other languages note'import antigravityonly works in version xprint statement is from
9,812
programmability wide range of readymade libraries that can be (freely!used in your own programsi "batteries includedsupportsbut doesn' forceobject-oriented programming (oopintegration with other languages ( javac"python footgraphic by david day
9,813
free doesn' cost freely usable and distributable even for commercial use open source code sizable community of developers with online support groups www pycon org www scipy org
9,814
scripting 'gluingtogether commands for other software applications programming text processingweb site developmentemailscientific computing www devsource com/ / /languages/more-than-five-things-you-didnt-know-you-could-do-with-pythonpython does com python does net python does java better than java python is high-perfor...
9,815
official python tutorial online resourcesincluding "freee-books through uofa' libraries (listed at the endhands-on now
9,816
command line the interpreter ide (idle)integrated development environment interactive window script window other software (not used in this workshop
9,817
we're going to skip the command lineand go on to
9,818
click the start button programs arcgis python idle (python guiwe are using the arcgis default installation of the integrated development environment because it is readily available for gis development many other ides (discussed laterare available for your usebut this one makes interacting with arcgis easy breezy
9,819
9,820
create new editing window open an existing file open list of recent files save current window to the associated file (unsaved windows have before and after the window titlesave current window to different file without changing the associated file close all windowsquit (asks to save if unsavedopen an existing module (se...
9,821
undo last change to current window ( maximum of changes may be undonecopy selection into system wide clipboardthen delete the selection insert system wide clipboard into window ask for line number and show that line redo last undone change to current window copy selection into system wide clipboard select the entire co...
9,822
search for the string in the selection open search dialog box for searching files open small window with function param hints highlight the surrounding parenthesis repeat last search open scroll window allowing selection keywords and attributes expand the word you have typed to match another word in the same bufferrepe...
9,823
scroll the shell window to the last restart restart the interpreter with fresh environment look around the insert point for filename and linenumberopen the fileand show the line run commands in the shell under the debugger show the stack traceback of the last exception open stack viewer on traceback toggles the window ...
9,824
open configuration dialog fontsindentationkeybindingsand color themes may be altered startup preferences may be setand additional help sources can be specified on macos this menu is not presentuse menu 'idle preferences instead versioncopyrightlicensecredits display summary file on all menu items access local python do...
9,825
click help idle help close when finished reading click options configure idle examine each tab and modify as needed change font (fonts/tabs tabe add custom web/file help link/path (general tab and click add button
9,826
program set of instructions or recipe that tells the computer what you want it to do
9,827
python program is divided into lines each line physically ends before newline lines that are blank (contain only spacestabsformfeeds and possibly commentare ignored breaking up statements on separate lines will break your programthesunshines true itsraining false
9,828
indentation and whitespace required leading whitespace ( spacesat the beginning of logical line is used to compute the indentation level of the linewhich in turn is used to determine the grouping of statements trailing whitespace is ignored all lines you want grouped together must be indented identically{(no begin/end ...
9,829
comments helps explain what the code is doing ignored when executed two ways to indicate commentstype comment here ""type comment here ""command prompts (interactive mode only
9,830
type the following in the interactive windowimport this help(import do not type the topics numbers strings note the lower case type quit or press ctrl- to exit the help system
9,831
type the following in the interactive windowhelp(keywordsnow retype with quotes around 'keywordshelp('print'print 'what is blue moon?abluemoon 'second to last full moon in four-moon seasonprint abluemoon for once in abluemoonprint once this is loopingwe'll learn about it later type alt- couple of times (and try alt-
9,832
computer computer programs modules statements expressions modules statements expressions programs difference between statement and an expressionstatement does something (orrathertells the computer to do somethinge print or assignmentexpression is something expressions consist ofliteral values variables operators parent...
9,833
notations for constant values of some built-in types ( the stuff you type directlynumeric plain integerslong integersfloating point numbersand imaginary numbers strings text enclosed in 'single quotesor "double quoteshelp('strings'help('numbers'
9,834
name that represents or refers to value ( the stuff you want stored for various usesdynamic no need to define the type up front created through an assignment statement that gives them values using the '=operator if you don' have an assignment ( name to the left of the '='then python stores it in the default result vari...
9,835
tokens that work with or operate on values includesarithmetic assignment comparison bitwise logical membership identity (notethe smaller-font ones are not included in the next set of slideslook them up in the help!help('operators'
9,836
*/add (noteconcatenation when used with stringssubtract multiply (noterepetition when used with stringsexponential (powercalculation divide modulus return remainder from division floor division return quotient from division
9,837
=!><equal tonot equal to (also greater than less than greater than or equal to less than or equal to *remember that single '=sign is the assignment operator
9,838
simple assignment operator+add and assignment operator -subtract and assignment operator *multiply and assignment operator /divide and assignment operator (assigns values from right side operands to left side operand(add right operand to the left operand and assign the result to left operand(subtract right operand from...
9,839
reserved word or identifier that has particular meaning to the programming language they must be spelled exactly as typed hereand elif if print as else import raise assert except in return break exec is try class finally lambda while continue for not with def from or yield del global pass help('keywords'
9,840
type the following in the interactive window case is importanta is not the same as bc then type 'stuff_ do not type the
9,841
type the following in the interactive windowcalculator expressions commenting and docstrings print statements sequences samples demonstrated here are provided in the pdf document idle is well-suited for testing out bits of code to see how it works
9,842
from the menu of the interactive (python shellwindowclick file new window new blank window ( file editoris used to type our programs in
9,843
open pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window open or wake up the python shell window run syntax check on the module execute the current file in the __main__ namespace shell and debug menus are not available in the script window...
9,844
shift selected lines right spaces shift selected lines left spaces insert #in front of selected lines remove leading or #from selected lines turn *alltabs into the right number of spaces open dialog to change indent width reformat the current blank-line-separated paragraph format menu is not available in the interactiv...
9,845
text file containing the statements that comprise python program reusablereusablereusable once createdthe script can be executed over and over without having to retype it each time any file editor (that saves as plain asciican be usedbut name the file with py extension but don' forget about interactive mode completelyi...
9,846
style guide for python code spaces per indentation (no tabs evermaximum line length of characters always import modulesafter initial comments or docstrings import them separately don' scatter them throughout your code namemodules with lowercase classes with capwords functions with lower_case_with_underscores constants ...
9,847
type some of the previous statements you`ve already tried in to the script window samples demonstrated here are provided in the pdf document save with meaningful name and py extension to your working directory optionallyclick run check module click run run module (or the key
9,848
control the behaviour of script by testing conditions and looping through values flow control statements (similar to other programming languagesspecify how the program is executed if while for also try and with (but not covered in this workshopkeyword statement (typicallyfollowed by colon and an indented block
9,849
the if statement is used for conditional executiona testing values and making decisions detailslets you perform an action (another statement or moreif given condition is trueif the condition is falsethen the block is not executed rememberwhen testing equality use =(and not =extending the testingelif allows you to check...
9,850
generic syntaxif expressionstatement(selif expressionstatement(selsestatement(smost basic minimum coding can be abbreviated as conditional statementx true_value if condition else false_value
9,851
the while statement is used for repeated execution as long as an expression is true detailskeeps executing (another statement or moreuntil the condition becomes false rememberto code finite loopi prevent the possibility that this condition never resolves to false value (unless an infinite loop is actually desiredgeneri...
9,852
the for statement is used to iterate over the elements of sequence (such as stringtuple or listor other iterable object detailscauses section of program to be repeated certain number of times by iterating ( counting eachrememberthis can loop through list-like objects and/or numeric ranges generic syntaxfor iterating_va...
9,853
type the following in the script windowif if else while for samples demonstrated here are provided in the pdf document
9,854
series of statements which returns some value to caller (it can also be passed zero or more arguments for its use/executionobjects that can be used by all python code without the need of an import statement dir(__builtins__
9,855
some of the tools that are always available to useabs(xbin(xcmp(xycomplex([real[imag]]dict([arg]dir([object]divmod(abenumerate(sequence[start= ]eval(expression[globals[locals]]file(filename[mode[bufsize]]float([ ]format(value[format_spec]globals(help([object]hex(xid(objectinput([prompt]int([ [base]]isinstance(objectcla...
9,856
more selected toolsmap(functioniterablemax(iterable[args ][key]min(iterable[args ][key]oct(xopen(filename[mode[bufsize]]pow(xy[ ]range([start]stop[step]raw_input([prompt]reversed(seqround( [ ]set([iterable]sorted(iterable[cmp[key[reverse]]]str([object]sum(iterable[start]tuple([iterable]type(objecttype(namebasesdictvars...
9,857
block of organizedreusable code that is used to perform single related actionthat you create similar to proceduressubroutinesand functions in other programming languagesbut may or may not return value generic syntaxrequired keyworddef defines the function def functionnameparameters )"""function_docstring""function_suit...
9,858
basicallysubprograms that define thingse functionsclassesvariables built-in (as opposed to user-definedmodules are also called standard libraries
9,859
different ways to grab these extra tools import requires module name as prefix to tools import random randvalue random random( from import reduces typing for commonly used tools from random import random randvalue random( from import (this way is not advised because it causes clutter
9,860
the python package index is one-stop 'shoppingfor all registered module packagessearchablecertainlysir what would you likenow thensome cheese pleasemy good man
9,861
as with all things and in pythonit' easier to ask forgiveness than permission try and perform an operationif all goes wellgreatif notask for forgiveness this is typically done with try/except the faq is worthwhile read
9,862
start new file for each of the scripts below make notes (comments in the code will do!if you think the instructor says something important during this hands-on demonstrations of practical python programming especially note the built-in modules highlighted from the standard library
9,863
set up generic_code py (name it what you wantuse comments/docstring at the top to indicate the filenamedate( )your nameoptional contact infoand details about what the script requires and does type out the basic structure of your common coding needsincluding import open the file when you're ready to start new programsim...
9,864
don' work too hard let python do the work for you by using the stuff built in to its standard library don' write loop when comprehension will do built-in syntax for transforming one data structure (listsdictionariesinto another version of itself without resorting to iteration learn as you gonot all at onceand learn con...
9,865
python scripting for arcgis software carpentrymit intro to computer science programmingread the related article on the importance of programming skills
9,866
(online links to softwaredocumentationfree bookstutorialssample codeand articles
9,867
(subscription is accessible through an on-campus computer with uofa ip address or ccid loginpro pythonmarty alchin python programming fundamentalskent lee primer on scientific programming with pythonhans petter langtangen python scripting for computational sciencehans petter langtangen beginning python visualizationcra...
9,868
files reading writing writing our own functions tuples modules system modules external modules dictionaries formatted text
9,869
on-line games web services applications science instrument control embedded systems en wikipedia org/wiki/list_of_python_software so who uses python and what forpython is used for everythingfor example"massively multiplayer online role-playing gameslike eve onlinescience fiction' answer to world of warcraftweb applicat...
9,870
compiled interpreted explicitly compiled to machine code explicitly compiled to byte code implicitly compiled to byte code purely interpreted cc++fortran javacpython shellperl what sort of language is pythonthe naive view of computer languages is that they come as either compiled languages or interpreted languages at t...
9,871
we are going to use python from the command line either directly or indirectly sofirst need unix command line will get that from the gui by clicking on the terminal icon in the desktop application bar
9,872
unix prompt unix command introductory blurb python python (defaultmay [gcc on linux : : python version python prompt nowthe unix interpreter prompts you to give it unix command with short bit of text that ends with dollar in the slides this will be represented simply as dollar this is unix prompt asking for unix comman...
9,873
exit(quit(any one of these ctrl there are various ways to quit interactive python there are two commands which are equivalent for our purposesquit(and exit()but the simplest is the key sequence [ctrl]+[
9,874
python prompt python command print('helloworld!'helloworldoutput python prompt there is tradition that the first program you ever run in any language generates the output "helloworld! see no reason to buck tradition welcome to your first python commandwe are going to output "helloworld!we type this command at the pytho...
9,875
python "functionround brackets -"parenthesesprint('helloworld!'function' "argumentprint print "case sensitive this is our first python "functiona function takes some inputdoes something with it and (optionallyreturns value the nomenclature derives from the mathematics of functionsbut we don' need to fixate on the mathe...
9,876
quotation marks 'helloworld!the body of the text the quotes are not part of the text itself the text itself is presented within single quotation marks (we will discuss the choice of quotation marks later the body of the text comes within the quotes the quotes are not part of the textthey merely indicate to the python i...
9,877
print command 'printtext so what do the quotes "do"if there are no quotes then python will try to interpret the letters as something it should know about with the quotes python simply interprets it as literal text for examplewithout quotes the string of characters - - - - are commandwith quotes they are the text to be ...
9,878
file in home directory print('helloworld!'run from unix prompt hello py unix prompt unix command to run python python hello py python script helloworldpython script' output unix prompt so we understand the "helloworldcommand and how to run it from an interactive python but serious python programs can' be typed in livet...
9,879
to edit scripts we will need plain text editor for the purposes of this course we will use an editor called "gedityou are welcome to use any text editor you are comfortable with ( vi or emacsif script already exists then we can launch the file browser and simply double-click on its icon this will launch the appropriate...
9,880
if the file does not already exist then click on the text editor icon in the dock to launch it with no content just as with the terminal you can get this from the dock on the left hand side of the screen
9,881
interactive python python scripts print(command simple python text
9,882
print "goodbyecruel world!from interactive python edit exercise py to print the same text run the modified exercise py script please ask if you have questions minutes during this course there will be some "lightning exercisesthese are very quick exercises just to check that you have understood what' been covered in the...
9,883
full "unicodesupport print('elda`aor!!'www unicode org/chartshello py now let' look at slightly different script just to see what python can do python has excellent support for fully international text (so did python but it was concealed python supports what is called the "unicodestandarda standard designed to allow fo...
9,884
altgr shift character selector "latin small letter with breve\ linux don' want to get too distracted by international charactersbut ought to mention that the hardest part of using them in python is typically getting them into python in the first place there are three "easyways there are key combinations that generate s...
9,885
type('helloworld!' string of characters classstring length letters str we will quickly look at how python stores textbecause it will give us an introduction to how python stores everything every object in python has "type(also known as "class"the type for text is called "strthis is short for "string of charactersand is...
9,886
str '\ 'gord(' ' chr( 'gg in these slides ' going to represent the stored text as characters because that' easier to read in realityall computers can store are numbers every character has number associated with it you can get the number corresponding to any character by using the ord(function and you can get the charac...
9,887
"concatenationprint('hello'world!'hello py 'hello'world!'helloworld! now let' do something with strings if we 'addtwo strings together python joins them together to form longer string python actually permits you to omit the "+don' do this
9,888
'hello,'world!'world!only simple concatenation 'world!no spaces added automatically 'helloworld!'hello,'helloworld!'hello,'hello,world! this joining together is very simple if you want words split by space you have to put the space in
9,889
'helloworld!single quotes 'helloworld!single quotes "helloworld!double quotes 'helloworld!single quotes it doesn' matter whether we write our strings with single or double quotes (so long as they match at the two endspython simply notes that we are defining string
9,890
'helloworld!"helloworld!single or double quotes on input create same string object 'helloworld!str single quotes on output internally there are no quotesjust record that the object is text when python comes to display the string and declares "this is textitself it uses single quotes
9,891
print('he said "helloto her 'he said "helloto her print("he said 'helloto her "he said 'helloto her having two sorts of quotes can be useful in certain circumstances if you want the text itself to include quotes of one type you can define it surrounded by the other type
9,892
print('he said 'helloto her 'file ""line print('he said 'helloto her 'syntaxerrorinvalid syntax you must mix the quotes like that if you do not then python will be unable to make sense of the command we will look at python' error messages in more detail later
9,893
print('he said \'hello\to her 'he said 'helloto her str \just an ordinary character \"escapingh there is more general solution to the "quotes within quotesproblem preceding each quote within the body of the text signals to python that this is just an ordinary quote character and should not be treated specially note tha...
9,894
helloworldwhat we want print('helloworld'print('hellofile ""line print('hellosyntaxerroreol while scanning string literal try this "eol"end of line we will follow the theme of "inserting awkward characters into stringsby looking at line breaks we cannot insert line break by hitting the |key this signals to python that ...
9,895
print('hello,\nworld!'helloworld\ str treated as new line converted into single character len('hello,\nworld!' len(functiongives the length of the object againthe backslash character comes to our rescue if we create string with the sequence "\nthen python interprets this as the single character python can tell us exact...
9,896
special ordinary ordinary special \\\ \ we have used backslash againthis time for slightly different result backslash before character with special significancesuch as the quote charactermakes the character "ordinaryused before an ordinary charactersuch as " "it produces something "specialonly few ordinary characters h...
9,897
'squire trelawneydr liveseyand the\ rest of these gentlemen having asked me\ to write down the whole particulars\nabou treasure islandfrom the\nbeginning to the endkeeping nothing\nback but the earings of the island,\nand that only bec ause there is still\ntreasure not yet lif tedi take up my\npen in the year of gra ce...
9,898
'''squire trelawneydr liveseyand the rest of these gentlemen having asked me to write down the whole particulars about treasure islandfrom the beginning to the endkeeping nothing back but the bearings of the islandand that only because there is still treasure not yet liftedi take up my pen in the year of grace __ and g...
9,899
'''helloworld''python asking for more of the same command the triple quote lets us see another python feature if we type long string raw then after we hit we see python' "secondary promptthe three dots indicate that python is expecting more input before it will process what it has in hand