id
int64
0
25.6k
text
stringlengths
0
4.59k
2,000
executablesand changing just py_python as needed conclusionsa net win for windows to be fairsome of the prior section' pitfalls may be an inevitable consequence of trying to simultaneously support unix feature on windows and multiple installed versions in exchangeit provides coherent way to manage mixed-version scripts...
2,001
python changes and this book this appendix briefly summarizes changes made in recent releases of python organized by the book editions where they first appearedand gives links to their coverage in this book it is intended as reference for both readers of prior editionsas well as developers migrating from prior python r...
2,002
to ( the with statement and class decorators)or back-ported later to ( set and dictionary comprehensions)but are not available in earlier releases see later sections for more fine-grained information about changes in earlier versionsand see python' "what' newdocuments for changes that may appear in future releases diff...
2,003
os and io classes that includes additional categories and granularity in xexception attributes must sometimes be inspected on system errors comparisons and sortsin xrelative magnitude comparisons of both mixedtypes and dictionaries are errorsand sorts do not support mixed types or general comparison functions (use key ...
2,004
general general remarks changes although the python line covered in the two most recent editions of this book is largely the same language as its predecessorit differs in some crucial ways as discussed in the preface and summarized in the preceding section ' nonoptional unicode modelmandatory new-style classesand broad...
2,005
modulesgrouping them into packagesand changing api call patterns some library changes are much broaderthough python ' unicode modelfor examplecreates widespread differences in ' standard library--it potentially impacts any program that processes file contentfilenamesdirectory walkerspipesdescriptor filessocketstext in ...
2,006
presented in this book--importing features from __future__avoiding versionspecific toolsand so on many of the examples in this book are platform-neutral for examplessee the benchmarking tools in the module reloaders and comma formatter in the class tree listers in most of the larger decorator examples in and the joke s...
2,007
changes list of table - or the python changes sectionboth ahead they were already present for xbut have been updated to reflect their availability in as well on the logistical frontper current plans will be the last major series releasebut will have long maintenance period in which it will continue to be used in produc...
2,008
and emailand potentially distutilsimpacts in this booktime has new portable calls in (see and an implementation of the __import__ function in importlib __import__in part to unify and more clearly expose its implementation (see and new capability in the windows installer that extends the system path setting to include '...
2,009
(multiple context manager syntax in with statements (new methods for number objects ((not added until this fifth editionfloating-point display changes and this fifth edition covers these topics in the just noted because python was targeted primarily at optimization and was released relatively soon after the fourth edit...
2,010
covered in sdivision operators in remaindersand / set literals in {abc set comprehensions in { ** for in seq dictionary comprehensions in {xx** for in seq binary digit-string support in and bin( the fraction number type in and fraction( function annotations in def ( : :str)->int keyword-only arguments in def ( *bc** ex...
2,011
replacement covered in sraw_input input old input eval(input() xrange range file open (and io module classes next __next__called by next( __getslice__ __getitem__ passed slice ob __setslice__ __setitem__ passed slice ob reduce functools reduce (or loop code execfile(filenameexec(open(file nameread() exec open(filenamee...
2,012
replacement covered in sdictionary compare sorted( items()(or loop code types listtype list (types is for non-built-in names __metaclass__ class (metaclass= ) __builtin__ builtins (renamed tkinter tkinter (renamed sys exc_typeexc_value sys exc_info()[ ][ function func_code function __code__ __getattr__ run by built-ins...
2,013
of the major language topics for which new or expanded coverage was provided (numbers here have been updated to reflect this fifth edition)the new if else conditional expression (with/as context managers (try/except/finally unification (relative import syntax (generator expressions (new generator function features (fun...
2,014
solutions to end-of-part exercises part igetting started see "test your knowledgepart exerciseson page in for the exercises interaction assuming python is configured properlythe interaction should look something like the following (you can run this any way you like (in idlefrom shell promptand so on)python copyright in...
2,015
file' directoryit contains the compiled byte code version of module see for more on modules scripts assuming your platform supports the #trickyour solution will look like the following (although your #line may need to list another path on your machinenote that these lines are significant under the windows launcher ship...
2,016
to the original listnot copy of the list an unending stream of [ [ [ [ and so onuntil you hit the break-key combination on your machine (whichtechnicallyraises keyboardinterrupt exception that prints default messagebeginning with python the printer is clever enough to detect cycles and prints []instead to let you know ...
2,017
about their meaning againnote that is used in few of these to squeeze more than one statement onto single line (the is statement separator)and commas build up tuples displayed in parentheses also keep in mind that the division result near the top differs in python and (see for details)and the list wrapper around dictio...
2,018
{' ': ' ': }[' ' {' ': ' ': ' ': [' ' [' ' [' ' [( , , ) index dictionary by key create new entry tuple used as key (immutabled {' ' ' ' ' ' ( ) ' ' list( keys())list( values())( , , in ([' '' '' '( )' '][ ]truemethodskey test empties [[]]["",[],(),{},none([[]][''[](){}none]lots of nothingsempty objects indexing and sl...
2,019
an empty list object therebut assigning an empty list to slice deletes the slice slice assignment expects another sequenceor you'll get type errorit inserts items inside the sequence assignednot the sequence itselfl [ , , , [ [ [ [] [ : [ [ del [ [ del [ : [ [ : traceback (innermost last)file ""line in typeerrorillegal...
2,020
been assigned when referencedbut they are created when first assigned in factvariable names can be processed as dictionary keys if you wish (they're made visible in module namespace or stack-frame dictionaries) {' ': ' ': ' ': [' ' [' 'traceback (innermost last)file ""line in keyerrord [' ' {' ' ' ' ' ' ' ' [ [ traceba...
2,021
list({keys()[[keys(traceback (innermost last)file ""line in attributeerrorkeys [][:[""[:'list(needed in xnot string indexing this is bit of trick question--because strings are collections of one-character stringsevery time you index stringyou get back string that can be indexed again [ ][ ][ ][ ][ just keeps indexing t...
2,022
print(file read()python maker py python reader py hello file worldls - myfile txt -rwxrwxrwa apr : myfile txt part iiistatements and syntax see "test your knowledgepart iii exerciseson page in for the exercises coding basic loops as you work through this exerciseyou'll wind up with code that looks like the followings '...
2,023
recent pythonsyou can achieve the same effect with the sorted built-intood {' ': ' ': ' ': ' ': ' ': ' ': ' ': {' ' ' ' ' ' ' ' ' ' ' ' ' ' keys list( keys()list(required in xnot in keys sort(for key in keysprint(key'=>' [key] = = = = = = = for key in sorted( )print(key'=>' [key]betterin more recent pythons program log...
2,024
if ( *xin lprint(( * )'was found at' index( * )elseprint( 'not found' [for in range( ) append( *iprint(lif ( *xin lprint(( * )'was found at' index( * )elseprint( 'not found' list(map(lambda **xrange( ))print(lor [ ** for in range( )list(to print all in xnot if ( *xin lprint(( * )'was found at' index( * )elseprint( 'not...
2,025
{'food''spam' arguments here' sample solution remember that you have to use print to see results in the test calls because file isn' the same as code typed interactivelypython doesn' normally echo the results of expression statements in filesdef adder(xy)return print(adder( )print(adder('spam''eggs')print(adder([' '' '...
2,026
adder adder spameggstoast adder [' '' '' '' '' '' 'adder adder spameggstoast adder [' '' '' '' '' '' ' keywords here is my solution to the first and second parts of this exercise (coded in the file mod pyto iterate over keyword argumentsuse the **args form in the function header and use loop ( for in args keys()use arg...
2,027
print(adder ( = = = )adder ( ='aa' ='bb' ='cc')print(adder ( = = = )adder ( ='aa' ='bb' ='cc') (and dictionary tools here are my solutions to exercises and (file dicts pythese are just coding exercisesthoughbecause python added the dictionary methods copy(and update( to handle things like copying and adding (mergingdic...
2,028
def (ab= * )print(abcpython ( ( = = defaults and positional varargs matched by position (order mattersmatched by name (order doesn' matterf ( ( extra positionals collected in tuple ( = = {' ' ' ' extra keywords collected in dictionary ( = = ( {' ' ' ' extra of both kinds ( ( both defaults kick in ( ( ( ( ,one argumentm...
2,029
prime( )prime( prime(- here is the module in actionthe /operator allows it to work for floating-point numbers tooeven though it perhaps should notpython primes py is prime is prime has factor has factor is prime is prime not prime - not prime this function still isn' very reusable--it could return valuesinstead of prin...
2,030
import systimer reps repslist range(repsfrom math import sqrt def mathmod()for in repslistres sqrt(ireturn res pull out range list time for not math sqrtadds attr fetch time def powcall()for in repslistres pow( return res def powexpr()for in repslistres * return res print(sys versionfor test in (mathmodpowcallpowexpr)e...
2,031
powexpr = to time the relative speeds of python and dictionary comprehensions and equivalent for loops interactivelyyou can run session like the following it appears that the two are roughly the same in this regard under python unlike list comprehensionsthoughmanual loops are slightly faster than dictionary comprehensi...
2,032
if = print('stop'elseprint(nend='countdown( - xprint 'stop xprint ncountdown( stop countdown( stop nonrecursive optionslist(range( - )[ on onlyt [print(iend='for in range( - ) list(map(lambda xprint(xend=')range( - )) didn' include generator-based solution in this exercise on the grounds of merit (and humanity!)but one...
2,033
reduce(operator mulrange( - )to avoid lambda #!python from __future__ import print_function from functools import reduce from timeit import repeat import math def fact ( )if = return elsereturn fact ( - def fact ( )return if = else fact ( - def fact ( )return reduce(lambda xyx yrange( + )def fact ( )res for in range( +...
2,034
of magnitude slower in cpythonthough these results vary in pypydef rev ( )if len( = return elsereturn [- rev ( [:- ]recursive slower in cpython today def rev ( )return 'join(reversed( )nonrecursive iterablesimplerfaster def rev ( )return [::- even better?sequence reversal by slice part vmodules and packages see "test y...
2,035
return tot generator expression can have the same effect (though the instructor might take off points for excessive magic!)def countlines(name)return sum(+ for line in open(name)def countchars(name)return sum(len(linefor line in open(name)on unixyou can verify your output with wc commandon windowsright-click on your fi...
2,036
def countchars(name)return len(open(nameread()def test(name)return countlines(name)countchars(nameor pass file object or return dictionary if __name__ ='__main__'print(test('mymod py')python mymod py ( this is where would probably begin to consider using command-line arguments or user input to provide the filename to b...
2,037
namecollector somenameand __main__ somenameall three share the same integer object initiallyand only the name somename exists at the interactive prompt as isfile mod py somename file collector py from mod import from mod import from mod import collect lots of names here from assigns to my names from collector import so...
2,038
when the recur import resumesthe second from finds the name in recur (it' been run completely)so no error is reported running file as script is not the same as importing it as modulethese cases are the same as running the first import or from in the script interactively for instancerunning recur as script worksbecause ...
2,039
not implementedx listadder([ ] [ [ [ in typeerrorcan only concatenate list (not "listadder"to list earliertypeerror__add__ nor __radd__ defined for these operands notice in the last test that you get an error for expressions where class instance appears on the right of +if you want to fix thisuse __radd__ methodsas des...
2,040
class mylistdef __init__(selfstart)#self wrapped start[:self wrapped list(startdef __add__(selfother)return mylist(self wrapped otherdef __mul__(selftime)return mylist(self wrapped timedef __getitem__(selfoffset)return self wrapped[offsetdef __len__(self)return len(self wrappeddef __getslice__(selflowhigh)return mylist...
2,041
class mylistsub(mylist)calls def __init__(selfstart)self adds mylist __init__(selfstartdef __add__(selfother)print('addstr(other)mylistsub calls + self adds + return mylist __add__(selfotherdef stats(self)return self callsself adds shared by instances varies in each instance class-wide counter per-instance counts all a...
2,042
attrs( append get append spam 'porkset spam pork get __coerce__ typeerror'nonetypeobject is not callable [ get __getitem__ typeerror'nonetypeobject is not callable [ : get __getslice__ typeerror'nonetypeobject is not callable :\codepy - same startup code typeerrorunsupported operand type(sfor +'attrsand 'intx[ typeerro...
2,043
class (file multiset pyit needs to replace only two methods in the original set the class' documentation string explains how it worksfrom setwrapper import set class multiset(set)""inherits all set namesbut extends intersect and union to support multiple operandsnote that "selfis still the first argument (stored in the...
2,044
multiset('spam' set:[' '' '' '' ''join( 'super''spamuer( 'super'multiset('slots'set:[' 'string sets class tree links here is the way changed the lister classesand rerun of the test to show its format do the same for the dir-based versionand also do this when formatting class objects in the tree climber variantclass lis...
2,045
place order with employee self food employee takeorder(foodnamedef printfood(self)print the name of my food print(self food nameclass employeedef takeorder(selffoodname)return food(foodnamereturn foodwith desired name class fooddef __init__(selfname)self name name store food name if __name__ ='__main__' lunch( order('b...
2,046
def line(self)print(self name ':'repr(self says())class customer(actor)name 'customerdef says(self)return "that' one ex-bird!class clerk(actor)name 'clerkdef says(self)return "no it isn' class parrot(actor)name 'parrotdef says(self)return none class scenedef __init__(self)self clerk clerk(self customer customer(self su...
2,047
caught an index error exception objects and lists here' the way extended this module for an exception of my ownfile oops pyfrom __future__ import print_function class myerror(exception)pass def oops()raise myerror('spam!'def doomed()tryoops(except indexerrorprint('caught an index error!'except myerror as dataprint('cau...
2,048
traceback (most recent call last)file " :\code\exctools py"line in safe callee(*pargs**kargscatch everything else file " :\code\oops py"line in oops raise myerror('spam!'oops myerrorspamgot spamthe following sort of code could turn this into function decorator that could wrap and catch exceptions raised by any function...
2,049
import sysospprint if sys platform[: ='win'dirname ' :\python \libelsedirname '/usr/lib/pythonallsizes [for (thisdirsubsherefilesherein os walk(dirname)for filename in fileshereif filename endswith(py')fullname os path join(thisdirfilenamefullsize os path getsize(fullnameallsizes append((fullsizefullname)allsizes sort(...
2,050
for (ixnumin enumerate(nums)sums[ixsums get(ix num for key in sorted(sums)print(key'='sums[key]similar to priorbut using lists instead of dictionaries for sums import sys filename sys argv[ numcols int(sys argv[ ]totals [ numcols for line in open(filename)cols line split(','nums [int(xfor in colstotals [( yfor (xyin zi...
2,051
label(popuptext='popup'bg='black'fg=colorpack( config(fg=colordef timer() config(fg=random choice(colors)win after( timerdef grow()global fontsize fontsize + config(font=('arial'fontsize'italic')win after( growwin tk( label(wintext='spam'font=('arial'fontsize'italic')fg='yellow'bg='navy'relief=raisedl pack(side=topexpa...
2,052
self grower(def grower(self)if self growingself fontsize + self lab config(font=('courier'self fontsize'bold')self lab after( self growerdef stop(self)"stop the button growing on stop pressesself growing false class mysubgui(mygui)colors ['black''purple'customize to change color choices mygui(tk()'main'mygui(toplevel()...
2,053
if input('delete?'in [' '' ']print('deleting'server dele(msgnumelseprint('skipping'finallyserver quit(input('bye 'get whole msg delete on srvr make sure we unlock mbox keep window up on windows cgi server-side script to interact with web browser #!/usr/bin/python import cgi form cgi fieldstorage(parse form data print("...
2,054
db close(database script to populate and query mysql database from mysqldb import connect conn connect(host='localhost'user='root'passwd='xxxxxxx'curs conn cursor(trycurs execute('drop database testpeopledb'exceptpass did not exist curs execute('create database testpeopledb'curs execute('use testpeopledb'curs execute('...
2,055
print('connecting 'connection ftp(sitenameconnection login(*userinfoconnection cwd(dirnameif nonpassiveconnection set_pasv(falseconnect to ftp site default is anonymous login xfer at time to localfile force active ftp if server requires print('downloading 'localfile open(filename'wb'local file to store download connect...
2,056
symbols character comments directives #characters - - (percent signformatting expression operator system shell prompt (parenthesescomprehensions and expression operators and statements and superclasses and tuples and (multiplicationoperator multiplying numbers repeating lists repeating strings (plusoperator adding numb...
2,057
any built-in function anydbm module apply built-in function arbitrary arguments - arbitrary expressions arbitrary structures - argparse module arguments (see also keyword argumentsabout arbitrary - avoiding changes calculating lengths of call expressions and coding functions decorator - - - default values - - intersect...
2,058
backslash (\escape sequences and - multiline statements and backtrackingexception handlers and base classes baseexception class __bases__ attribute about inheritance and bdfl (benevolent dictator for life) benchmarking pystone py program quiz questions and answers timeit module - timing iteration - usage examples benev...
2,059
changing strings bytes built-in function bytes string type about - bytearray string type and encoded text making bytes objects method calls mixing string types pickle module and quiz questions and answers - sequence operations type and content mismatches language argument-passing model #define directive error checks #i...
2,060
closures versus coding class trees - coding gotchas - combining - customizing behavior - customizing constructors - decorators and - descriptors and dictionaries versus - docstrings and exception - explicit attributes and extending built-in types - functions and generators and - inheritance and - - instances (see insta...
2,061
colon character common usage mistakes special case rules - - terminating timing comprehension variables comprehensions (see also list comprehensionsdictionary - - iterables versus - quiz questions and answers set - syntax summary - concatenating lists strings tuples virtual concatenation conflict resolutiondiamond inhe...
2,062
databases and filesystemsdbm module __debug__ built-in variable debugging python code about - idle debugger string issues tools supporting with try statement decimal module decimals (decimal objectabout - context manager from_float method getcontext method localcontext method numeric accuracy in resetting precision tem...
2,063
built-in type gotchas - class gotchas - code reuse - coding class decorators - coding class trees - coding constructors coding exception classes - coding exception details - coding function decorators - coding functions - - coding metaclasses - coding methods - coding strings - coding subclasses common coding gotchas -...
2,064
- dir built-in function about customizing version of as documentation source - inheritance and - inspecting namespaces directives directoriesfile precedence over - diretory walkers display formats generic display tool neutralizing difference with code - numeric print operations - distutils modules division operations a...
2,065
pythonstartup py_python py_python py_python tcl_library tk_library eoferror exception __eq__ method equality built-in object types - shared references and - testing truth values - value equality operators equivalence (==operator errno module error handling displaying errors and tracebacks exceptions and missing keys - ...
2,066
polymorphism and set operations and version considerations expressions (see also lambda expressionsabout arbitrary call - code examples expression operators - functions versus generator - indexing numbers in - objects and operator overloading and quiz questions and answers slice statements and - string formatting - var...
2,067
general format iteration and list comprehensions and nested loops nesting - parallel traversals - quiz questions and answers range built-in function and recursion versus sequence scans sorting keys - terminating usage examples - format built-in function __format__ method formatting strings (see string formattingfractio...
2,068
quiz questions and answers recursive - - scope considerations signaling conditions with unbound methods as functools module __future__ module garbage collection about exception variables and objects and - gc module __ge__ method generators about classes and - eibti acronym - functions versus expressions - generating sc...
2,069
string escape sequences html reports - - command-line argument __iadd__ method - icon clicks about limitations - windows platform - id built-in function ides (integrated development environmentsabout alternative - idle user interface about advanced tools basic usage - common usage mistakes - multiline block strings sta...
2,070
instances and mapping attributes to sources - metaclasses and - multiple namespaces and oop considerations - specializing inherited methods subclasses and type object and usage examples __init__ method about attribute validation and class decorators and coding multiple constructors and inheritance and metaclasses and _...
2,071
additional contexts - additional information built-in functions and - built-in types supported - comprehensions versus - in dictionaries - in files - generators and - in lists loop coding techniques - - manual - multiple versus single pass one-shot operator overloading and - quiz questions and answers timing iteration ...
2,072
working directory list built-in function about converting objects to lists iteration protocol and type customization and list comprehensions about - - extended syntax - files and filter built-in function and - for statement and functional tools - generator expressions and map built-in function versus matrixes and - ran...
2,073
system shell prompt working directory macrosdecorators versus __main__ module - manager functions - map built-in function benchmarking generator expressions versus - homegrown timing module and - iteration and - list comprehensions versus loop coding techniques and - parallel traversals - timing calls example version c...
2,074
scopes in static string - - string formatting - superclass constructors tuple - unbound - underscores in usage examples microthreads min built-in function missing keys - mix-in classes - - __mod__ method module search path about - changing - lookup rules summary running modules modules (see also from statementimport st...
2,075
metaprogram example mixed usage modes - modules and preset value name collisions name mangling name resolution - named tuples - namespace declarations namespace dictionaries about - __dict__ attribute slots and - namespace package model about file precedence in - nesting semantics - usage examples - namespaces about as...
2,076
complex decimals (see decimalsdivision operation - expression operators - in expressions - floating-point (see floating-point numbersfractions (see fractionsintegers (see integersnumeric display formats numeric extensions numeric literals - quiz questions and answers rational sequence operations sets (see setsin variab...
2,077
pseudoprivate class attributes - python and quiz questions and answers realistic example of classes - state information static and class methods - super built-in function - open built-in function customizing - file processing and version considerations windows platform and operations (see specific operationsoperator mo...
2,078
- package imports package search paths recording for recursive calls pattern matching in strings about re module and pdb command-line debugger pep (python enhancement proposal) percent sign (%formatting expression operator system shell prompt performance considerations (see also benchmarkinglist comprehensions mro and ...
2,079
optimization tools - performance considerations programmer' perspective - pvm and quiz questions and answers - selecting from options system command lines and files - text editor launch options unix-style scripts - program units (see also classesfunctionsmodulesprogramming python (lutz) programs about metaprograms - mo...
2,080
pillars of programming portability quiz questions and answers - scripting and technical strengths - tools supporting - tradeoffs using user base - version considerations (see version considerations for pythonpython software foundation (psf) python virtual machine (pvm) pythonioencoding environment variable pythonlaunch...
2,081
raising exceptions raising instances signaling conditions with version considerations random module about generator example range built-in function counter loops iteration and list comprehensions and loop coding techniques and - nonexhaustive traversals sequence scans sequence shufflers timing calls example rapid devel...
2,082
scipy programming extension scopes about - accessing global variables builtins module - comprehension variables and function-related gotchas global statement imports versus legb rule and - in methods and classes minimizing cross-file changes - minimizing global variables modules and name resolution and - nested functio...
2,083
__setslice__ method shadowing shared references about - arguments and - augmented assignments and equality and - in-place changes and - multiple-target assignments and shed skin system shell tools and commands - (see also system command lines and filesshelve module about dictionary interfaces and exploring shelves inte...
2,084
indenting - interactive loops example - listed - modules and parentheses and python syntax model - quiz questions and answers semicolon and special case rules - - syntax rules - terminating version considerations static methods about alternatives for counting instances usage considerations - version considerations - st...
2,085
operator overloading and - parsing text pattern matching quiz questions and answers repeating replace method rstrip method sequence operations - slicing - split method tool changes - type and content mismatches type-specific methods - unicode - - upper method version considerations - - strong typing struct module - __s...
2,086
try/finally statement and - - with/as statement and testing error handling - filtering results from statement and interactive prompt and list comprehensions and - for missing keys with __name__ attribute for positional arguments - processes - reloading variants timing calls example truth values - - type - text editor l...
2,087
python is an easy to learnpowerful programming language it has efficient high-level data structures and simple but effective approach to object-oriented programming python' elegant syntax and dynamic typingtogether with its interpreted naturemake it an ideal language for scripting and rapid application development in m...
2,088
contents
2,089
one whetting your appetite if you do much work on computerseventually you find that there' some task you' like to automate for exampleyou may wish to perform search-and-replace over large number of text filesor rename and rearrange bunch of photo files in complicated way perhaps you' like to write small custom database...
2,090
are really hookedyou can link the python interpreter into an application written in and use it as an extension or command language for that application by the waythe language is named after the bbc show "monty python' flying circusand has nothing to do with reptiles making references to monty python skits in documentat...
2,091
two using the python interpreter invoking the interpreter the python interpreter is usually installed as /usr/local/bin/python on those machines where it is availableputting /usr/local/bin in your unix shell' search path makes it possible to start it by typing the commandpython to the shell since the choice of the dire...
2,092
all command line options are described in using-on-general argument passing when known to the interpreterthe script name and additional arguments thereafter are turned into list of strings and assigned to the argv variable in the sys module you can access this list by executing import sys the length of the list is at l...
2,093
for exampleto declare that windows- encoding is to be usedthe first line of your source code file should be-*codingcp -*one exception to the first line rule is when the source code starts with unix "shebangline in this casethe encoding declaration should be added as the second line of the file for example#!/usr/bin/env...
2,094
using the python interpreter
2,095
three an informal introduction to python in the following examplesinput and output are distinguished by the presence or absence of prompts and )to repeat the exampleyou must type everything after the promptwhen the prompt appearslines that do not begin with prompt are output from the interpreter note that secondary pro...
2,096
division (/always returns float to do floor division and get an integer result (discarding any fractional resultyou can use the /operatorto calculate the remainder you can use % classic division returns float / floor division discards the fractional part the operator returns the remainder of the division result divisor...
2,097
in addition to int and floatpython supports other types of numberssuch as decimal and fraction python also has built-in support for complex numbersand uses the or suffix to indicate the imaginary part ( + jstrings besides numberspython can also manipulate stringswhich can be expressed in several ways they can be enclos...
2,098
print("""usagethingy [options- - hostname """display this usage message hostname to connect to produces the following output (note that the initial newline is not included)usagethingy [options- - hostname display this usage message hostname to connect to strings can be concatenated (glued togetherwith the operatorand r...
2,099
word[- 'nword[- 'oword[- 'plast character second-last character note that since - is the same as negative indices start from - in addition to indexingslicing is also supported while indexing is used to obtain individual charactersslicing allows you to obtain substringword[ : 'pyword[ : 'thocharacters from position (inc...