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 actually be lot like codehandy tools for compatibilityi' the clean and shiny # |
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-performance python talks to hardware education mit and other institutions use python as the programming language in their introductory computer science courses |
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 (searches sys pathshow classes and methods in current file show sys path directoriesmodulesclasses and methods save current window to new filewhich becomes the associated file print the current window close current window (asks to save if unsaved |
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 contents of the edit buffer open search dialog box with many options open search and replace dialog box |
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 bufferrepeat to get different expansion |
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 between configured size and maximum height the rest of this menu lists the names of all open windowsselect one to bring it to the foreground (deiconifying it if necessaryshell and debug menus are not available in the script 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 documentationif installed otherwiseaccess www python org (additional help sources may be added here using options configure idle * good to know |
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 or braces)thesunshines true while thesunshinesprint "skip work and go to the beachthesunshines false |
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 parentheses (to override the built-in precedence systemand some other things |
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 variable ' (notetype '_at the command prompt to view current value"programmers use these variable names to make their code read more like englishand because they have lousy memories if they didn' use good names for things in their softwarethey' get lost when they tried to read their code again ("learn python the hard wayby zed shaw |
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 the left operand and assign the result to left operand(multiply right operand with the left operand and assign the result to left operand(divide left operand with the right operand and assign the result to left operand*remember that double '==sign is the equality operator |
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 butall the previously shown ones arefileeditwindowshelprun menu is not available in the interactive 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 interactive window |
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 completelyit makes an excellent testing ground |
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 with uppercase (and possibly " "use blank lines to separate groups of related code surround operators with single space on either side avoid extraneous whitespace in other situations consistencyyou really should read through pep |
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 multiple expressions for truth value and execute block of code as soon as the first one of the conditions evaluates to true (all following elif expressions are ignoredelse is catch-all in case previous condition(snot met |
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 desiredgeneric syntaxwhile expressionstatement( |
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_var in sequencestatements( |
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(objectclassinfoiter( [sentinel]len(slist([iterable]locals(long([ [base]]see |
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([object]xrange([start]stop[step]zip([iterable]see |
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_suite return [expression |
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 programsimply saving as new appropriate name before modifying |
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 constantly (rememberconcepts are the important things idle is often good for quick jobs (and has some useful tools don' reinvent the wheel check the python package index (pypifirst from author of "head first pythonbook paul berry |
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 visualizationcrafting visual transformation scriptsshai vaingast dive into pythonmark pilgrim foundations of agile python developmentjeff younker beginning pythonfrom novice to professionalmagnus lie hetland python programming for the absolute beginnermichael dawson gray hat pythonpython programming for hackers and reverse engineersjustin seitz pythoncreate modify reusejames knowlton python power!the comprehensive guidematt telles most recently published (and latest editionslisted from top to bottom |
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 applications written in framework built on python called "django"desktop applications like blenderthe - animation suite which makes considerable use of python scriptsthe scientific python libraries ("scipy")instrument control and embedded systems |
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 the strictly compiled end languages like cc+or fortran are "compiled(convertedinto raw machine code for your computer you point your cpu at that code and it runs slightly separate from the strictly compiled languages are languages like java and (or anything running in the net frameworkyou do need to explicitly compile these programming languages but they are compiled to machine code for fake cpu which is then emulated on whichever system you run on then there is python python does not have to be explicitly compiled but behind the scenes there is system that compiles python into an intermediate code which is stashed away to make things faster in future but it does this without you having to do anything explicit yourself so from the point of view of how you use it you can treat it as purely interpreted language like the shell or perl |
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 command the unix command we are going to give is "python please note that trailing " the command "pythongives you either python or python depending on what system you are on with this command we are insisting on getting version of python the python interpreter then runsstarting with couple of lines of blurb in particular it identifies the specific version of python it is running in this slide then it gives prompt of its ownthree "greater thancharacters the python program is now running and it is prompting us to give python command you cannot give unix command at python prompt (or vice versa |
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 python prompt the convention in these slides is that the typewriter text in bold face is what you type and the text in regular face is what the computer prints we type "printfollowed by an opening round brackets and the text "helloworld!surrounded by single quotesending with closing round bracket and hitting the return key|]to indicate that we are done with that line of instruction the computer responds by outputting "helloworld!without the quotes once it has done that it prompts us again asking for another python command with another python prompt" |
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 mathematical underpinnings of computer science in this course our function in this case is "printand the command necessarily starts with the name of the function the inputs to the function are called its "argumentsand follow the function inside round brackets ("parentheses"in this case there is single argumentthe text to print note that pythonas with many but not all programming languagesis "case sensitivethe word "printis not the same as "printor "print |
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 interpreter that "heythis is text!recall that the the printed output does not have quotes |
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 printed |
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 livethey need to be kept in file and python needs to be directed to run the commands from that file these files are called "scriptsand we are now going to look at the python script version of "helloworldin your home directories we have put file called "hello pyit is conventional that python scripts have file names ending with pysuffix some tools actually require it we will follow this convention and you should too this contains exactly the same as we were typing manuallya single line with the print command on it we are going to make python run the instructions out of the script we call this "running the scriptscripts are run from the unix command line we issue the unix command "python to execute python againbut this time we add an extra wordthe name of the script"hello pywhen it runs commands from scriptpython doesn' bother with the lines of blurb and as soon as it has run the commands (hence the outputit exists immediatelyreturning control to the unix environmentso we get unix prompt back |
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 application for python (textscript this is the text editor (and not python instance to run the script |
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 course up to that point here is your first firstmake sure you can print text from interactive python and quit it afterwards secondedit the exercise py script and run the edited version with the different output this is really test of whether you can get the basic tools running please ask if you have any problems |
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 for characters from almost every language in the world if you are interested in international text you need to know about the unicode standard the url shown will introduce you to the wide range of characters supported the example in the slide contains the following charactersplanck' constant divided by two pi cyrillic small letter latin small letter with bar da cherokee letter da ` ethiopic syllable pharyngeal da !greek small letter omega white smiling face armenian small letter reh coptic small letter lauda partial differential double exclamation mark |
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 special characters on linuxfor examplethe combination of the three keys [altgr][shift]and [#set up the breve accent to be applied to the next key pressed perhaps easier is the "character selectorapplication this runs like freestanding "insert special characterfunction from word processor you can select character from itcopy it to the clipboard and paste it into any document you want finallypython supports the idea of "unicode codesthe two characters "\ufollowed by the hexadecimal (base code for the character in the unicode tables will represent that character you have all memorized your code tableshaven' you |
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 the conventional computing name for text we typically call them "stringsinternallypython allocates chunk of computer memory to store our text it stores certain items together to do this first it records that the object is stringbecause that will determine how memory is allocated subsequently then it records how long the string is then it records the text itself |
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 character corresponding to any number with the chr(function mathematical notethe subscript and indicate the "baseof the numbers |
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 that what is encoded in the string is single character the backslash is signal to the python interpreter as its constructs the string once the string is constructedwith quotes in itthe backslash' work is done this process of flagging character to be treated differently than normal is called "escapingthe character |
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 it should process the line so far and python cannotit is incomplete |
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 exactly how many characters there are in string the len(function tells us the length of the string in characters there are characters in the string created by 'hello,\nworld!the quotes are not part of the text and the \ becomes single character |
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 have special characters associated with them but the two most commonly useful are these\ new line \ tab stop |
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 __ and go\nback to the time when my father kept\nthe admiral benbow inn and he brown\nold seaman with the sabre cut irst\ntook up his lodging under our roof single line the "\ntrick is useful for the occasional new line it is no use for long texts where we want to control the formatting ourselves |
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 go back to the time when my father kept the admiral benbow inn and the brown old seaman with the sabre cut first took up his lodging under our roof ''triple quotes multiple lines python has special trick precisely for convenient definition of longmultiline text if you start the text with "triple quotethen the special treatment of hitting the [|key is turned off this lets you enter text "free formwith natural line breaks the triple quote is three quote characters with no spaces between them the quote character used can be either one but the triple use at one end must match the one used at the other end |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.