id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
2,200 | arguments are assigned to the named local variables in function body see the calls section for the rules governing this assignment syntacticallyany expression can be used to represent an argumentthe evaluated value is assigned to the local variable see also the parameter glossary entrythe faq question on the difference between arguments and parametersand pep asynchronous context manager an object which controls the environment seen in an async with statement by defining __aenter__(and __aexit__(methods introduced by pep asynchronous generator function which returns an asynchronous generator iterator it looks like coroutine function defined with async def except that it contains yield expressions for producing series of values usable in an async for loop usually refers to asynchronous generator functionbut may refer to an asynchronous generator iterator in some contexts in cases where the intended meaning isn' clearusing the full terms avoids ambiguity an asynchronous generator function may contain await expressions as well as async forand async with statements asynchronous generator iterator an object created by asynchronous generator function this is an asynchronous iterator which when called using the __anext__(method returns an awaitable object which will execute that the body of the asynchronous generator function until the next yield expression each yield temporarily suspends processingremembering the location execution state (including local variables and pending try-statementswhen the asynchronous generator iterator effectively resumes with another awaitable returned by __anext__()it picks up where it left off see pep and pep asynchronous iterable an objectthat can be used in an async for statement must return an asynchronous iterator from its __aiter__(method introduced by pep asynchronous iterator an object that implements the __aiter__(and __anext__(methods __anext__ must return an awaitable object async for resolves the awaitables returned by an asynchronous iterator' __anext__(method until it raises stopasynciteration exception introduced by pep attribute value associated with an object which is referenced by name using dotted expressions for exampleif an object has an attribute it would be referenced as awaitable an object that can be used in an await expression can be coroutine or an object with an __await__(method see also pep bdfl benevolent dictator for lifea guido van rossumpython' creator binary file file object able to read and write bytes-like objects examples of binary files are files opened in binary mode ('rb''wbor 'rb+')sys stdin buffersys stdout bufferand instances of io bytesio and gzip gzipfile see also text file for file object able to read and write str objects bytes-like object an object that supports the bufferobjects and can export -contiguous buffer this includes all bytesbytearrayand array array objectsas well as many common memoryview objects bytes-like objects can be used for various operations that work with binary datathese include compressionsaving to binary fileand sending over socket some operations need the binary data to be mutable the documentation often refers to these as "readwrite bytes-like objectsexample mutable buffer objects include bytearray and memoryview of bytearray other operations require the binary data to be stored in immutable objects ("read-only bytes-like objects")examples of these include bytes and memoryview of bytes object appendix glossary |
2,201 | bytecode python source code is compiled into bytecodethe internal representation of python program in the cpython interpreter the bytecode is also cached in pyc files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoidedthis "intermediate languageis said to run on virtual machine that executes the machine code corresponding to each bytecode do note that bytecodes are not expected to work between different python virtual machinesnor to be stable between python releases list of bytecode instructions can be found in the documentation for the dis module class template for creating user-defined objects class definitions normally contain method definitions which operate on instances of the class class variable variable defined in class and intended to be modified only at class level ( not in an instance of the classcoercion the implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type for exampleint( converts the floating point number to the integer but in + each argument is of different type (one intone float)and both must be converted to the same type before they can be added or it will raise typeerror without coercionall arguments of even compatible types would have to be normalized to the same value by the programmere float( )+ rather than just + complex number an extension of the familiar real number system in which all numbers are expressed as sum of real part and an imaginary part imaginary numbers are real multiples of the imaginary unit (the square root of - )often written in mathematics or in engineering python has built-in support for complex numberswhich are written with this latter notationthe imaginary part is written with suffixe + to get access to complex equivalents of the math moduleuse cmath use of complex numbers is fairly advanced mathematical feature if you're not aware of need for themit' almost certain you can safely ignore them context manager an object which controls the environment seen in with statement by defining __enter__(and __exit__(methods see pep contiguous buffer is considered contiguous exactly if it is either -contiguous or fortran contiguous zero-dimensional buffers are and fortran contiguous in one-dimensional arraysthe items must be laid out in memory next to each otherin order of increasing indexes starting from zero in multidimensional -contiguous arraysthe last index varies the fastest when visiting items in order of memory address howeverin fortran contiguous arraysthe first index varies the fastest coroutine coroutines is more generalized form of subroutines subroutines are entered at one point and exited at another point coroutines can be enteredexitedand resumed at many different points they can be implemented with the async def statement see also pep coroutine function function which returns coroutine object coroutine function may be defined with the async def statementand may contain awaitasync forand async with keywords these were introduced by pep cpython the canonical implementation of the python programming languageas distributed on python org the term "cpythonis used when necessary to distinguish this implementation from others such as jython or ironpython decorator function returning another functionusually applied as function transformation using the @wrapper syntax common examples for decorators are classmethod(and staticmethod(the decorator syntax is merely syntactic sugarthe following two function definitions are semantically equivalentdef ) staticmethod( (continues on next page |
2,202 | (continued from previous page@staticmethod def )the same concept exists for classesbut is less commonly used there see the documentation for function definitions and class definitions for more about decorators descriptor any object which defines the methods __get__()__set__()or __delete__(when class attribute is descriptorits special binding behavior is triggered upon attribute lookup normallyusing to getset or delete an attribute looks up the object named in the class dictionary for abut if is descriptorthe respective descriptor method gets called understanding descriptors is key to deep understanding of python because they are the basis for many features including functionsmethodspropertiesclass methodsstatic methodsand reference to super classes for more information about descriptorsmethodssee descriptors dictionary an associative arraywhere arbitrary keys are mapped to values the keys can be any object with __hash__(and __eq__(methods called hash in perl dictionary view the objects returned from dict keys()dict values()and dict items(are called dictionary views they provide dynamic view on the dictionary' entrieswhich means that when the dictionary changesthe view reflects these changes to force the dictionary view to become full list use list(dictviewsee dict-views docstring string literal which appears as the first expression in classfunction or module while ignored when the suite is executedit is recognized by the compiler and put into the __doc__ attribute of the enclosing classfunction or module since it is available via introspectionit is the canonical place for documentation of the object duck-typing programming style which does not look at an object' type to determine if it has the right interfaceinsteadthe method or attribute is simply called or used ("if it looks like duck and quacks like duckit must be duck "by emphasizing interfaces rather than specific typeswell-designed code improves its flexibility by allowing polymorphic substitution duck-typing avoids tests using type(or isinstance((notehoweverthat duck-typing can be complemented with abstract base classes insteadit typically employs hasattr(tests or eafp programming eafp easier to ask for forgiveness than permission this common python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false this clean and fast style is characterized by the presence of many try and except statements the technique contrasts with the lbyl style common to many other languages such as expression piece of syntax which can be evaluated to some value in other wordsan expression is an accumulation of expression elements like literalsnamesattribute accessoperators or function calls which all return value in contrast to many other languagesnot all language constructs are expressions there are also statements which cannot be used as expressionssuch as if assignments are also statementsnot expressions extension module module written in or ++using python' api to interact with the core and with user code -string string literals prefixed with 'for 'fare commonly called " -stringswhich is short for formatted string literals see also pep file object an object exposing file-oriented api (with methods such as read(or write()to an underlying resource depending on the way it was createda file object can mediate access to real on-disk file or to another type of storage or communication device (for example standard input/outputin-memory bufferssocketspipesetc file objects are also called file-like objects or streams there are actually three categories of file objectsraw binary filesbuffered binary files and text files their interfaces are defined in the io module the canonical way to create file object is by using the appendix glossary |
2,203 | open(function file-like object synonym for file object finder an object that tries to find the loader for module that is being imported since python there are two types of findermeta path finders for use with sys meta_pathand path entry finders for use with sys path_hooks see pep pep and pep for much more detail floor division mathematical division that rounds down to nearest integer the floor division operator is /for examplethe expression / evaluates to in contrast to the returned by float true division note that (- / is - because that is - rounded downward see pep function series of statements which returns some value to caller it can also be passed zero or more arguments which may be used in the execution of the body see also parametermethodand the function section function annotation an annotation of function parameter or return value function annotations are usually used for type hintsfor example this function is expected to take two int arguments and is also expected to have an int return valuedef sum_two_numbers(aintbint-intreturn function annotation syntax is explained in section function see variable annotation and pep which describe this functionality __future__ pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter by importing the __future__ module and evaluating its variablesyou can see when new feature was first added to the language and when it becomes the defaultimport __future__ __future__ division _feature(( 'alpha' )( 'alpha' ) garbage collection the process of freeing memory when it is not used anymore python performs garbage collection via reference counting and cyclic garbage collector that is able to detect and break reference cycles the garbage collector can be controlled using the gc module generator function which returns generator iterator it looks like normal function except that it contains yield expressions for producing series of values usable in for-loop or that can be retrieved one at time with the next(function usually refers to generator functionbut may refer to generator iterator in some contexts in cases where the intended meaning isn' clearusing the full terms avoids ambiguity generator iterator an object created by generator function each yield temporarily suspends processingremembering the location execution state (including local variables and pending try-statementswhen the generator iterator resumesit picks up where it left off (in contrast to functions which start fresh on every invocationgenerator expression an expression that returns an iterator it looks like normal expression followed by for expression defining loop variablerangeand an optional if expression the combined expression generates values for an enclosing functionsum( * for in range( ) sum of squares |
2,204 | generic function function composed of multiple functions implementing the same operation for different types which implementation should be used during call is determined by the dispatch algorithm see also the single dispatch glossary entrythe functools singledispatch(decoratorand pep gil see global interpreter lock global interpreter lock the mechanism used by the cpython interpreter to assure that only one thread executes python bytecode at time this simplifies the cpython implementation by making the object model (including critical built-in types such as dictimplicitly safe against concurrent access locking the entire interpreter makes it easier for the interpreter to be multi-threadedat the expense of much of the parallelism afforded by multi-processor machines howeversome extension moduleseither standard or third-partyare designed so as to release the gil when doing computationally-intensive tasks such as compression or hashing alsothe gil is always released when doing / past efforts to create "free-threadedinterpreter (one which locks shared data at much finer granularityhave not been successful because performance suffered in the common single-processor case it is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain hash-based pyc bytecode cache file that uses the hash rather than the last-modified time of the corresponding source file to determine its validity see pyc-invalidation hashable an object is hashable if it has hash value which never changes during its lifetime (it needs __hash__(method)and can be compared to other objects (it needs an __eq__(methodhashable objects which compare equal must have the same hash value hashability makes an object usable as dictionary key and set memberbecause these data structures use the hash value internally all of python' immutable built-in objects are hashablemutable containers (such as lists or dictionariesare not objects which are instances of user-defined classes are hashable by default they all compare unequal (except with themselves)and their hash value is derived from their id(idle an integrated development environment for python idle is basic editor and interpreter environment which ships with the standard distribution of python immutable an object with fixed value immutable objects include numbersstrings and tuples such an object cannot be altered new object has to be created if different value has to be stored they play an important role in places where constant hash value is neededfor example as key in dictionary import path list of locations (or path entriesthat are searched by the path based finder for modules to import during importthis list of locations usually comes from sys pathbut for subpackages it may also come from the parent package' __path__ attribute importing the process by which python code in one module is made available to python code in another module importer an object that both finds and loads moduleboth finder and loader object interactive python has an interactive interpreter which means you can enter statements and expressions at the interpreter promptimmediately execute them and see their results just launch python with no arguments (possibly by selecting it from your computer' main menuit is very powerful way to test out new ideas or inspect modules and packages (remember help( )interpreted python is an interpreted languageas opposed to compiled onethough the distinction can be blurry because of the presence of the bytecode compiler this means that source files can be run directly without explicitly creating an executable which is then run interpreted languages typically appendix glossary |
2,205 | have shorter development/debug cycle than compiled onesthough their programs generally also run more slowly see also interactive interpreter shutdown when asked to shut downthe python interpreter enters special phase where it gradually releases all allocated resourcessuch as modules and various critical internal structures it also makes several calls to the garbage collector this can trigger the execution of code in user-defined destructors or weakref callbacks code executed during the shutdown phase can encounter various exceptions as the resources it relies on may not function anymore (common examples are library modules or the warnings machinerythe main reason for interpreter shutdown is that the __main__ module or the script being run has finished executing iterable an object capable of returning its members one at time examples of iterables include all sequence types (such as liststrand tupleand some non-sequence types like dictfile objectsand objects of any classes you define with an __iter__(method or with __getitem__(method that implements sequence semantics iterables can be used in for loop and in many other places where sequence is needed (zip()map()when an iterable object is passed as an argument to the built-in function iter()it returns an iterator for the object this iterator is good for one pass over the set of values when using iterablesit is usually not necessary to call iter(or deal with iterator objects yourself the for statement does that automatically for youcreating temporary unnamed variable to hold the iterator for the duration of the loop see also iteratorsequenceand generator iterator an object representing stream of data repeated calls to the iterator' __next__(method (or passing it to the built-in function next()return successive items in the stream when no more data are available stopiteration exception is raised instead at this pointthe iterator object is exhausted and any further calls to its __next__(method just raise stopiteration again iterators are required to have an __iter__(method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted one notable exception is code which attempts multiple iteration passes container object (such as listproduces fresh new iterator each time you pass it to the iter(function or use it in for loop attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration passmaking it appear like an empty container more information can be found in typeiter key function key function or collation function is callable that returns value used for sorting or ordering for examplelocale strxfrm(is used to produce sort key that is aware of locale specific sort conventions number of tools in python accept key functions to control how elements are ordered or grouped they include min()max()sorted()list sort()heapq merge()heapq nsmallest()heapq nlargest()and itertools groupby(there are several ways to create key function for example the str lower(method can serve as key function for case insensitive sorts alternativelya key function can be built from lambda expression such as lambda ( [ ] [ ]alsothe operator module provides three key function constructorsattrgetter()itemgetter()and methodcaller(see the sorting how to for examples of how to create and use key functions keyword argument see argument lambda an anonymous inline function consisting of single expression which is evaluated when the function is called the syntax to create lambda function is lambda [parameters]expression lbyl look before you leap this coding style explicitly tests for pre-conditions before making calls or lookups this style contrasts with the eafp approach and is characterized by the presence of many if statements |
2,206 | in multi-threaded environmentthe lbyl approach can risk introducing race condition between "the lookingand "the leapingfor examplethe codeif key in mappingreturn mapping[keycan fail if another thread removes key from mapping after the testbut before the lookup this issue can be solved with locks or by using the eafp approach list built-in python sequence despite its name it is more akin to an array in other languages than to linked list since access to elements is ( list comprehension compact way to process all or part of the elements in sequence and return list with the results result ['{:# }format(xfor in range( if = generates list of strings containing even hex numbers ( in the range from to the if clause is optional if omittedall elements in range( are processed loader an object that loads module it must define method named load_module( loader is typically returned by finder see pep for details and importlib abc loader for an abstract base class mapping container object that supports arbitrary key lookups and implements the methods specified in the mapping or mutablemapping abstract base classes examples include dictcollections defaultdictcollections ordereddict and collections counter meta path finder finder returned by search of sys meta_path meta path finders are related tobut different from path entry finders see importlib abc metapathfinder for the methods that meta path finders implement metaclass the class of class class definitions create class namea class dictionaryand list of base classes the metaclass is responsible for taking those three arguments and creating the class most object oriented programming languages provide default implementation what makes python special is that it is possible to create custom metaclasses most users never need this toolbut when the need arisesmetaclasses can provide powerfulelegant solutions they have been used for logging attribute accessadding thread-safetytracking object creationimplementing singletonsand many other tasks more information can be found in metaclasses method function which is defined inside class body if called as an attribute of an instance of that classthe method will get the instance object as its first argument (which is usually called selfsee function and nested scope method resolution order method resolution order is the order in which base classes are searched for member during lookup see the python method resolution order for details of the algorithm used by the python interpreter since the release module an object that serves as an organizational unit of python code modules have namespace containing arbitrary python objects modules are loaded into python by the process of importing see also package module spec namespace containing the import-related information used to load module an instance of importlib machinery modulespec mro see method resolution order mutable mutable objects can change their value but keep their id(see also immutable named tuple any tuple-like class whose indexable elements are also accessible using named attributes (for exampletime localtime(returns tuple-like object where the year is accessible either with an index such as [ or with named attribute like tm_yeara named tuple can be built-in type such as time struct_timeor it can be created with regular class definition full featured named tuple can also be created with the factory function collections namedtuple(the latter approach automatically provides extra features such as self-documenting representation like employee(name='jones'title='programmer' appendix glossary |
2,207 | namespace the place where variable is stored namespaces are implemented as dictionaries there are the localglobal and built-in namespaces as well as nested namespaces in objects (in methodsnamespaces support modularity by preventing naming conflicts for instancethe functions builtins open and os open(are distinguished by their namespaces namespaces also aid readability and maintainability by making it clear which module implements function for instancewriting random seed(or itertools islice(makes it clear that those functions are implemented by the random and itertools modulesrespectively namespace package pep package which serves only as container for subpackages namespace packages may have no physical representationand specifically are not like regular package because they have no __init__ py file see also module nested scope the ability to refer to variable in an enclosing definition for instancea function defined inside another function can refer to variables in the outer function note that nested scopes by default work only for reference and not for assignment local variables both read and write in the innermost scope likewiseglobal variables read and write to the global namespace the nonlocal allows writing to outer scopes new-style class old name for the flavor of classes now used for all class objects in earlier python versionsonly new-style classes could use python' newerversatile features like __slots__descriptorsproperties__getattribute__()class methodsand static methods object any data with state (attributes or valueand defined behavior (methodsalso the ultimate base class of any new-style class package python module which can contain submodules or recursivelysubpackages technicallya package is python module with an __path__ attribute see also regular package and namespace package parameter named entity in function (or methoddefinition that specifies an argument (or in some casesargumentsthat the function can accept there are five kinds of parameterpositional-or-keywordspecifies an argument that can be passed either positionally or as keyword argument this is the default kind of parameterfor example foo and bar in the followingdef func(foobar=none)positional-onlyspecifies an argument that can be supplied only by position python has no syntax for defining positional-only parameters howeversome built-in functions have positionalonly parameters ( abs()keyword-onlyspecifies an argument that can be supplied only by keyword keyword-only parameters can be defined by including single var-positional parameter or bare in the parameter list of the function definition before themfor example kw_only and kw_only in the followingdef func(arg*kw_only kw_only )var-positionalspecifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameterssuch parameter can be defined by prepending the parameter name with *for example args in the followingdef func(*args**kwargs)var-keywordspecifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameterssuch parameter can be defined by prepending the parameter name with **for example kwargs in the example above parameters can specify both optional and required argumentsas well as default values for some optional arguments |
2,208 | see also the argument glossary entrythe faq question on the difference between arguments and parametersthe inspect parameter classthe function sectionand pep path entry single location on the import path which the path based finder consults to find modules for importing path entry finder finder returned by callable on sys path_hooks ( path entry hookwhich knows how to locate modules given path entry see importlib abc pathentryfinder for the methods that path entry finders implement path entry hook callable on the sys path_hook list which returns path entry finder if it knows how to find modules on specific path entry path based finder one of the default meta path finders which searches an import path for modules path-like object an object representing file system path path-like object is either str or bytes object representing pathor an object implementing the os pathlike protocol an object that supports the os pathlike protocol can be converted to str or bytes file system path by calling the os fspath(functionos fsdecode(and os fsencode(can be used to guarantee str or bytes result insteadrespectively introduced by pep pep python enhancement proposal pep is design document providing information to the python communityor describing new feature for python or its processes or environment peps should provide concise technical specification and rationale for proposed features peps are intended to be the primary mechanisms for proposing major new featuresfor collecting community input on an issueand for documenting the design decisions that have gone into python the pep author is responsible for building consensus within the community and documenting dissenting opinions see pep portion set of files in single directory (possibly stored in zip filethat contribute to namespace packageas defined in pep positional argument see argument provisional api provisional api is one which has been deliberately excluded from the standard library' backwards compatibility guarantees while major changes to such interfaces are not expectedas long as they are marked provisionalbackwards incompatible changes (up to and including removal of the interfacemay occur if deemed necessary by core developers such changes will not be made gratuitously they will occur only if serious fundamental flaws are uncovered that were missed prior to the inclusion of the api even for provisional apisbackwards incompatible changes are seen as "solution of last resortevery attempt will still be made to find backwards compatible resolution to any identified problems this process allows the standard library to continue to evolve over timewithout locking in problematic design errors for extended periods of time see pep for more details provisional package see provisional api python nickname for the python release line (coined long ago when the release of version was something in the distant future this is also abbreviated "py kpythonic an idea or piece of code which closely follows the most common idioms of the python languagerather than implementing code using concepts common to other languages for examplea common idiom in python is to loop over all elements of an iterable using for statement many other languages don' have this type of constructso people unfamiliar with python sometimes use numerical counter insteadfor in range(len(food))print(food[ ] appendix glossary |
2,209 | as opposed to the cleanerpythonic methodfor piece in foodprint(piecequalified name dotted name showing the "pathfrom module' global scope to classfunction or method defined in that moduleas defined in pep for top-level functions and classesthe qualified name is the same as the object' nameclass cclass ddef meth(self)pass __qualname__ 'cc __qualname__ ' dc meth __qualname__ ' methwhen used to refer to modulesthe fully qualified name means the entire dotted path to the moduleincluding any parent packagese email mime textimport email mime text email mime text __name__ 'email mime textreference count the number of references to an object when the reference count of an object drops to zeroit is deallocated reference counting is generally not visible to python codebut it is key element of the cpython implementation the sys module defines getrefcount(function that programmers can call to return the reference count for particular object regular package traditional packagesuch as directory containing an __init__ py file see also namespace package __slots__ declaration inside class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries though popularthe technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in memory-critical application sequence an iterable which supports efficient element access using integer indices via the __getitem__(special method and defines __len__(method that returns the length of the sequence some built-in sequence types are liststrtupleand bytes note that dict also supports __getitem__(and __len__()but is considered mapping rather than sequence because the lookups use arbitrary immutable keys rather than integers the collections abc sequence abstract base class defines much richer interface that goes beyond just __getitem__(and __len__()adding count()index()__contains__()and __reversed__(types that implement this expanded interface can be registered explicitly using register(single dispatch form of generic function dispatch where the implementation is chosen based on the type of single argument slice an object usually containing portion of sequence slice is created using the subscript notation[with colons between numbers when several are givensuch as in variable_name[ : : the bracket (subscriptnotation uses slice objects internally |
2,210 | special method method that is called implicitly by python to execute certain operation on typesuch as addition such methods have names starting and ending with double underscores special methods are documented in specialnames statement statement is part of suite ( "blockof codea statement is either an expression or one of several constructs with keywordsuch as ifwhile or for struct sequence tuple with named elements struct sequences expose an interface similar to named tuple in that elements can either be accessed either by index or as an attribute howeverthey do not have any of the named tuple methods like _make(or _asdict(examples of struct sequences include sys float_info and the return value of os stat(text encoding codec which encodes unicode strings to bytes text file file object able to read and write str objects oftena text file actually accesses byte-oriented datastream and handles the text encoding automatically examples of text files are files opened in text mode ('ror ' ')sys stdinsys stdoutand instances of io stringio see also binary file for file object able to read and write bytes-like objects triple-quoted string string which is bound by three instances of either quotation mark ("or an apostrophe ('while they don' provide any functionality not available with single-quoted stringsthey are useful for number of reasons they allow you to include unescaped single and double quotes within string and they can span multiple lines without the use of the continuation charactermaking them especially useful when writing docstrings type the type of python object determines what kind of object it isevery object has type an object' type is accessible as its __class__ attribute or can be retrieved with type(objtype alias synonym for typecreated by assigning the type to an identifier type aliases are useful for simplifying type hints for examplefrom typing import listtuple def remove_gray_shadescolorslist[tuple[intintint]]-list[tuple[intintint]]pass could be made more readable like thisfrom typing import listtuple color tuple[intintintdef remove_gray_shades(colorslist[color]-list[color]pass see typing and pep which describe this functionality type hint an annotation that specifies the expected type for variablea class attributeor function parameter or return value type hints are optional and are not enforced by python but they are useful to static type analysis toolsand aid ides with code completion and refactoring type hints of global variablesclass attributesand functionsbut not local variablescan be accessed using typing get_type_hints(see typing and pep which describe this functionality universal newlines manner of interpreting text streams in which all of the following are recognized as ending linethe unix end-of-line convention '\ 'the windows convention '\ \ 'and the old appendix glossary |
2,211 | macintosh convention '\rsee pep and pep as well as bytes splitlines(for an additional use variable annotation an annotation of variable or class attribute when annotating variable or class attributeassignment is optionalclass cfield'annotationvariable annotations are usually used for type hintsfor example this variable is expected to take int valuescountint variable annotation syntax is explained in section annassign see function annotationpep and pep which describe this functionality virtual environment cooperatively isolated runtime environment that allows python users and applications to install and upgrade python distribution packages without interfering with the behaviour of other python applications running on the same system see also venv virtual machine computer defined entirely in software python' virtual machine executes the bytecode emitted by the bytecode compiler zen of python listing of python design principles and philosophies that are helpful in understanding and using the language the listing can be found by typing "import thisat the interactive prompt |
2,212 | appendix glossary |
2,213 | about these documents these documents are generated from restructuredtext sources by sphinxa document processor specifically written for the python documentation development of the documentation and its toolchain is an entirely volunteer effortjust like python itself if you want to contributeplease take look at the reporting-bugs page for information on how to do so new volunteers are always welcomemany thanks go tofred drakejr the creator of the original python documentation toolset and writer of much of the contentthe docutils project for creating restructuredtext and the docutils suitefredrik lundh for his alternative python reference project from which sphinx got many good ideas contributors to the python documentation many people have contributed to the python languagethe python standard libraryand the python documentation see misc/acks in the python source distribution for partial list of contributors it is only with the input and contributions of the python community that python has such wonderful documentation thank you |
2,214 | appendix about these documents |
2,215 | history and license history of the software python was created in the early by guido van rossum at stichting mathematisch centrum (cwisee principal authoralthough it includes many contributions from others in guido continued his work on python at the corporation for national research initiatives (cnrisee in may guido and the python core development team moved to beopen com to form the beopen pythonlabs team in october of the same yearthe pythonlabs team moved to digital creations (now zope corporationsee //www python org/psf/was formeda non-profit organization created specifically to own python-related intellectual property zope corporation is sponsoring member of the psf all python releases are open source (see various releases release thru thru and above derived from / year - - -now owner cwi cnri cnri beopen com cnri psf psf psf psf psf psf gpl compatibleyes yes no no no no yes yes yes yes yes notegpl-compatible doesn' mean that we're distributing python under the gpl all python licensesunlike the gpllet you distribute modified version without making your changes open source the gplcompatible licenses make it possible to combine python with other software that is released under the gplthe others don' thanks to the many outside volunteers who have worked under guido' direction to make these releases possible |
2,216 | terms and conditions for accessing or otherwise using python psf license agreement for python this license agreement is between the python software foundation ("psf")and the individual or organization ("licensee"accessing and otherwise using python software in source or binary form and its associated documentation subject to the terms and conditions of this license agreementpsf hereby grants licensee nonexclusiveroyalty-freeworld-wide license to reproduceanalyzetestperform and/or display publiclyprepare derivative worksdistributeand otherwise use python alone or in any derivative versionprovidedhoweverthat psf' license agreement and psf' notice of copyrighti "copyright ( - python software foundationall rights reservedare retained in python alone or in any derivative version prepared by licensee in the event licensee prepares derivative work that is based on or incorporates python or any part thereofand wants to make the derivative work available to others as provided hereinthen licensee hereby agrees to include in any such work brief summary of the changes made to python psf is making python available to licensee on an "as isbasis psf makes no representations or warrantiesexpress or implied by way of examplebut not limitationpsf makes no and disclaims any representation or warranty of merchantability or fitness for any particular purpose or that the use of python will not infringe any third party rights psf shall not be liable to licensee or any other users of python for any incidentalspecialor consequential damages or loss as result of modifyingdistributingor otherwise using python or any derivative thereofeven if advised of the possibility thereof this license agreement will automatically terminate upon material breach of its terms and conditions nothing in this license agreement shall be deemed to create any relationship of agencypartnershipor joint venture between psf and licensee this license agreement does not grant permission to use psf trademarks or trade name in trademark sense to endorse or promote products or services of licenseeor any third party by copyinginstalling or otherwise using python licensee agrees to be bound by the terms and conditions of this license agreement beopen com license agreement for python beopen python open source license agreement version this license agreement is between beopen com ("beopen")having an office at saratoga avenuesanta claraca and the individual or organization (continues on next page appendix history and license |
2,217 | (continued from previous page("licensee"accessing and otherwise using this software in source or binary form and its associated documentation ("the software" subject to the terms and conditions of this beopen python license agreementbeopen hereby grants licensee non-exclusiveroyalty-freeworld-wide license to reproduceanalyzetestperform and/or display publiclyprepare derivative worksdistributeand otherwise use the software alone or in any derivative versionprovidedhoweverthat the beopen python license is retained in the softwarealone or in any derivative version prepared by licensee beopen is making the software available to licensee on an "as isbasis beopen makes no representations or warrantiesexpress or implied by way of examplebut not limitationbeopen makes no and disclaims any representation or warranty of merchantability or fitness for any particular purpose or that the use of the software will not infringe any third party rights beopen shall not be liable to licensee or any other users of the software for any incidentalspecialor consequential damages or loss as result of usingmodifying or distributing the softwareor any derivative thereofeven if advised of the possibility thereof this license agreement will automatically terminate upon material breach of its terms and conditions this license agreement shall be governed by and interpreted in all respects by the law of the state of californiaexcluding conflict of law provisions nothing in this license agreement shall be deemed to create any relationship of agencypartnershipor joint venture between beopen and licensee this license agreement does not grant permission to use beopen trademarks or trade names in trademark sense to endorse or promote products or services of licenseeor any third party as an exceptionthe "beopen pythonlogos available at granted on that web page by copyinginstalling or otherwise using the softwarelicensee agrees to be bound by the terms and conditions of this license agreement cnri license agreement for python this license agreement is between the corporation for national research initiativeshaving an office at preston white driverestonva ("cnri")and the individual or organization ("licensee"accessing and otherwise using python software in source or binary form and its associated documentation subject to the terms and conditions of this license agreementcnri hereby grants licensee nonexclusiveroyalty-freeworld-wide license to reproduceanalyzetestperform and/or display publiclyprepare derivative worksdistributeand otherwise use python alone or in any derivative versionprovidedhoweverthat cnri' license agreement and cnri' notice of copyrighti "copyright ( - corporation for national research initiativesall rights reservedare retained in python alone or in any derivative version prepared by licensee alternatelyin lieu of cnri' license agreementlicensee may substitute the following text (omitting the quotes)"python is made available subject to the terms and conditions in cnri' license (continues on next pagec terms and conditions for accessing or otherwise using python |
2,218 | (continued from previous pageagreement this agreement together with python may be located on the internet using the following uniquepersistent identifier (known as handle)this agreement may also be obtained from proxy server on the internet using the following url in the event licensee prepares derivative work that is based on or incorporates python or any part thereofand wants to make the derivative work available to others as provided hereinthen licensee hereby agrees to include in any such work brief summary of the changes made to python cnri is making python available to licensee on an "as isbasis cnri makes no representations or warrantiesexpress or implied by way of examplebut not limitationcnri makes no and disclaims any representation or warranty of merchantability or fitness for any particular purpose or that the use of python will not infringe any third party rights cnri shall not be liable to licensee or any other users of python for any incidentalspecialor consequential damages or loss as result of modifyingdistributingor otherwise using python or any derivative thereofeven if advised of the possibility thereof this license agreement will automatically terminate upon material breach of its terms and conditions this license agreement shall be governed by the federal intellectual property law of the united statesincluding without limitation the federal copyright lawandto the extent such federal law does not applyby the law of the commonwealth of virginiaexcluding virginia' conflict of law provisions notwithstanding the foregoingwith regard to derivative works based on python that incorporate non-separable material that was previously distributed under the gnu general public license (gpl)the law of the commonwealth of virginia shall govern this license agreement only as to issues arising under or with respect to paragraphs and of this license agreement nothing in this license agreement shall be deemed to create any relationship of agencypartnershipor joint venture between cnri and licensee this license agreement does not grant permission to use cnri trademarks or trade name in trademark sense to endorse or promote products or services of licenseeor any third party by clicking on the "acceptbutton where indicatedor by copyinginstalling or otherwise using python licensee agrees to be bound by the terms and conditions of this license agreement cwi license agreement for python through copyright ( stichting mathematisch centrum amsterdamthe netherlands all rights reserved permission to usecopymodifyand distribute this software and its documentation for any purpose and without fee is hereby grantedprovided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentationand that the name of stichting mathematisch centrum or cwi not be used in advertising or publicity pertaining to distribution of the software without specificwritten prior permission (continues on next page appendix history and license |
2,219 | (continued from previous pagestichting mathematisch centrum disclaims all warranties with regard to this softwareincluding all implied warranties of merchantability and fitnessin no event shall stichting mathematisch centrum be liable for any specialindirect or consequential damages or any damages whatsoever resulting from loss of usedata or profitswhether in an action of contractnegligence or other tortious actionarising out of or in connection with the use or performance of this software licenses and acknowledgements for incorporated software this section is an incompletebut growing list of licenses and acknowledgements for third-party software incorporated in the python distribution mersenne twister the _random module includes code based on download from ~ -mat/mt/mt /emt ar html the following are the verbatim comments from the original codea -program for mt with initialization improved coded by takuji nishimura and makoto matsumoto before usinginitialize the state by using init_genrand(seedor init_by_array(init_keykey_lengthcopyright ( makoto matsumoto and takuji nishimuraall rights reserved redistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution the names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors "as isand any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the copyright owner or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this (continues on next pagec licenses and acknowledgements for incorporated software |
2,220 | (continued from previous pagesoftwareeven if advised of the possibility of such damage any feedback is very welcome emailm-mat math sci hiroshima- ac jp (remove spacec sockets the socket module uses the functionsgetaddrinfo()and getnameinfo()which are coded in separate source files from the wide projectcopyright ( and wide project all rights reserved redistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the project and contributors ``as is'and any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the project or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage asynchronous socket services the asynchat and asyncore modules contain the following noticecopyright by sam rushing all rights reserved permission to usecopymodifyand distribute this software and its documentation for any purpose and without fee is hereby grantedprovided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentationand that the name of sam rushing not be used in advertising or publicity pertaining to (continues on next page appendix history and license |
2,221 | (continued from previous pagedistribution of the software without specificwritten prior permission sam rushing disclaims all warranties with regard to this softwareincluding all implied warranties of merchantability and fitnessin no event shall sam rushing be liable for any specialindirect or consequential damages or any damages whatsoever resulting from loss of usedata or profitswhether in an action of contractnegligence or other tortious actionarising out of or in connection with the use or performance of this software cookie management the http cookies module contains the following noticecopyright by timothy 'malley all rights reserved permission to usecopymodifyand distribute this software and its documentation for any purpose and without fee is hereby grantedprovided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentationand that the name of timothy 'malley not be used in advertising or publicity pertaining to distribution of the software without specificwritten prior permission timothy 'malley disclaims all warranties with regard to this softwareincluding all implied warranties of merchantability and fitnessin no event shall timothy 'malley be liable for any specialindirect or consequential damages or any damages whatsoever resulting from loss of usedata or profitswhether in an action of contractnegligence or other tortious actionarising out of or in connection with the use or performance of this software execution tracing the trace module contains the following noticeportions copyright autonomous zones industriesinc all rights err reserved and offered to the public under the terms of the python license authorzooko 'whielacronx mailto:zooko@zooko com copyright mojam mediainc all rights reserved authorskip montanaro copyright bioreasoninc all rights reserved authorandrew dalke (continues on next pagec licenses and acknowledgements for incorporated software |
2,222 | (continued from previous pagecopyright - automatrixinc all rights reserved authorskip montanaro copyright - stichting mathematisch centrumall rights reserved permission to usecopymodifyand distribute this python software and its associated documentation for any purpose without fee is hereby grantedprovided that the above copyright notice appears in all copiesand that both that copyright notice and this permission notice appear in supporting documentationand that the name of neither automatrixbioreason or mojam media be used in advertising or publicity pertaining to distribution of the software without specificwritten prior permission uuencode and uudecode functions the uu module contains the following noticecopyright by lance ellinghouse cathedral citycalifornia republicunited states of america all rights reserved permission to usecopymodifyand distribute this software and its documentation for any purpose and without fee is hereby grantedprovided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentationand that the name of lance ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specificwritten prior permission lance ellinghouse disclaims all warranties with regard to this softwareincluding all implied warranties of merchantability and fitnessin no event shall lance ellinghouse centrum be liable for any specialindirect or consequential damages or any damages whatsoever resulting from loss of usedata or profitswhether in an action of contractnegligence or other tortious actionarising out of or in connection with the use or performance of this software modified by jack jansencwijuly use binascii module to do the actual line-by-line conversion between ascii and binary this results in -fold speedup the version is still times fasterthough arguments more compliant with python standard xml remote procedure calls the xmlrpc client module contains the following noticethe xml-rpc client interface is copyright ( - by secret labs ab copyright ( - by fredrik lundh by obtainingusingand/or copying this software and/or its (continues on next page appendix history and license |
2,223 | (continued from previous pageassociated documentationyou agree that you have readunderstoodand will comply with the following terms and conditionspermission to usecopymodifyand distribute this software and its associated documentation for any purpose and without fee is hereby grantedprovided that the above copyright notice appears in all copiesand that both that copyright notice and this permission notice appear in supporting documentationand that the name of secret labs ab or the author not be used in advertising or publicity pertaining to distribution of the software without specificwritten prior permission secret labs ab and the author disclaims all warranties with regard to this softwareincluding all implied warranties of merchantability and fitness in no event shall secret labs ab or the author be liable for any specialindirect or consequential damages or any damages whatsoever resulting from loss of usedata or profitswhether in an action of contractnegligence or other tortious actionarising out of or in connection with the use or performance of this software test_epoll the test_epoll module contains the following noticecopyright ( - twisted matrix laboratories permission is hereby grantedfree of chargeto any person obtaining copy of this software and associated documentation files (the "software")to deal in the software without restrictionincluding without limitation the rights to usecopymodifymergepublishdistributesublicenseand/or sell copies of the softwareand to permit persons to whom the software is furnished to do sosubject to the following conditionsthe above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided "as is"without warranty of any kindexpress or impliedincluding but not limited to the warranties of merchantabilityfitness for particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claimdamages or other liabilitywhether in an action of contracttort or otherwisearising fromout of or in connection with the software or the use or other dealings in the software select kqueue the select module contains the following notice for the kqueue interfacecopyright ( doug white james knight christian heimes all rights reserved (continues on next pagec licenses and acknowledgements for incorporated software |
2,224 | (continued from previous pageredistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution this software is provided by the author and contributors ``as is'and any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the author or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage siphash the file python/pyhash contains marek majkowskiimplementation of dan bernstein' siphash algorithm the contains the following notecopyright ( marek majkowski permission is hereby grantedfree of chargeto any person obtaining copy of this software and associated documentation files (the "software")to deal in the software without restrictionincluding without limitation the rights to usecopymodifymergepublishdistributesublicenseand/or sell copies of the softwareand to permit persons to whom the software is furnished to do sosubject to the following conditionsthe above copyright notice and this permission notice shall be included in all copies or substantial portions of the software original locationsolution inspired by code fromsamuel neves (supercop/crypto_auth/siphash /littledjb (supercop/crypto_auth/siphash /little jean-philippe aumasson ( strtod and dtoa the file python/dtoa cwhich supplies functions dtoa and strtod for conversion of doubles to and from stringsis derived from the file of the same name by david gaycurrently available from http//www netlib org/fpthe original fileas retrieved on march contains the following copyright and licensing notice appendix history and license |
2,225 | /***************************************************************the author of this software is david gay copyright ( by lucent technologies permission to usecopymodifyand distribute this software for any purpose without fee is hereby grantedprovided that this entire notice is included in all copies of any software which is or includes copy or modification of this software and in all copies of the supporting documentation for such software this software is being provided "as is"without any express or implied warranty in particularneither the author nor lucent makes any representation or warranty of any kind concerning the merchantability of this software or its fitness for any particular purpose *************************************************************** openssl the modules hashlibposixsslcrypt use the openssl library for added performance if made available by the operating system additionallythe windows and mac os installers for python may include copy of the openssl librariesso we include copy of the openssl license herelicense issues =============the openssl toolkit stays under dual licensei both the conditions of the openssl license and the original ssleay license apply to the toolkit see below for the actual license texts actually both licenses are bsd-style open source licenses in case of any license issues related to openssl please contact openssl-core@openssl org openssl license /===================================================================copyright ( - the openssl project all rights reserved redistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution all advertising materials mentioning features or use of this software must display the following acknowledgment"this product includes software developed by the openssl project for use in the openssl toolkit ((continues on next pagec licenses and acknowledgements for incorporated software |
2,226 | (continued from previous page the names "openssl toolkitand "openssl projectmust not be used to endorse or promote products derived from this software without prior written permission for written permissionplease contact openssl-core@openssl org products derived from this software may not be called "opensslnor may "opensslappear in their names without prior written permission of the openssl project redistributions of any form whatsoever must retain the following acknowledgment"this product includes software developed by the openssl project for use in the openssl toolkit (this software is provided by the openssl project ``as is'and any expressed or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the openssl project or its contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage ===================================================================this product includes cryptographic software written by eric young (eay@cryptsoft comthis product includes software written by tim hudson (tjh@cryptsoft com*original ssleay license /copyright ( - eric young (eay@cryptsoft comall rights reserved this package is an ssl implementation written by eric young (eay@cryptsoft comthe implementation was written so as to conform with netscapes ssl this library is free for commercial and non-commercial use as long as the following conditions are aheared to the following conditions apply to all code found in this distributionbe it the rc rsalhashdesetc codenot just the ssl code the ssl documentation included with this distribution is covered by the same copyright terms except that the holder is tim hudson (tjh@cryptsoft comcopyright remains eric young'sand as such any copyright notices in the code are not to be removed if this package is used in producteric young should be given attribution as the author of the parts of the library used (continues on next page appendix history and license |
2,227 | (continued from previous pagethis can be in the form of textual message at program startup or in documentation (online or textualprovided with the package redistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution all advertising materials mentioning features or use of this software must display the following acknowledgement"this product includes cryptographic software written by eric young (eay@cryptsoft com)the word 'cryptographiccan be left out if the rouines from the library being used are not cryptographic related :- if you include any windows specific code (or derivative thereoffrom the apps directory (application codeyou must include an acknowledgement"this product includes software written by tim hudson (tjh@cryptsoft com)this software is provided by eric young ``as is'and any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the author or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage the licence and distribution terms for any publically available version or derivative of this code cannot be changed this code cannot simply be copied and put under another distribution licence [including the gnu public licence * expat the pyexpat extension is built using an included copy of the expat sources unless the build is configured --with-system-expatcopyright ( thai open source software center ltd and clark cooper permission is hereby grantedfree of chargeto any person obtaining copy of this software and associated documentation files (the "software")to deal in the software without restrictionincluding without limitation the rights to usecopymodifymergepublishdistributesublicenseand/or sell copies of the softwareand to permit persons to whom the software is furnished to do sosubject to the following conditions(continues on next pagec licenses and acknowledgements for incorporated software |
2,228 | (continued from previous pagethe above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided "as is"without warranty of any kindexpress or impliedincluding but not limited to the warranties of merchantabilityfitness for particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claimdamages or other liabilitywhether in an action of contracttort or otherwisearising fromout of or in connection with the software or the use or other dealings in the software libffi the _ctypes extension is built using an included copy of the libffi sources unless the build is configured --with-system-libfficopyright ( - red hatinc and others permission is hereby grantedfree of chargeto any person obtaining copy of this software and associated documentation files (the ``software'')to deal in the software without restrictionincluding without limitation the rights to usecopymodifymergepublishdistributesublicenseand/or sell copies of the softwareand to permit persons to whom the software is furnished to do sosubject to the following conditionsthe above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided ``as is''without warranty of any kindexpress or impliedincluding but not limited to the warranties of merchantabilityfitness for particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claimdamages or other liabilitywhether in an action of contracttort or otherwisearising fromout of or in connection with the software or the use or other dealings in the software zlib the zlib extension is built using an included copy of the zlib sources if the zlib version found on the system is too old to be used for the buildcopyright ( - jean-loup gailly and mark adler this software is provided 'as-is'without any express or implied warranty in no event will the authors be held liable for any damages arising from the use of this software permission is granted to anyone to use this software for any purposeincluding commercial applicationsand to alter it and redistribute it freelysubject to the following restrictions(continues on next page appendix history and license |
2,229 | (continued from previous page the origin of this software must not be misrepresentedyou must not claim that you wrote the original software if you use this software in productan acknowledgment in the product documentation would be appreciated but is not required altered source versions must be plainly marked as suchand must not be misrepresented as being the original software this notice may not be removed or altered from any source distribution jean-loup gailly jloup@gzip org mark adler madler@alumni caltech edu cfuhash the implementation of the hash table used by the tracemalloc is based on the cfuhash projectcopyright ( don owens all rights reserved this code is released under the bsd licenseredistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are metredistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors "as isand any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the copyright owner or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage licenses and acknowledgements for incorporated software |
2,230 | libmpdec the _decimal module is built using an included copy of the libmpdec library unless the build is configured --with-system-libmpdeccopyright ( - stefan krah all rights reserved redistribution and use in source and binary formswith or without modificationare permitted provided that the following conditions are met redistributions of source code must retain the above copyright noticethis list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright noticethis list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution this software is provided by the author and contributors "as isand any express or implied warrantiesincludingbut not limited tothe implied warranties of merchantability and fitness for particular purpose are disclaimed in no event shall the author or contributors be liable for any directindirectincidentalspecialexemplaryor consequential damages (includingbut not limited toprocurement of substitute goods or servicesloss of usedataor profitsor business interruptionhowever caused and on any theory of liabilitywhether in contractstrict liabilityor tort (including negligence or otherwisearising in any way out of the use of this softwareeven if advised of the possibility of such damage appendix history and license |
2,231 | revised and updated th edition david amosdan baderjoanna jablonskifletcher heisler copyright (creal python (realpython com) - for online information and ordering of this and other books by real pythonplease visit realpython com for more informationplease contact us at info@realpython com isbn (paperbackisbn (electroniccover design by aldren santos additional editing and proofreading by jacob schmitt "pythonand the python logos are trademarks or registered trademarks of the python software foundationused by real python with permission from the foundation thank you for downloading this ebook this ebook is licensed for your personal enjoyment only this ebook may not be resold or given away to other people if you would like to share this book with another personplease purchase an additional copy for each recipient if you're reading this book and did not purchase itor if it was not purchased for your use onlythen please return to realpython com/pybasics-book and purchase your own copy thank you for respecting the hard work behind this book |
2,232 | introduction to python with the full version of the book you get complete python curriculum to go all the way from beginner to intermediate-level every step along the way is explained and illustrated with short clear code samples coding exercises within each and our interactive quizzes help fast-track your progress and ensure you always know what to focus on next become fluent pythonista and gain programming knowledge you can apply in the real-worldtodayif you enjoyed the sample you can purchase full version of the book at realpython com/pybasics-book |
2,233 | " love [the book]the wording is casualeasy to understandand makes the information ow well never feel lost in the materialand it' not too dense so it' easy for me to review older over and over 've looked at over di erent python tutorials/books/online coursesand 've probably learned the most from real python!-thomas wong "three years later and still return to my real python books when need quick refresher on usage of vital python commands -rob fowler " oundered for long time trying to teach myself slogged through dozens of incomplete online tutorials snoozed through hours of boring screencasts gave up on countless crufty books from big-time publishers and then found real python the easy-to-followstep-by-step instructions break the big concepts down into bite-sized chunks written in plain english the authors never forget their audience and are consistently thorough and detailed in their explanations ' up and running nowbut constantly refer to the material for guidance -jared nielsen |
2,234 | real world and interesting challenges just built savings estimator that actually re ects my savings account neat!-drew prescott "as practice of what you taught started building simple scripts for people on my team to help them in their everyday duties when my managers noticed thati was ered new position as developer know there is heaps of things to learn and there will be huge challengesbut nally started doing what really came to like once againmany thanks!-kamil "what found great about the real python courses compared to others is how they explain things in the simplest way possible lot of coursesin any discipline reallyrequire the learning of lot of jargon when in fact what is being taught could be taught quickly and succinctly without too much of it the courses do very good job of keeping the examples interesting -stephen grady "after reading the rst real python course wrote script to automate mundane task at work what used to take me three to ve hours now takes less than ten minutes!-brandon youngdale |
2,235 | looking really hard for things that could maybe be added or improvedbut this tutorial is amazingyou do wonderful job of explaining and teaching python in way that people like mea complete novicecould really grasp the ow of the lessons works perfectly throughout the exercises truly helped along the way and you feel very accomplished when you nish up the book think you have gift for making python seem more attainable to people outside the programming world this is something never thought would be doing or learning and with little push from you am learning it and can see that it will be nothing but bene cial to me in the future!-shea klusewicz "the authors of the courses have not forgotten what it is like to be beginner something that many authors do and assume nothing about their readerswhich makes the courses fantastic reads the courses are also accompanied by some great videos as well as plenty of references for extra learninghomework assignments and example code that you can experiment with and extend really liked that there was always full code examples and each line of code had good comments so you can see what is doing what now have number of books on python and the real python ones are the only ones have actually nished cover to coverand they are hands down the best on the market if like meyou're not programmer ( work in online marketingyou'll nd these courses to be like mentor due to the clearu -free explanationshighly recommended!-craig addyman |
2,236 | at real python you'll learn real-world programming skills from community of professional pythonistas from all around the world the realpython com website launched in and currently helps more than three million python developers each month with free programming tutorials and in-depth learning resources everyone who worked on this book is practitioner with several years of professional experience in the software industry here are the members of the real python tutorial team who worked on python basicsdavid amos is the content technical lead for real python after leaving academia in david worked in various technical positions as programmer and data scientist in david joined real python full time to pursue his passion for education he lead the charge on rewriting and updating the python basics curriculum to python dan bader is the owner and editor in chief of real python and the main developer of the realpython com learning platform dan has been writing code for more than twenty years and holds master' degree in computer science he' the author of python tricksa bestselling programming book for intermediate python developers joanna jablonski is the executive editor of real python she likes natural languages just as much as she likes programming languages her love for puzzlespatternsand pesky little details led her to follow career in translation it was only matter of time before she would fall in love with new languagepythonshe joined real python in and has been helping pythonistas level up ever since fletcher heisler is the founder of hunter where he teaches developers how to hack and secure modern web apps as one of the founding members of real pythonfletcher wrote the first version of the python curriculum this book is based on in |
2,237 | contents foreword introduction why this book about real python how to use this book bonus material and learning resources your first python program write python program mess things up create variable inspect values in the interactive window leave yourself helpful notes summary and additional resources setting up python note on python versions windows macos ubuntu linux strings and string methods what is string concatenationindexingand slicing |
2,238 | manipulate strings with methods interact with user input challengepick apart your user' input working with strings and numbers streamline your print statements find string in string challengeturn your user into summary and additional resources numbers and math integers and floating-point numbers arithmetic operators and expressions challengeperform calculations on user input make python lie to you math functions and number methods print numbers in style complex numbers summary and additional resources functions and loops what is functionreally write your own functions challengeconvert temperatures run in circles challengetrack your investments understand scope in python summary and additional resources conditional logic and control flow compare values add some logic control the flow of your program finding and fixing code bugs use the debug control window squash some bugs summary and additional resources |
2,239 | challengefind the factors of number break out of the pattern recover from errors simulate events and calculate probabilities challengesimulate coin toss experiment challengesimulate an election summary and additional resources object-oriented programming (oop define class instantiate an object inherit from other classes challengemodel farm summary and additional resources tupleslistsand dictionaries tuples are immutable sequences lists are mutable sequences nestingcopyingand sorting tuples and lists challengelist of lists challengewax poetic store relationships in dictionaries challengecapital city loop how to pick data structure challengecats with hats summary and additional resources modules and packages working with modules working with packages summary and additional resources file input and output files and the file system working with file paths in python common file system operations challengemove all image files to new directory |
2,240 | reading and writing files read and write csv data challengecreate high scores list summary and additional resources installing packages with pip installing third-party packages with pip the pitfalls of third-party packages summary and additional resources working with databases an introduction to sqlite libraries for working with other sql databases summary and additional resources creating and modifying pdf files extracting text from pdf extracting pages from pdf challengepdffilesplitter class concatenating and merging pdfs rotating and cropping pdf pages encrypting and decrypting pdfs challengeunscramble pdf creating pdf file from scratch summary and additional resources interacting with the web scrape and parse text from websites use an html parser to scrape websites interact with html forms interact with websites in real time summary and additional resources scienti computing and graphing use numpy for matrix manipulation use matplotlib for plotting graphs summary and additional resources |
2,241 | graphical user interfaces add gui elements with easygui example apppdf page rotator challengepdf page extraction application introduction to tkinter working with widgets controlling layout with geometry managers making your applications interactive example apptemperature converter example apptext editor challengereturn of the poet summary and additional resources final thoughts and next steps free weekly tips for python developers python tricksthe book real python video course library acknowledgements |
2,242 | helloand welcome to python basicsa practical introduction to python hope you're ready to learn why so many professional and hobbyist developers are drawn to python and how you can begin using it on your own projectssmall and largeright away this book is targeted at beginners who either know little programming but not the python language and ecosystem or are starting fresh with no programming experience whatsoever if you don' have computer science degreedon' worry daviddanjoannaand fletcher will guide you through the important computing concepts while teaching you the python basics andjust as importantlyskipping the unnecessary details at first python is full-spectrum language when learning new programming languageyou don' yet have the experience to judge how well it will serve you in the long run if you're considering learning pythonlet me assure you that this is good choice one key reason is that python is full-spectrum language what do mean by thissome languages are very good for beginners they hold your hand and make programming super easy we can go to the extreme and look at visual languages such as scratch in scratchyou get blocks that represent programming concepts like variablesloopsmethod callsand so onand you drag and drop them on visual surface scratch may be easy to get started with for sim |
2,243 | ple programsbut you cannot build professional applications with it name one fortune company that powers its core business logic with scratch come up emptyme toobecause that would be insanity other languages are incredibly powerful for expert developers the most popular one in this category is likely +and its close relativec whichever web browser you used today was likely written in or +your operating system running that browser was very likely also built with / +your favorite first-person shooter or strategy video gameyou nailed itc/ +you can do amazing things with these languagesbut they are wholly unwelcoming to newcomers looking for gentle introduction you might not have read lot of +code it can almost make your eyes burn here' an examplea real albeit complex onetemplate _defervoid ( ::*)(void))(const pid&void ( ::*)(void))defer(const pidpidvoid ( ::*method)(void)void (*dispatch)(const pid&void ( ::*)(void)&process::template dispatchreturn std::tr ::bind(dispatchpidmethod)pleasejust no both scratch and +are decidedly not what would call fullspectrum languages with scratchit' easy to startbut you have to switch to "reallanguage to build real applications converselyyou can build real apps with ++but there' no gentle on-ramp you dive headfirst into all the complexity of the languagewhich exists to support these rich applications |
2,244 | pythonon the other handis special it is full-spectrum language we often judge the simplicity of language based on the helloworld test that iswhat syntax and actions are necessary to get the language to output helloworld to the userin pythonit couldn' be simplerprint("helloworld"that' ithoweveri find this an unsatisfying test the helloworld test is useful but really not enough to show the power or complexity of language let' try another example not everything here needs to make total sense--just follow along to get the zen of it the book covers these concepts and more as you go through the next example is certainly something you could write as you get near the end of the book here' the new testwhat would it take to write program that accesses an external websitedownloads the content to your app in memorythen displays subsection of that content to the userlet' try that experiment using python with the help of the requests package (which needs to be installed--more on that in )import requests resp requests get("html resp text print(html[ : ]incrediblythat' itwhen runthe program outputs something like thisplease log in to access mount olympusthis is the easygetting-started side of the python spectrum few trivial lines can unleash incredible power because python has access to so many powerful but well-packaged librariessuch as requestsit' often described as having batteries included |
2,245 | so there you have simple yet powerful starter example on the realworld side of thingsmany incredible applications have been written in python as well youtubethe world' most popular video streaming siteis written in python and processes more than million requests per second instagram is another example of python application closer to homewe even have realpython com and my sitessuch as talkpython fm this full-spectrum aspect of python means that you can start with the basics and adopt more advanced features as your application demands grow python is popular you might have heard that python is popular it may seem that it doesn' really matter how popular language is so long as you can build the app you want to build with it butfor better or worsethe popularity of programming language is strong indicator of the quality of libraries you'll have available as well the number of job openings you'll find in shortyou should tend to gravitate toward more popular technologies as there will be more choices and integrations available sois python actually that popularyes it is you'll find lot of hype and hyperbolebut there are plenty of stats backing this claim let' look at some analytics presented by stackoverflow coma popular question-and-answer site for programmers stack overflow runs site called stack overflow trends where you can look at the trends for various technologies by tag when you compare |
2,246 | python to the other likely candidates you could pick to learn programmingyou'll see one is unlike the othersyou can explore this chart and create similar charts to this one over at insights stackoverflow com/trends notice the incredible growth of python compared to the flat or even downward trend of the other usual candidatesif you're betting your future on the success of given technologywhich one would you choose from this listthat' just one chart--what does it really tell uswelllet' look at another stack overflow does yearly survey of developers it' comprehensive and very well done you can find the full results at insights stackoverflow com/survey/ from that writeupi' like to call your attention to section titled "most loveddreadedand wanted languages in the "most wantedsectionyou'll find data on the share of "developers who are not developing with the language or technology but have expressed interest in developing with it |
2,247 | againin the graph belowyou'll see that python is topping the charts and is well above even second placeif you agree with me that the relative popularity of programming language mattersthen python is clearly good choice we don' need you to be computer scientist one other point that want to emphasize as you start your python learning journey is that we don' need you to be computer scientist if that' your goalthen great learning python is powerful step in that direction but the invitation to learn programming is often framed as "we have all these developer jobs going unfilledwe need software developers!that may or may not be true butmore importantlyprogramming (even little programmingcan be personal superpower for you to illustrate this ideasuppose you are biologist should you drop out of biology and get job as front-end web developerprobably not but skills such as the one opened this foreword withusing requests to get data from the webcan be incredibly powerful for you as biologist rather than manually exporting and scraping data from the web or from spreadsheetsyou can use python to scrape thousands of data sources or spreadsheets in the time it takes you to do just one man |
2,248 | ually python skills can take your biology power and amplify it well beyond your colleaguesto make it your superpower dan and real python finallylet me leave you with comment on your authors dan bader and the other real python authors work day in and day out to bring clear and powerful explanations of python concepts to all of us via realpython com they have unique view into the python ecosystem and are keyed into what beginners need to know ' confident leaving you in their hands on this python journey go forth and learn this amazing language using this great book most importantlyremember to have fun-michael kennedyfounder of talk python (@mkennedy |
2,249 | introduction welcome to real python' python basics bookfully updated for python in this bookyou'll learn real-world python programming techniquesillustrated with useful and interesting examples whether you're new programmer or professional software developer looking to dive into new languagethis book will teach you all the practical python that you need to get started on projects of your own no matter what your ultimate goals may beif you work with computer at allthen you'll soon be finding endless ways to improve your life by automating tasks and solving problems through python programs that you create but what' so great about python as programming languagefor onepython is open source freewaremeaning you can download it for free and use it for any purposecommercial or not python also has an amazing community that has built number of useful tools that you can use in your own programs need to work with pdf documentsthere' comprehensive tool for that want to collect data from web pagesno need to start from scratch |
2,250 | python was built to be easier to use than other programming languages it' usually much easier to read python code and much faster to write code in python than in other languages for instancehere' some basic code written in canother commonly used programming language#include int main(voidprintf("helloworld\ ")all the program does is show the text helloworld on the screen that was lot of work to output one phrasehere' the same program written in pythonprint("helloworld"that' pretty simplerightthe python code is faster to write and easier to read we find that it looks friendlier and more approachabletooat the same timepython has all the functionality of other languages and more you might be surprised by how many professional products are built on python codeinstagramyoutuberedditspotifyto name just few python is not only friendly and fun language to learnbut it also powers the technology behind multiple world-class companies and offers fantastic career opportunities for any programmer who masters it why this booklet' face itthere' an overwhelming amount of information about python on the internet but many beginners studying on their own have trouble figuring out what to learn and in what order to learn it |
2,251 | you may be asking yourselfwhat should learn about python in the beginning to get strong foundationif sothen this book is for youno matter if you're complete beginner or if you've already dabbled in python or other languages python basics is written in plain english and breaks down the core concepts that you really need to know into bite-sized chunks this means you'll learn enough to be dangerous with pythonfast instead of just going through boring list of language featuresyou'll see exactly how the different building blocks fit together and what' involved in building real applications and scripts with python step by stepyou'll master fundamental python concepts that will help you get started on your journey toward learning python many programming books try to cover every last possible variation of every commandwhich makes it easy for readers to get lost in the details this approach is great if you're looking for reference manualbut it' horrible way to learn programming language not only do you spend most of your time cramming things into your head that you'll never usebut you also don' have any funthis book is built on the / principlewhich suggests that you can learn most of what you need to know by focusing on few crucial concepts we'll cover the commands and techniques used in the vast majority of cases and focus on how to program real-world solutions to everyday problems this waywe guarantee that you willlearn useful programming techniques quickly spend less time struggling with unimportant complications find more practical uses for python in your own life have more fun in the process |
2,252 | once you've mastered the material in this bookyou will have gained strong enough foundation that venturing out on your own into more advanced territory will be breeze what you'll learn here is based on the first part of the original real python course initially released in over the yearsthis python curriculum has been battle-tested by thousands of pythonistasdata scientistsand developers working for companies big and smallincluding amazonred hatand microsoft for python basicswe've thoroughly expandedrefinedand updated the material so you can build your python skills quickly and efficiently about real python at real pythonyou'll learn real-world programming skills from community of professional pythonistas from all around the world the realpython com website launched in and currently helps more than three million python developers each month with booksprogramming tutorialsand other in-depth learning resources everyone who worked on this book is python practitioner recruited from the real python team with several years of professional experience in the software industry here' where you can find real python on the webrealpython com @realpython on twitter the real python newsletter the real python podcast |
2,253 | how to use this book how to use this book the first half of this book is quick but thorough overview of all the python fundamentals you don' need any prior experience with programming to get started the second half is focused on finding practical solutions to interestingreal-world coding problems if you're beginnerthen we recommend that you go through the first half of this book from beginning to end the second half covers topics that don' overlap as muchso you can jump around more easilybut the do increase in difficulty as you go along if you're more experienced programmerthen you may find yourself heading toward the second part of the book right away but don' neglect getting strong foundation in the basics firstand be sure to fill in any knowledge gaps along the way most sections within are followed by review exercises to help you make sure that you've mastered all the topics covered there are also number of code challengeswhich are more involved and usually require you to tie together several different concepts from previous the practice files that accompany this book also include full solutions to the challenges as well as some of the trickier exercises but to get the most out of the materialyou should try your best to solve the challenge problems on your own before looking at the example solutions if you're completely new to programmingthen you may want to supplement the first few with additional practice we recommend working through the entry-level tutorials available for free at realpython com to make sure you're on solid footing if you have any questions or feedback about the bookyou're always welcome to contact us directly |
2,254 | learning by doing this book is all about learning by doingso be sure to actually type in the code snippets you encounter in the book for best resultswe recommend that you avoid copying and pasting the code examples you'll learn the concepts better and pick up the syntax faster if you type out each line of code yourself plusif you screw up--which is totally normal and happens to all developers on daily basis--the simple act of correcting typos will help you learn how to debug your code try to complete the review exercises and code challenges on your own before getting help from outside resources with enough practiceyou'll master this material--and have fun along the wayhow long will it take to finish this bookif you're already familiar with programming languagethen you could finish this book in as little as thirty-five to forty hours if you're new to programmingthen you may need to spend up to one hundred hours or more take your time and don' feel like you have to rush programming is super-rewarding but complex skill to learn good luck on your python journey we're rooting for you bonus material and learning resources this book comes with number of free bonus resources and downloads that you can access online at the link below we're also maintaining an errata list with corrections thererealpython com/python-basics/resources |
2,255 | interactive quizzes most in this book come with free online quiz to check your learning progress you can access the quizzes using the links provided at the end of the the quizzes are hosted on the real python website and can be viewed on your phone or computer each quiz takes you through series of questions related to particular in the book some of them are multiple choicesome will ask you to type in an answerand some will require you to write actual python code as you make your way through each quizit will keep score of which questions you answered correctly at the end of the quizyou'll receive grade based on your result if you don' score percent on your first trydon' fretthese quizzes are meant to challenge you it' expected that you'll go through them several timesimproving your score with each run exercises code repository this book has an accompanying code repository on the web containing example source code as well as the answers to exercises and code challenges the repository is broken up by so you can check your code against the solutions provided by us after you finish each here' the linkrealpython com/python-basics/exercises note the code found in this book has been tested with python on windowsmacosand linux |
2,256 | example code license the example python scripts associated with this book are licensed under creative commons public domain (cc license this means that you're welcome to use any portion of the code for any purpose in your own programs formatting conventions code blocks will be used to present example codethis is python codeprint("helloworld"terminal commands follow the unix formatthis is terminal commandpython hello-world py (the dollar signs are not part of the command monospace text will be used to denote filenamehello-world py bold text will be used to denote new or important term keyboard shortcuts will be formatted as followsctrl menu shortcuts will be formatted as followsfile new file notes and important information will be highlighted as followsnote this is note filled in with placeholder text the quick brown fox jumps over the lazy dog the quick brown python slithers over the lazy hog |
2,257 | feedback and errata we welcome ideassuggestionsfeedbackand the occasional rant did you find topic confusingdid you find an error in the text or codedid we leave out topic that you' love to know more aboutwe're always looking to improve our teaching materials whatever the reasonplease send in your feedback at the link belowrealpython com/python-basics/feedback |
2,258 | setting up python this book is about programming computers with python you could read this book from cover to cover without ever touching keyboardbut you' miss out on the fun part--codingto get the most out of this bookyou need computer with python installed on it and way to createeditand save python code files in this you'll learn how toinstall the latest version of python on your computer open idlepython' built-in integrated development and learning environment let' get started |
2,259 | note on python versions note on python versions many operating systemsincluding macos and linuxcome with python preinstalled the version of python that comes with your operating system is called the system python the system python is used by your operating system and is usually out of date it' essential that you have the most recent version of python so that you can successfully follow along with the examples in this book important do not attempt to uninstall the system pythonyou can have multiple versions of python installed on your computer in this you'll install the latest version of python alongside any system python that may already exist on your machine note even if you already have python installedit' still good idea to skim this to double-check that your environment is set up for following along with this book this is split into three sectionswindowsmacosand ubuntu linux find the section for your operating system and follow the steps to get set upthen skip ahead to the next if you have different operating systemthen check out real python' "python installation setup guideto see if your os is covered readers on tablets and mobile devices can refer to the "online python interpreterssection for some browser-based options |
2,260 | windows follow these steps to install python and open idle on windows important the code in this book is tested only against python installed as described in this section be aware that if you have installed python through some other meanssuch as anaconda pythonyou may encounter problems when running some of the code examples install python windows doesn' typically come with system python fortunatelyinstallation involves little more than downloading and running the python installer from the python org website step download the python installer open web browser and navigate to the following urlclick latest python release python located beneath the "python releases for windowsheading near the top of the page as of this writingthe latest version was python then scroll to the bottom and click windows - executable installer to start the download note if your system has -bit processorthen you should choose the -bit installer if you aren' sure if your computer is -bit or -bitstick with the -bit installer mentioned above |
2,261 | step run the installer open your downloads folder in windows explorer and double-click the file to run the installer dialog that looks like the following one will appearit' okay if the python version you see is greater than as long as the version is not less than important make sure you select the box that says add python to path if you install python without selecting this boxthen you can run the installer again and select it click install now to install python wait for the installation to finishthen continue to open idle |
2,262 | open idle you can open idle in two steps click the start menu and locate the python folder open the folder and select idle (python idle opens python shell in new window the python shell is an interactive environment that allows you to type in python code and execute it immediately it' great way to get started with pythonnote while you're free to use code editor other than idle if you prefernote that some especially "finding and fixing code bugs,do contain material specific to idle the python shell window looks like thisat the top of the windowyou can see the version of python that is running and some information about the operating system if you see version less than then you may need to revisit the installation instructions in the previous section |
2,263 | the symbol that you see is called prompt whenever you see thisit means that python is waiting for you to give it some instructions interactive quiz this comes with free online quiz to check your learning progress you can access the quiz using your phone or computer at the following web addressrealpython com/quizzes/pybasics-setup now that you have python installedlet' get straight into writing your first python programgo ahead and move on to macos follow these steps to install python and open idle on macos important the code in this book is tested only against python installed as described in this section be aware that if you have installed python through some other meanssuch as anaconda pythonyou may encounter problems when running some of the code examples install python to install the latest version of python on macosdownload and run the official installer from the python org website step download the python installer open web browser and navigate to the following url |
2,264 | click latest python release python located beneath the "python releases for mac os xheading near the top of the page as of this writingthe latest version was python then scroll to the bottom of the page and click macos -bit installer to start the download step run the installer open finder and double-click the downloaded file to run the installer dialog box that looks like the following will appearpress continue few times until you are asked to agree to the software license agreement then click agree you'll be shown window that tells you where python will be installed and how much space it will take you most likely don' want to change the default locationso go ahead and click install to start the installation |
2,265 | when the installer is finished copying filesclick close to close the installer window open idle you can open idle in three steps open finder and click applications double-click the python folder double-click the idle icon idle opens python shell in new window the python shell is an interactive environment that allows you to type in python code and execute it immediately it' great way to get started with pythonnote while you're free to use code editor other than idle if you prefernote that some especially "finding and fixing code bugs,do contain material specific to idle the python shell window looks like this |
2,266 | at the top of the windowyou can see the version of python that is running and some information about the operating system if you see version less than then you may need to revisit the installation instructions in the previous section the symbol that you see is called prompt whenever you see thisit means that python is waiting for you to give it some instructions interactive quiz this comes with free online quiz to check your learning progress you can access the quiz using your phone or computer at the following web addressrealpython com/quizzes/pybasics-setup now that you have python installedlet' get straight into writing your first python programgo ahead and move on to ubuntu linux follow these steps to install python and open idle on ubuntu linux important the code in this book is tested only against python installed as described in this section be aware that if you have installed python through some other meanssuch as anaconda pythonyou may encounter problems when running some of the code examples |
2,267 | install python there' good chance that your ubuntu distribution already has python installedbut it probably won' be the latest versionand it may be python instead of python to find out what version(syou haveopen terminal window and try the following commandspython --version python --version one or more of these commands should respond with versionas belowpython --version python your version number may vary if the version shown is python or version of python that is less than then you want to install the latest version how you install python on ubuntu depends on which version of ubuntu you're running you can determine your local ubuntu version by running the following commandlsb_release - no lsb modules are available distributor idubuntu descriptionubuntu lts release codenamebionic look at the version number next to release in the console outputand follow the corresponding instructions below |
2,268 | ubuntu or greater ubuntu version does not come with python by defaultbut it is in the universe repository you can install it with the following commands in the terminal applicationsudo apt-get update sudo apt-get install python idle-python python -pip note that because the universe repository is usually behind the python release scheduleyou may not get the latest version of python howeverany version of python will work for this book ubuntu and lower for ubuntu versions and lowerpython is not in the universe repository you need to get it from personal package archive (ppato install python from the deadsnakes pparun the following commands in the terminal applicationsudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install python idle-python python -pip you can check that the correct version of python was installed by running python --version if you see version number less than then you may need to type python --version now you can open idle and get ready to write your first python program open idle you can open idle from the command line by typing the followingidle-python |
2,269 | on some linux installationsyou can open idle with the following shortened commandidle idle opens python shell in new window the python shell is an interactive environment that allows you to type in python code and execute it immediately it' great way to get started with pythonnote while you're free to use code editor other than idle if you prefernote that some especially "finding and fixing code bugs,do contain material specific to idle the python shell window looks like thisat the top of the windowyou can see the version of python that is running and some information about the operating system if you see version less than then you may need to revisit the installation instructions in the previous section |
2,270 | important if you open idle with the idle command and see version less than displayed in the python shell windowthen you'll need to open idle with the idle-python command the symbol that you see in the idle window is called prompt whenever you see thisit means that python is waiting for you to give it some instructions interactive quiz this comes with free online quiz to check your learning progress you can access the quiz using your phone or computer at the following web addressrealpython com/quizzes/pybasics-setup now that you have python installedlet' get straight into writing your first python programgo ahead and move on to |
2,271 | your first python program now that you have the latest version of python installed on your computerit' time to start codingin this you willwrite your first python program learn what happens when you run program with an error learn how to declare variable and inspect its value learn how to write comments ready to begin your python journeylet' go |
2,272 | write python program write python program if you don' already have idle openthen go ahead and open it there are two main windows that you'll work with in idlethe interactive windowwhich is the one that opens when you start idleand the editor window you can type code into both the interactive window and the editor window the difference between the two windows is in how they execute code in this sectionyou'll learn how to execute python code in both windows the interactive window idle' interactive window contains python shellwhich is textual user interface used to interact with the python language you can type bit of python code into the interactive window and press enter to immediately see the results hence the name interactive window the interactive window opens automatically when you start idle you'll see the following textwith some minor differences depending on your setupdisplayed at the top of the windowpython (tags/ : [msc bit (intel)on win type "help""copyright""creditsor "licensefor more information this text shows the version of python that idle is running you can also see information about your operating system and some commands you can use to get help and view information about python the symbol in the last line is called the prompt this is where you'll type in your code |
2,273 | go ahead and type at the prompt and press enter python evaluates the expressiondisplays the result ( )then displays another prompt every time you run some code in the interactive windowa new prompt appears directly below the result executing python in the interactive window can be described as loop with three steps python reads the code entered at the prompt python evaluates the code python prints the result and waits for more input this loop is commonly referred to as read-evaluate-print loop and is abbreviated as repl python programmers sometimes refer to the python shell as the python replor just "the replfor short let' try something little more interesting than adding numbers rite of passage for every programmer is writing program that prints the phrase "helloworldon the screen at the prompt in the interactive windowtype the word print followed by set of parentheses with the text "helloworldinsideprint("helloworld"helloworld |
2,274 | function is code that performs some task and can be invoked by name the above code invokesor callsthe print(function with the text "helloworldas input the parentheses tell python to call the print(function they also enclose everything that gets sent to the function as input the quotation marks indicate that "helloworldreally is text and not something else note idle highlights parts of your code in different colors as you type to make it easier for you to identify the different parts by defaultfunctions are highlighted in purple and text is highlighted in green the interactive window executes single line of code at time this is useful for trying out small code examples and exploring the python languagebut it has major limitationyou have to enter your code one line at timealternativelyyou can save python code in text file and execute all of the code in the file to run an entire program the editor window you'll write your python files using idle' editor window you can open the editor window by selecting file new file from the menu at the top of the interactive window the interactive window stays open when you open the editor window it displays the output generated by code in the editor windowso you'll want to arrange the two windows so that you can see them both at the same time |
2,275 | in the editor windowtype in the same code you used to print "helloworldin the interactive windowprint("helloworld"idle highlights code typed into the editor window just like in the interactive window important when you write code in python fileyou don' need to include the prompt before you run your programyou need to save it select file from the menu and save the file as hello_world py save note on some systemsthe default directory for saving files in idle is the python installation directory do not save your files to this directory insteadsave them to your desktop or to folder in your user' home directory the py extension indicates that file contains python code in factsaving your file with any other extension removes the code highlighting idle only highlights python code when it' stored in py file running python programs in the editor window to run your programselect run editor window run module from the menu in the note pressing also runs program from the editor window program output always appears in the interactive window |
2,276 | every time you run code from fileyou'll see something like the following output in the interactive window==================restart ==================idle restarts the python interpreterwhich is the computer program that actually executes your codeevery time you run file this makes sure that programs are executed the same way each time opening python files in the editor window to open an existing file in idleselect file open from the menuthen select the file you want to open idle opens every file in new editor windowso you can have several files open at the same time you can also open file from file managersuch as windows explorer or macos finder right-click the file icon and select edit with idle to open the file in idle' editor window double-clicking on py file from file manager executes the program howeverthis usually runs the file with the system pythonand the program window disappears immediately after the program terminates--often before you can even see any output for nowthe best way to run your python programs is to open them in idle' editor window and run them from there mess things up everybody makes mistakes--especially while programmingin case you haven' made any mistakes yetlet' get head start and mess something up on purpose to see what happens mistakes in programs are called errors you'll experience two main types of errorssyntax errors and runtime errors |
2,277 | syntax errors syntax error occurs when you write code that isn' allowed in the python language let' create syntax error by removing the last quotation mark from the code in the hello_world py file that you created in the last sectionprint("helloworldsave the file and press to run it the code won' runidle displays an alert box with the following messageeol while scanning string literal there are two terms in this message that may be unfamiliar string literal is text enclosed in quotation marks worldis string literal "hello eol stands for end of line sothe message tells you that python got to the end of line while reading string literal string literals must be terminated with quotation mark before the end of line idle highlights the line containing print("helloworldin red to help you quickly find the line of code with the syntax error without the second quotation markeverything after the first quotation mark-including the closing parenthesis--is part of string literal runtime errors idle catches syntax errors before program starts running in contrastruntime errors only occur while program is running to generate runtime errorremove both quotation marks in the hello_world py file |
2,278 | print(helloworlddid you notice how the text color changed to black when you removed the quotation marksidle no longer recognizes helloworld as text what do you think will happen when you run the programpress to find outthe following text displays in red in the interactive windowtraceback (most recent call last)file "/home/hello_world py"line in print(helloworldnameerrorname 'hellois not defined whenever an error occurspython stops executing the program and displays several lines of text called traceback the traceback shows useful information about the error tracebacks are best read from the bottom upthe last line of the traceback tells you the name of the error and the error message in this casea nameerror occurred because the name hello is not defined anywhere the second to last line shows you the code that produced the error there' only one line of code in hello_world pyso it' not hard to guess where the problem is this information is more helpful for larger files the third to last line tells you the name of the file and the line number so you can go to the exact spot in your code where the error occurred in the next sectionyou'll see how to define names for values in your code before you move onthoughyou can get some practice with syntax errors and runtime errors by working on the review exercises |
2,279 | review exercises you can nd the solutions to these exercises and many other bonus resources online at realpython com/python-basics/resources write program that idle won' run because it has syntax error write program that crashes only while it' running because it has runtime error create variable in pythonvariables are names that can be assigned value and then used to refer to that value throughout your code variables are fundamental to programming for two reasons variables keep values accessiblefor exampleyou can assign the result of some time-consuming operation to variable so that your program doesn' have to perform the operation each time you need to use the result variables give values contextthe number could mean lots of different thingssuch as the number of students in classthe number of times user has accessed websiteand so on giving the value name like num_students makes the meaning of the value clear in this sectionyou'll learn how to use variables in your codeas well as some of the conventions python programmers follow when choosing names for variables the assignment operator an operator is symbolsuch as +that performs an operation on one or more values for examplethe operator takes two numbersone to the left of the operator and one to the rightand adds them together |
2,280 | values are assigned to variable names using special symbol called the assignment operator (=the operator takes the value to the right of the operator and assigns it to the name on the left let' modify the hello_world py file from the previous section to assign some text in variable before printing it to the screengreeting "helloworldprint(greetinghelloworld on the first lineyou create variable named greeting and assign it the value "helloworldusing the operator print(greetingdisplays the output helloworld because python looks for the name greetingfinds that it' been assigned the value "helloworld"and replaces the variable name with its value before calling the function if you hadn' executed greeting "helloworldbefore executing print(greeting)then you would have seen nameerror like you did when you tried to execute print(helloworldin the previous section note although looks like the equals sign from mathematicsit has different meaning in python this distinction is important and can be source of frustration for beginner programmers just rememberwhenever you see the operatorwhatever is to the right of it is being assigned to variable on the left variable names are case sensitiveso variable named greeting is not the same as variable named greeting for instancethe following code produces nameerror |
2,281 | greeting "helloworldprint(greetingtraceback (most recent call last)file ""line in nameerrorname 'greetingis not defined if you have trouble with an example in this bookdouble-check that every character in your code--including spaces--matches the example exactly computers have no common senseso being almost correct isn' good enoughrules for valid variable names variable names can be as long or as short as you likebut there are few rules that you must follow variable names may contain uppercase and lowercase letters ( -za- )digits ( - )and underscores ( )but they cannot begin with digit for exampleeach of the following is valid python variable namestring _a list_of_names the following aren' valid variable names because they start with digit lives _balloons beornot be in addition to english letters and digitspython variable names may contain many different valid unicode characters unicode is standard for digitally representing characters used in most of the world' writing systems that means variable names can contain letters from non-english alphabetssuch as decorated letters |
2,282 | like and uand even chinesejapaneseand arabic symbols howevernot every system can display decorated charactersso it' good idea to avoid them if you're going to share your code with people in different regions note you'll learn more about unicode in you can also read about python' support for unicode in the official python documentation just because variable name is valid doesn' necessarily mean that it' good name choosing good name for variable can be surprisingly difficult fortunatelythere are some guidelines that you can follow to help you choose better names descriptive names are better than short names descriptive variable names are essentialespecially for complex programs writing descriptive names often requires using multiple words don' be afraid to use long variable names in the following examplethe value is assigned to the variable ss the name is totally ambiguous using full word makes it lot easier to understand what the code meansseconds |
2,283 | seconds is better name than because it provides more context but it still doesn' convey the full meaning of the code is the number of seconds it takes for process to finishor is it the length of moviethere' no way to tell the following name leaves no doubt about what the code meansseconds_per_hour when you read the above codethere' no question that is the number of seconds in an hour seconds_per_hour takes longer to type than both the single letter and the word secondsbut the payoff in clarity is massive although naming variables descriptively means using longer variable namesyou should avoid using excessively long names good rule of thumb is to limit variable names to three or four words maximum python variable naming conventions in many programming languagesit' common to write variable names in mixedcase in this systemyou capitalize the first letter of every word except the first and leave all other letters in lowercase for examplenumstudents and listofnames are written in mixedcase in pythonhoweverit' more common to write variable names in lower_case_with_underscores in this systemyou leave every letter in lowercase and separate each word with an underscore for instanceboth num_students and list_of_names are written using the lower_case_with_underscores system there' no rule mandating that you write your variable names in lower_case_with_underscores the practice is codifiedthoughin document called pep which is widely regarded as the official style guide for writing python |
2,284 | note pep stands for python enhancement proposal pep is design document used by the python community to propose new features to the language following the standards outlined in pep ensures that your python code is readable by most python programmers this makes sharing code and collaborating with other people easier for everyone involved review exercises you can nd the solutions to these exercises and many other bonus resources online at realpython com/python-basics/resources using the interactive windowdisplay some text using print( using the interactive windowassign string literal to variable then print the contents of the variable using the print(function repeat the first two exercises using the editor window inspect values in the interactive window type the following into idle' interactive windowgreeting "helloworldgreeting 'helloworldwhen you press enter after typing greeting second timepython prints the string literal assigned to greeting even though you didn' use the print(function this is called variable inspection |
2,285 | now print the string assigned to greeting using the print(functionprint(greetinghelloworld can you spot the difference between the output displayed by using print(and the output displayed by just entering the variable name and pressing enter when you type the variable name greeting and press enter python prints the value assigned to the variable as it appears in your code you assigned the string literal "helloworldto greetingwhich is why 'helloworldis displayed with quotation marks note string literals can be created with single or double quotation marks in python at real pythonwe use double quotes wherever possiblewhereas idle output appears in single quotes by default both "helloworldand 'helloworldmean the same thing in python--what' most important is that you be consistent in your usage you'll learn more about strings in on the other handprint(displays more human-readable representation of the variable' value whichfor string literalsmeans displaying the text without quotation marks sometimesboth printing and inspecting variable produce the same outputx print( |
2,286 | hereyou assign the number to both using print(xand inspecting display output without quotation marks because is number and not text in most casesthoughvariable inspection gives you more useful information than print(suppose you have two variablesxwhich is assigned the number and ywhich is assigned the string literal " in this caseprint(xand print(yboth display the same thingx " print( print( howeverinspecting and shows the difference between each variable' valuex ' the key takeaway here is that print(displays readable representation of variable' valuewhile variable inspection displays the value as it appears in the code keep in mind that variable inspection works only in the interactive window for exampletry running the following program from the editor windowgreeting "helloworldgreeting the program executes without any errorsbut it doesn' display any output |
2,287 | leave yourself helpful notes programmers sometimes read code they wrote while ago and wonder"what does this do?when you haven' looked at code in whileit can be difficult to remember why you wrote it the way you didto help avoid this problemyou can leave comments in your code comments are lines of text that don' affect the way program runs they document what code does or why the programmer made certain decisions how to write comment the most common way to write comment is to begin new line in your code with the character when you run your codepython ignores lines starting with comments that start on new line are called block comments you can also write inline commentswhich are comments that appear on the same line as the code they reference just put at the end of the line of codefollowed by the text in your comment here' an example of program with both kinds of commentsthis is block comment greeting "helloworldprint(greetingthis is an inline comment of courseyou can still use the symbol inside string for instancepython won' mistake the following for the start of commentprint("# "# in generalit' good idea to keep comments as short as possiblebut sometimes you need to write more than reasonably fits on single line in that caseyou can continue your comment on new line that also begins with the symbol |
2,288 | this is my first program it prints the phrase "helloworldthe comments are longer than the codegreeting "helloworldprint(greetingyou can also use comments to comment out code while you're testing program putting at the beginning of line of code lets you run your program as if that line of code didn' existbut it doesn' actually delete the code to comment out section of code in idlehighlight one or more lines to be commented and presswindowsalt macosctrl ubuntu linuxctrl to remove commentshighlight the commented lines and presswindowsalt macosctrl ubuntu linuxctrl shift now let' look at some common conventions for code comments conventions and pet peeves according to pep comments should always be written in complete sentences with single space between the and the first word of the commentthis comment is formatted to pep #this one isn' for inline commentspep recommends at least two spaces between |
2,289 | the code and the symbolphrase "helloworldthis comment is pep compliant print(phrase)this comment isn' pep recommends that comments be used sparingly major pet peeve among programmers is comments that describe what is already obvious from reading the code for examplethe comment in the following code is unnecessaryprint "helloworldprint("helloworld"the comment is unnecessary because the code itself explicitly describes what' happening comments are best used to clarify code that may be difficult to understand or to explain why something is coded certain way summary and additional resources in this you wrote and executed your first python programyou wrote small program that displays the text "helloworldusing the print(function then you learned about syntax errorswhich occur before idle executes program that contains invalid python codeand runtime errorswhich only occur while program is running you saw how to assign values to variables using the assignment operator (=and how to inspect variables in the interactive window finallyyou learned how to write helpful comments in your code for when you or someone else looks at it in the future |
2,290 | interactive quiz this comes with free online quiz to check your learning progress you can access the quiz using your phone or computer at the following web addressrealpython com/quizzes/pybasics-first-program additional resources to learn morecheck out the following resources" beginner tips for learning python programming"writing comments in python (guide)for links and additional resources to further deepen your python skillsvisit realpython com/python-basics/resources |
2,291 | strings and string methods many programmersregardless of their specialtydeal with text on daily basis for exampleweb developers work with text input from web forms data scientists process text to extract data and perform tasks like sentiment analysiswhich can help identify and classify opinions in body of text collections of text in python are called strings special functions called string methods are used to manipulate strings there are string methods for changing string from lowercase to uppercaseremoving whitespace from the beginning or end of stringreplacing parts of string with different textand much more in this you'll learn how tomanipulate strings with string methods work with user input deal with strings of numbers format strings for printing let' get started |
2,292 | what is string what is stringin you created the string "helloworldand printed it in idle' interactive window using print(in this sectionyou'll get deeper look into exactly what strings are and the various ways you can create them in python the string data type strings are one of the fundamental python data types the term data type refers to what kind of data value represents strings are used to represent text note there are several other data types built into python for exampleyou'll learn about numerical data types in and boolean data types in we say that strings are fundamental data type because they can' be broken down into smaller values of different type not all data types are fundamental you'll learn about compound data typesalso known as data structuresin the string data type has special abbreviated name in pythonstr you can see this by using type()which is function used to determine the data type of given value type the following into idle' interactive windowtype("helloworld"the output indicates that the value "helloworldis an instance of the str data type that is"helloworldis string |
2,293 | note for nowyou can think of the word class as synonym for data typealthough it actually refers to something more specific you'll see just what class is in type(also works for values that have been assigned to variablephrase "helloworldtype(phrasestrings have three important properties strings contain individual letters or symbols called characters strings have lengthdefined as the number of characters the string contains characters in string appear in sequencewhich means that each character has numbered position in the string let' take closer look at how strings are created string literals as you've already seenyou can create string by surrounding some text with quotation marksstring 'helloworldstring " you can use either single quotes (string or double quotes (string to create string as long as you use the same type at the beginning and end of the string whenever you create string by surrounding text with quotation marksthe string is called string literal the name indicates that the string is literally written out in your code all the strings you've seen thus far are string literals |
2,294 | note not every string is string literal sometimes strings are input by user or read from file since they're not typed out with quotation marks in your codethey're not string literals the quotes surrounding string are called delimiters because they tell python where string begins and where it ends when one type of quotes is used as the delimiterthe other type can be used inside the stringstring "we're # !string ' said"put it over by the llama "after python reads the first delimiterit considers all the characters after it part of the string until it reaches second matching delimiter this is why you can use single quote in string delimited by double quotesand vice versa if you try to use double quotes inside string delimited by double quotesyou'll get an errortext "she said"what time is it?"file ""line text "she said"what time is it?"syntaxerrorinvalid syntax python throws syntaxerror because it thinks the string ends after the second "and it doesn' know how to interpret the rest of the line if you need to include quotation mark that matches the delimiter inside stringthen you can escape the character using backslashtext "she said\"what time is it?\"print(textshe said"what time is it? |
2,295 | note when you work on projectit' good idea to use only single quotes or only double quotes to delimit every string keep in mind that there really isn' right or wrong choicethe goal is to be consistent because consistency helps make your code easier to read and understand strings can contain any valid unicode character for examplethe string "we're # !contains the pound sign (#and " contains numbers "xpythongxis also valid python stringdetermine the length of string the number of characters contained in stringincluding spacesis called the length of the string for examplethe string "abchas length of and the string "don' panichas length of python has built-in len(function that you can use to determine the length of string to see how it workstype the following into idle' interactive windowlen("abc" you can also use len(to get the length of string that' assigned to variableletters "abclen(letters firstyou assign the string "abcto the variable letters then you use len(to get the length of letterswhich is |
2,296 | multiline strings the pep style guide recommends that each line of python code contain no more than seventy-nine characters--including spaces note pep ' seventy-nine-character line length is recommendationnot rule some python programmers prefer slightly longer line length in this bookwe'll strictly follow pep ' recommended line length whether you follow pep or choose longer line lengthsometimes you'll need to create string literals with more characters than your chosen limit to deal with long stringsyou can break them up across multiple lines into multiline strings for examplesuppose you need to fit the following text into string literalthis planet has--or rather had-- problemwhich was thismost of the people living on it were unhappy for pretty much of the time many solutions were suggested for this problembut most of these were largely concerned with the movements of small green pieces of paperwhich is odd because on the whole it wasn' the small green pieces of paper that were unhappy -douglas adamsthe hitchhiker' guide to the galaxy this paragraph contains far more than seventy-nine charactersso any line of code containing the paragraph as string literal violates pep sowhat do you dothere are couple of ways to tackle this one way is to break the string up across multiple lines and put backslash (\at the end of all but the |
2,297 | last line to be pep compliantthe total length of the lineincluding the backslashesmust be seventy-nine characters or fewer here' how you could write the paragraph as multiline string using the backslash methodparagraph "this planet has--or rather had-- problemwhich was thismost of the people living on it were unhappy for pretty much of the time many solutions were suggested for this problembut most of these were largely concerned with the movements of small green pieces of paperwhich is odd because on the whole it wasn' the small green pieces of paper that were unhappy notice that you don' have to close each line with quotation mark normallypython would get to the end of the first line and complain that you didn' close the string with matching double quote with backslash at the endyou can keep writing the same string on the next line when you print( multiline string that' broken up by backslashesthe output is displayed on single linelong_string "this multiline string is displayed on one lineprint(long_stringthis multiline string is displayed on one line you can also create multiline strings using triple quotes (""or '''as delimiters here' how to write long paragraph using this approachparagraph """this planet has--or rather had-- problemwhich was thismost of the people living on it were unhappy for pretty much of the time many solutions were suggested for this problembut most of these were largely concerned with the movements of small green pieces of paperwhich is odd because on the whole it wasn' the small green pieces of paper that were unhappy "" |
2,298 | triple-quoted strings preserve whitespaceincluding newlines this means that running print(paragraphwould display the string on multiple linesjust as it appears in the string literal this may or may not be what you wantso you'll need to think about the desired output before you choose how to write multiline string to see how whitespace is preserved in triple-quoted stringtype the following into idle' interactive windowprint("""an example of string that spans across multiple lines and also preserves whitespace """an example of string that spans across multiple lines and also preserves whitespace notice how the second and third lines in the output are indented in exactly the same way as the string literal review exercises you can nd the solutions to these exercises and many other bonus resources online at realpython com/python-basics/resources print string that uses double quotation marks inside the string print string that uses an apostrophe inside the string print string that spans multiple lines with whitespace preserved print string that is coded on multiple lines but gets printed on single line concatenationindexingand slicing now that you know what string is and how to declare string literals in your codelet' explore some of the things you can do with strings |
2,299 | in this sectionyou'll learn about three basic string operations concatenationwhich joins two strings together indexingwhich gets single character from string slicingwhich gets several characters from string at once let' dive instring concatenation you can combineor concatenatetwo strings using the operatorstring "abrastring "cadabramagic_string string string magic_string 'abracadabrain this examplethe string concatenation occurs on the third line you concatenate string and string using +and then you assign the result to the variable magic_string notice that the two strings are joined without any whitespace between them you can use string concatenation to join two related stringssuch as joining first name and last name into full namefirst_name "arthurlast_name "dentfull_name first_name last_name full_name 'arthur denthereyou use string concatenation twice on the same line firstyou concatenate first_name with to ensure space appears after the first name in the final string this produces the string "arthur "which you then concatenate with last_name to produce the full name "arthur dent |
Subsets and Splits