-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtp_encoded_2048.json
1 lines (1 loc) · 668 KB
/
tp_encoded_2048.json
1
[{"id": "501460308ac99945b0696b60bbdb25ba", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ae15f3ffef81335a502cd8c4e5dbe740", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.\nPython is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Python:\n\nPython is Interpreted \u2212 Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.\nPython is Interactive \u2212 You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.\nPython is Object-Oriented \u2212 Python supports Object-Oriented style or technique of programming that encapsulates code within objects.\nPython is a Beginner's Language \u2212 Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2293c2f249346ba605288a9402b7eb9a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following are important characteristics of Python Programming \u2212\n\nIt supports functional and structured programming methods as well as OOP.\nIt can be used as a scripting language or can be compiled to byte-code for building large applications.\nIt provides very high-level dynamic data types and supports dynamic type checking.\nIt supports automatic garbage collection.\nIt can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d380ef9bf90157f28cfbe278f31bf591", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Just to give you a little excitement about Python, I'm going to give you a small conventional Python Hello World program, You can try it using Demo link.\n\nprint (\"Hello, Python!\");", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "676f30dfc5dbf75218a3edea6d32e87e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "As mentioned before, Python is one of the most widely used language over the web. I'm going to list few of them here:\n\nEasy-to-learn \u2212 Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.\nEasy-to-read \u2212 Python code is more clearly defined and visible to the eyes.\nEasy-to-maintain \u2212 Python's source code is fairly easy-to-maintain.\nA broad standard library \u2212 Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.\nInteractive Mode \u2212 Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.\nPortable \u2212 Python can run on a wide variety of hardware platforms and has the same interface on all platforms.\nExtendable \u2212 You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.\nDatabases \u2212 Python provides interfaces to all major commercial databases.\nGUI Programming \u2212 Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.\nScalable \u2212 Python provides a better structure and support for large programs than shell scripting.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "53d6662481b2103e370c962d436c64e8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This Python tutorial is designed for software programmers who need to learn Python programming language from scratch.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "93f1818bfe28a3708af0600ff01558ad", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.\n\nPython is Interpreted \u2212 Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.\nPython is Interactive \u2212 You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.\nPython is Object-Oriented \u2212 Python supports Object-Oriented style or technique of programming that encapsulates code within objects.\nPython is a Beginner's Language \u2212 Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "056520633b34554892f45ab454e1a437", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.\nPython is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.\nPython is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).\nPython is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9c519ebb7929dfaff4027d02102534fb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "30f05058c47a92e277ca2cd36f2ebde4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Open a terminal window and type \"python\" to find out if it is already installed and which version is installed.\n\nUnix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)\nWin 9x/NT/2000\nMacintosh (Intel, PPC, 68K)\nOS/2\nDOS (multiple versions)\nPalmOS\nNokia mobile phones\nWindows CE\nAcorn/RISC OS\nBeOS\nAmiga\nVMS/OpenVMS\nQNX\nVxWorks\nPsion\nPython has also been ported to the Java and .NET virtual machines", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2fd419d1eb3ac5731a497f1b5555cd74", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/\nYou can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5df8a254bcf3a21b62715ccb538d401a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.\nIf the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.\nHere is a quick overview of installing Python on various platforms \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "38f7c86af29882429b62b207a19ea3f2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are the simple steps to install Python on Unix/Linux machine.\n\nOpen a Web browser and go to https://www.python.org/downloads/.\nFollow the link to download zipped source code available for Unix/Linux.\nDownload and extract files.\nEditing the Modules/Setup file if you want to customize some options.\nrun ./configure script\nmake\nmake install\n\nThis installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d89033b208c37634e9a63c9c6a440ab3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are the steps to install Python on Windows machine.\n\nOpen a Web browser and go to https://www.python.org/downloads/.\nFollow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.\nTo use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.\nRun the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "18adf2d3c4076d5a7eaa775ce607603c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available.\nJack Jansen maintains it and you can have full access to the entire documentation at his website \u2212 http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f3d578aa000e8d0b9589f515783051a0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.\nThe path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.\nThe path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).\nIn Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5bd0b017140e1b4bc6d91a3e6c41de32", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To add the Python directory to the path for a particular session in Unix \u2212\n\nIn the csh shell \u2212 type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter.\nIn the bash shell (Linux) \u2212 type export PATH=\"$PATH:/usr/local/bin/python\" and press Enter.\nIn the sh or ksh shell \u2212 type PATH=\"$PATH:/usr/local/bin/python\" and press Enter.\nNote \u2212 /usr/local/bin/python is the path of the Python directory", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0bbe61317d058137534558f4a4084474", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To add the Python directory to the path for a particular session in Windows \u2212\nAt the command prompt \u2212 type path %path%;C:\\Python and press Enter.\nNote \u2212 C:\\Python is the path of the Python directory", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4e0d5ba3deea9a7b654eb313a95b5cd0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are important environment variables, which can be recognized by Python \u2212\n\n\nSr.No.\nVariable & Description\n\n\n1\nPYTHONPATH\nIt has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.\n\n\n2\nPYTHONSTARTUP\nIt contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it\ncontains commands that load utilities or modify PYTHONPATH.\n\n\n3\nPYTHONCASEOK\nIt is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.\n\n\n4\nPYTHONHOME\nIt is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "046b72b85d880a0da4de3b1cfad6c4cf", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are three different ways to start Python \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "62630de6d7436452cb967dbf85fdf5ae", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.\nEnter python the command line.\nStart coding right away in the interactive interpreter.\n\n$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n\nHere is the list of all the available command line options \u2212\n\n\n\nSr.No.\nOption & Description\n\n\n1\n-d\nIt provides debug output.\n\n\n2\n-O\nIt generates optimized bytecode (resulting in .pyo files).\n\n\n3\n-S\nDo not run import site to look for Python paths on startup.\n\n\n4\n-v\nverbose output (detailed trace on import statements).\n\n\n5\n-X\ndisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.\n\n\n6\n-c cmd\nrun Python script sent in as cmd string\n\n\n7\nfile\nrun Python script from given file", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "76c50f181acb174618a11fa085d86589", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following \u2212\n\n$python script.py # Unix/Linux\n\nor\n\npython% script.py # Unix/Linux\n\nor \n\nC: >python script.py # Windows/DOS\n\nNote \u2212 Be sure the file permission mode allows execution.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9ba315b41221fb38a42443df2757ae8a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "741b603813ed60133ef5c315f9ee43d6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us execute programs in different modes of programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cc9d77114e3824cd156622ddf6397fca", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Invoking the interpreter without passing a script file as a parameter brings up the following prompt \u2212\n\n$ python\nPython 2.4.3 (#1, Nov 11 2010, 13:34:43)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n\nType the following text at the Python prompt and press the Enter \u2212\n\n>>> print \"Hello, Python!\"\n\nIf you are running new version of Python, then you would need to use print statement with parenthesis as in print (\"Hello, Python!\");. However in Python version 2.4.3, this produces the following result \u2212\n\nHello, Python!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "30aec843164400e938b5e48c1e7a6812", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.\nLet us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file \u2212\n\nprint \"Hello, Python!\"\n\nWe assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows \u2212\n\n$ python test.py\n\nThis produces the following result \u2212\n\nHello, Python!\n\nLet us try another way to execute a Python script. Here is the modified test.py file \u2212\n\n#!/usr/bin/python\n\nprint \"Hello, Python!\"\n\nWe assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows \u2212\n\n$ chmod +x test.py # This is to make file executable\n$./test.py\n\nThis produces the following result \u2212\n\nHello, Python!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e9202204fccb4b8a2be7d907579d1d8f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).\nPython does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.\nHere are naming conventions for Python identifiers \u2212\n\nClass names start with an uppercase letter. All other identifiers start with a lowercase letter.\nStarting an identifier with a single leading underscore indicates that the identifier is private.\nStarting an identifier with two leading underscores indicates a strongly private identifier.\nIf the identifier also ends with two trailing underscores, the identifier is a language-defined special name.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b3e4ac13d80db642f5157045aae0f29e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.\n\n\nand\nexec\nnot\n\n\nassert\nfinally\nor\n\n\nbreak\nfor\npass\n\n\nclass\nfrom\nprint\n\n\ncontinue\nglobal\nraise\n\n\ndef\nif\nreturn\n\n\ndel\nimport\ntry\n\n\nelif\nin\nwhile\n\n\nelse\nis\nwith \n\n\nexcept\nlambda\nyield", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0376403018ca1c1f11bf4a1370adef49", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.\nThe number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example \u2212\n\nif True:\n print \"True\"\nelse:\n print \"False\"\n\nHowever, the following block generates an error \u2212\n\nif True:\nprint \"Answer\"\nprint \"True\"\nelse:\nprint \"Answer\"\nprint \"False\"\n\nThus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks \u2212\nNote \u2212 Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.\n\n#!/usr/bin/python\n\nimport sys\n\ntry:\n # open file stream\n file = open(file_name, \"w\")\nexcept IOError:\n print \"There was an error writing to\", file_name\n sys.exit()\nprint \"Enter '\", file_finish,\nprint \"' When finished\"\nwhile file_text != file_finish:\n file_text = raw_input(\"Enter text: \")\n if file_text == file_finish:\n # close the file\n file.close\n break\n file.write(file_text)\n file.write(\"\\n\")\nfile.close()\nfile_name = raw_input(\"Enter filename: \")\nif len(file_name) == 0:\n print \"Next time please enter something\"\n sys.exit()\ntry:\n file = open(file_name, \"r\")\nexcept IOError:\n print \"There was an error reading file\"\n sys.exit()\nfile_text = file.read()\nfile.close()\nprint file_text", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "29e70229bae49158b7396bd588542b72", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\\) to denote that the line should continue. For example \u2212\n\ntotal = item_one + \\\n item_two + \\\n item_three\n\nStatements contained within the [], {}, or () brackets do not need to use the line continuation character. For example \u2212\n\ndays = ['Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday']", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ba28739eda93c77c5e89740f825608e5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python accepts single ('), double (\") and triple (''' or \"\"\") quotes to denote string literals, as long as the same type of quote starts and ends the string.\nThe triple quotes are used to span the string across multiple lines. For example, all the following are legal \u2212\n\nword = 'word'\nsentence = \"This is a sentence.\"\nparagraph = \"\"\"This is a paragraph. It is\nmade up of multiple lines and sentences.\"\"\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0a2591d45277898c7e064a82a63746e7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.\n\n#!/usr/bin/python\n\n# First comment\nprint \"Hello, Python!\" # second comment\n\nThis produces the following result \u2212\n\nHello, Python!\n\nYou can type a comment on the same line after a statement or expression \u2212\n\nname = \"Madisetti\" # This is again comment\n\nYou can comment multiple lines as follows \u2212\n\n# This is a comment.\n# This is a comment, too.\n# This is a comment, too.\n# I said that already.\n\nFollowing triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:\n\n'''\nThis is a multiline\ncomment.\n'''", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "03a4161db01d791e98fccc7e6e788eee", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.\nIn an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c9f967eabbad4758dcacf1bdd79a5333", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following line of the program displays the prompt, the statement saying \u201cPress the enter key to exit\u201d, and waits for the user to take action \u2212\n\n#!/usr/bin/python\n\nraw_input(\"\\n\\nPress the enter key to exit.\")\n\nHere, \"\\n\\n\" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bc2f74412fc9485cb8afa7f9f2fbb7ac", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon \u2212\n\nimport sys; x = 'foo'; sys.stdout.write(x + '\\n')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1544c8893fe5dd42dd10947a003af2ea", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.\nHeader lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example \u2212\n\nif expression : \n suite\nelif expression : \n suite \nelse : \n suite", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b07bc09d9ba4f4d2a0a4e5ed12ce2cfd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.\nBased on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "24ce437f89b0c6a2869a2ff11cf5108c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.\nThe operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\ncounter = 100 # An integer assignment\nmiles = 1000.0 # A floating point\nname = \"John\" # A string\n\nprint counter\nprint miles\nprint name\n\nHere, 100, 1000.0 and \"John\" are the values assigned to counter, miles, and name variables, respectively. This produces the following result \u2212\n\n100\n1000.0\nJohn", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "59f277e335476cc5a19ec6837514fdd6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python allows you to assign a single value to several variables simultaneously. For example \u2212\n\na = b = c = 1\n\nHere, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example \u2212\n\na,b,c = 1,2,\"john\"\n\nHere, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value \"john\" is assigned to the variable c.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e6f5dce801ebc37eb7dcaa9b2d28bd6b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.\nPython has five standard data types \u2212\n\nNumbers\nString\nList\nTuple\nDictionary", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7041299db27f82784c4109caf4362a74", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Number data types store numeric values. Number objects are created when you assign a value to them. For example \u2212\n\nvar1 = 1\nvar2 = 10\n\nYou can also delete the reference to a number object by using the del statement. The syntax of the del statement is \u2212\n\ndel var1[,var2[,var3[....,varN]]]]\n\nYou can delete a single object or multiple objects by using the del statement. For example \u2212\n\ndel var\ndel var_a, var_b\n\nPython supports four different numerical types \u2212\n\nint (signed integers)\nlong (long integers, they can also be represented in octal and hexadecimal)\nfloat (floating point real values)\ncomplex (complex numbers)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6f2e5fdaa9f5250eed803c93dd946f3b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are some examples of numbers \u2212\n\n\nint\nlong\nfloat\ncomplex\n\n\n10\n51924361L\n0.0\n3.14j\n\n\n100\n-0x19323L\n15.20\n45.j\n\n\n-786\n0122L\n-21.9\n9.322e-36j\n\n\n080\n0xDEFABCECBDAECBFBAEl\n32.3+e18\n.876j\n\n\n-0490\n535633629843L\n-90.\n-.6545+0J\n\n\n-0x260\n-052318172735L\n-32.54e100\n3e+26J\n\n\n0x69\n-4721885298529L\n70.2-E12\n4.53e-7j\n\n\n\nPython allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.\nA complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4844da8a469809aff71d1e198c4ee2ed", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.\nThe plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\nstr = 'Hello World!'\n\nprint str # Prints complete string\nprint str[0] # Prints first character of the string\nprint str[2:5] # Prints characters starting from 3rd to 5th\nprint str[2:] # Prints string starting from 3rd character\nprint str * 2 # Prints string two times\nprint str + \"TEST\" # Prints concatenated string\n\nThis will produce the following result \u2212\n\nHello World!\nH\nllo\nllo World!\nHello World!Hello World!\nHello World!TEST", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "223322c271eb8786260b0d059ccfe4e0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.\nThe values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example \u2212\n\n#!/usr/bin/python\n\nlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntinylist = [123, 'john']\n\nprint list # Prints complete list\nprint list[0] # Prints first element of the list\nprint list[1:3] # Prints elements starting from 2nd till 3rd \nprint list[2:] # Prints elements starting from 3rd element\nprint tinylist * 2 # Prints list two times\nprint list + tinylist # Prints concatenated lists\n\nThis produce the following result \u2212\n\n['abcd', 786, 2.23, 'john', 70.2]\nabcd\n[786, 2.23]\n[2.23, 'john', 70.2]\n[123, 'john', 123, 'john']\n['abcd', 786, 2.23, 'john', 70.2, 123, 'john']", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "780c50095aa5444707944d5d1d5c9072", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.\nThe main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\ntuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )\ntinytuple = (123, 'john')\n\nprint tuple # Prints the complete tuple\nprint tuple[0] # Prints first element of the tuple\nprint tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd \nprint tuple[2:] # Prints elements of the tuple starting from 3rd element\nprint tinytuple * 2 # Prints the contents of the tuple twice\nprint tuple + tinytuple # Prints concatenated tuples\n\nThis produce the following result \u2212\n\n('abcd', 786, 2.23, 'john', 70.2)\nabcd\n(786, 2.23)\n(2.23, 'john', 70.2)\n(123, 'john', 123, 'john')\n('abcd', 786, 2.23, 'john', 70.2, 123, 'john')\n\nThe following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists \u2212\n\n#!/usr/bin/python\n\ntuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )\nlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntuple[2] = 1000 # Invalid syntax with tuple\nlist[2] = 1000 # Valid syntax with list", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "786099dbad9d44ed4ab844da078bbac9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.\nDictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\ndict = {}\ndict['one'] = \"This is one\"\ndict[2] = \"This is two\"\n\ntinydict = {'name': 'john','code':6734, 'dept': 'sales'}\n\n\nprint dict['one'] # Prints value for 'one' key\nprint dict[2] # Prints value for 2 key\nprint tinydict # Prints complete dictionary\nprint tinydict.keys() # Prints all the keys\nprint tinydict.values() # Prints all the values\n\nThis produce the following result \u2212\n\nThis is one\nThis is two\n{'dept': 'sales', 'code': 6734, 'name': 'john'}\n['dept', 'code', 'name']\n['sales', 6734, 'john']\n\nDictionaries have no concept of order among elements. It is incorrect to say that the elements are \"out of order\"; they are simply unordered.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "921ccfd7ac22a3e55019de94379e24e6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Operators are the constructs which can manipulate the value of operands.\nConsider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "97c9790ea0cdbff4b5deb440bfc09ea5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python language supports the following types of operators.\n\nArithmetic Operators\nComparison (Relational) Operators\nAssignment Operators\nLogical Operators\nBitwise Operators\nMembership Operators\nIdentity Operators\n\nLet us have a look on all operators one by one.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "051ce6732fe0fbc99281176b32ebd08e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n+ Addition\nAdds values on either side of the operator.\na + b = 30\n\n\n- Subtraction\nSubtracts right hand operand from left hand operand.\na \u2013 b = -10\n\n\n* Multiplication\nMultiplies values on either side of the operator\na * b = 200\n\n\n/ Division\nDivides left hand operand by right hand operand\nb / a = 2\n\n\n% Modulus\nDivides left hand operand by right hand operand and returns remainder\nb % a = 0\n\n\n** Exponent\nPerforms exponential (power) calculation on operators\na**b =10 to the power 20\n\n\n//\nFloor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) \u2212\n9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bff7d10e2ca2b4e36cc2bcecfcd7173b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.\nAssume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n==\nIf the values of two operands are equal, then the condition becomes true.\n(a == b) is not true.\n\n\n!=\nIf values of two operands are not equal, then condition becomes true.\n(a != b) is true.\n\n\n<>\nIf values of two operands are not equal, then condition becomes true.\n(a <> b) is true. This is similar to != operator.\n\n\n>\nIf the value of left operand is greater than the value of right operand, then condition becomes true.\n(a > b) is not true.\n\n\n<\nIf the value of left operand is less than the value of right operand, then condition becomes true.\n(a < b) is true.\n\n\n>=\nIf the value of left operand is greater than or equal to the value of right operand, then condition becomes true.\n(a >= b) is not true.\n\n\n<=\nIf the value of left operand is less than or equal to the value of right operand, then condition becomes true.\n(a <= b) is true.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "458c95da7abfb385db2a80c716d15203", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n=\nAssigns values from right side operands to left side operand\nc = a + b assigns value of a + b into c\n\n\n+= Add AND\nIt adds right operand to the left operand and assign the result to left operand\nc += a is equivalent to c = c + a\n\n\n-= Subtract AND\nIt subtracts right operand from the left operand and assign the result to left operand\nc -= a is equivalent to c = c - a\n\n\n*= Multiply AND\nIt multiplies right operand with the left operand and assign the result to left operand\nc *= a is equivalent to c = c * a\n\n\n/= Divide AND\nIt divides left operand with the right operand and assign the result to left operand\nc /= a is equivalent to c = c / a\n\n\n\n%= Modulus AND\nIt takes modulus using two operands and assign the result to left operand\nc %= a is equivalent to c = c % a\n\n\n**= Exponent AND\nPerforms exponential (power) calculation on operators and assign value to the left operand\nc **= a is equivalent to c = c ** a\n\n\n//= Floor Division\nIt performs floor division on operators and assign value to the left operand\nc //= a is equivalent to c = c // a", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f01758272edbc2ffb680e81835085ff2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands \u2212\na = 0011 1100\nb = 0000 1101\n-----------------\na&b = 0000 1100\na|b = 0011 1101\na^b = 0011 0001\n~a\u00a0 = 1100 0011\nThere are following Bitwise operators supported by Python language\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n& Binary AND\nOperator copies a bit to the result if it exists in both operands\n(a & b) (means 0000 1100)\n\n\n| Binary OR\nIt copies a bit if it exists in either operand.\n(a | b) = 61 (means 0011 1101)\n\n\n^ Binary XOR\nIt copies the bit if it is set in one operand but not both.\n(a ^ b) = 49 (means 0011 0001)\n\n\n~ Binary Ones Complement\nIt is unary and has the effect of 'flipping' bits.\n(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.\n\n\n<< Binary Left Shift\nThe left operands value is moved left by the number of bits specified by the right operand.\na << 2 = 240 (means 1111 0000)\n\n\n>> Binary Right Shift\nThe left operands value is moved right by the number of bits specified by the right operand.\na >> 2 = 15 (means 0000 1111)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "979b0900d4800d2cdf345a75f1a175a2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nand Logical AND\nIf both the operands are true then condition becomes true.\n(a and b) is true.\n\n\nor Logical OR\nIf any of the two operands are non-zero then condition becomes true.\n(a or b) is true.\n\n\nnot Logical NOT\nUsed to reverse the logical state of its operand.\nNot(a and b) is false.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e133ac2f4f96cab23e1bd294fbe35669", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python\u2019s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nin\nEvaluates to true if it finds a variable in the specified sequence and false otherwise.\nx in y, here in results in a 1 if x is a member of sequence y.\n\n\nnot in\nEvaluates to true if it does not finds a variable in the specified sequence and false otherwise.\nx not in y, here not in results in a 1 if x is not a member of sequence y.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "53ebd351babee9c1b09b8e403dc0a47c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Identity operators compare the memory locations of two objects. There are two Identity operators explained below \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nis\nEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.\nx is y, here is results in 1 if id(x) equals id(y).\n\n\nis not\nEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.\nx is not y, here is not results in 1 if id(x) is not equal to id(y).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "03cc671c93bd71aa0a7b1ac1c156c700", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.\nDecision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.\nFollowing is the general form of a typical decision making structure found in most of the programming languages \u2212\n\nPython programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.\nPython programming language provides following types of decision making statements. Click the following links to check their detail.\n\n\nSr.No.\nStatement & Description\n\n\n1\nif statements\nAn if statement consists of a boolean expression followed by one or more statements.\n\n\n2\nif...else statements\nAn if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.\n\n\n3\nnested if statements\nYou can use one if or else if statement inside another if or else if statement(s).\n\n\nLet us go through each decision making briefly \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ed1232cf90bee4845c0d6de632590c6f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.\nProgramming languages provide various control structures that allow for more complicated execution paths.\nA loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement \u2212\n\nPython programming language provides following types of loops to handle looping requirements.\n\n\nSr.No.\nLoop Type & Description\n\n\n1\nwhile loop\nRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.\n\n\n2\nfor loop\nExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.\n\n\n3\nnested loops\nYou can use one or more loop inside any another while, for or do..while loop.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c010399bc1aefe3497773f04d2315710", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.\nNumber objects are created when you assign a value to them. For example \u2212\n\nvar1 = 1\nvar2 = 10\n\nYou can also delete the reference to a number object by using the del statement. The syntax of the del statement is \u2212\n\ndel var1[,var2[,var3[....,varN]]]]\n\nYou can delete a single object or multiple objects by using the del statement. For example \u2212\n\ndel var\ndel var_a, var_b\n\nPython supports four different numerical types \u2212\n\nint (signed integers) \u2212 They are often called just integers or ints, are positive or negative whole numbers with no decimal point.\nlong (long integers ) \u2212 Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.\nfloat (floating point real values) \u2212 Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).\ncomplex (complex numbers) \u2212 are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6fb370979d7a9924941d8c2e16b755d0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are some examples of numbers\n\n\nint\nlong\nfloat\ncomplex\n\n\n10\n51924361L\n0.0\n3.14j\n\n\n100\n-0x19323L\n15.20\n45.j\n\n\n-786\n0122L\n-21.9\n9.322e-36j\n\n\n080\n0xDEFABCECBDAECBFBAEL\n32.3+e18\n.876j\n\n\n-0490\n535633629843L\n-90.\n-.6545+0J\n\n\n-0x260\n-052318172735L\n-32.54e100\n3e+26J\n\n\n0x69\n-4721885298529L\n70.2-E12\n4.53e-7j\n\n\n\nPython allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.\nA complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f01f8bcfa0d658babe29c65a1b2cb57a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.\n\nType int(x) to convert x to a plain integer.\nType long(x) to convert x to a long integer.\nType float(x) to convert x to a floating-point number.\nType complex(x) to convert x to a complex number with real part x and imaginary part zero.\nType complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f127da68200d65b1b3bcdf0c86e6c5a4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes following functions that perform mathematical calculations.\n\n\nSr.No.\nFunction & Returns ( description )\n\n\n1\nabs(x)\nThe absolute value of x: the (positive) distance between x and zero.\n\n\n2\nceil(x)\nThe ceiling of x: the smallest integer not less than x\n\n\n3\ncmp(x, y)\n-1 if x < y, 0 if x == y, or 1 if x > y\n\n\n4\nexp(x)\nThe exponential of x: ex\n\n\n5\nfabs(x)\nThe absolute value of x.\n\n\n6\nfloor(x)\nThe floor of x: the largest integer not greater than x\n\n\n7\nlog(x)\nThe natural logarithm of x, for x> 0\n\n\n8\nlog10(x)\nThe base-10 logarithm of x for x> 0.\n\n\n9\nmax(x1, x2,...)\nThe largest of its arguments: the value closest to positive infinity\n\n\n10\nmin(x1, x2,...)\nThe smallest of its arguments: the value closest to negative infinity\n\n\n11\nmodf(x)\nThe fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.\n\n\n12\npow(x, y)\nThe value of x**y.\n\n\n13\nround(x [,n])\nx rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.\n\n\n14\nsqrt(x)\nThe square root of x for x > 0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d0308cc132dc032aca31715b6244fd83", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.\n\n\nSr.No.\nFunction & Description\n\n\n1\nchoice(seq)\nA random item from a list, tuple, or string.\n\n\n2\nrandrange ([start,] stop [,step])\nA randomly selected element from range(start, stop, step)\n\n\n3\nrandom()\nA random float r, such that 0 is less than or equal to r and r is less than 1\n\n\n4\nseed([x])\nSets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.\n\n\n5\nshuffle(lst)\nRandomizes the items of a list in place. Returns None.\n\n\n6\nuniform(x, y)\nA random float r, such that x is less than or equal to r and r is less than y", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5345d739ae4955249c3a58fca89a16ab", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes following functions that perform trigonometric calculations.\n\n\nSr.No.\nFunction & Description\n\n\n1\nacos(x)\nReturn the arc cosine of x, in radians.\n\n\n2\nasin(x)\nReturn the arc sine of x, in radians.\n\n\n3\natan(x)\nReturn the arc tangent of x, in radians.\n\n\n4\natan2(y, x)\nReturn atan(y / x), in radians.\n\n\n5\ncos(x)\nReturn the cosine of x radians.\n\n\n6\nhypot(x, y)\nReturn the Euclidean norm, sqrt(x*x + y*y).\n\n\n7\nsin(x)\nReturn the sine of x radians.\n\n\n8\ntan(x)\nReturn the tangent of x radians.\n\n\n9\ndegrees(x)\nConverts angle x from radians to degrees.\n\n\n10\nradians(x)\nConverts angle x from degrees to radians.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5870c5c2a3b15ae74a9b75fb59ee2adb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example \u2212\n\nvar1 = 'Hello World!'\nvar2 = \"Python Programming\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "33c401b5f0b17c1effdd719eaa6cf3e6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python does not support a character type; these are treated as strings of length one, thus also considered a substring.\nTo access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example \u2212\n\n#!/usr/bin/python\n\nvar1 = 'Hello World!'\nvar2 = \"Python Programming\"\n\nprint \"var1[0]: \", var1[0]\nprint \"var2[1:5]: \", var2[1:5]\n\nWhen the above code is executed, it produces the following result \u2212\n\nvar1[0]: H\nvar2[1:5]: ytho", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2bf1961ccabbc8f6a9f4ba2f939e6fbb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can \"update\" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example \u2212\n\n#!/usr/bin/python\n\nvar1 = 'Hello World!'\nprint \"Updated String :- \", var1[:6] + 'Python'\n\nWhen the above code is executed, it produces the following result \u2212\n\nUpdated String :- Hello Python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8a03553927aa21b7e460edb281137a8d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following table is a list of escape or non-printable characters that can be represented with backslash notation.\nAn escape character gets interpreted; in a single quoted as well as double quoted strings.\n\n\nBackslash notation\nHexadecimal character\nDescription\n\n\n\\a\n0x07\nBell or alert\n\n\n\\b\n0x08\nBackspace\n\n\n\\cx\n\u00a0\nControl-x\n\n\n\\C-x\n\u00a0\nControl-x\n\n\n\\e\n0x1b\nEscape\n\n\n\\f\n0x0c\nFormfeed\n\n\n\\M-\\C-x\n\u00a0\nMeta-Control-x\n\n\n\\n\n0x0a\nNewline\n\n\n\\nnn\n\u00a0\nOctal notation, where n is in the range 0.7\n\n\n\\r\n0x0d\nCarriage return\n\n\n\\s\n0x20\nSpace\n\n\n\\t\n0x09\nTab\n\n\n\\v\n0x0b\nVertical tab\n\n\n\\x\n\u00a0\nCharacter x\n\n\n\\xnn\n\u00a0\nHexadecimal notation, where n is in the range 0.9, a.f, or A.F", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2bb8dda462c02ec2d0dcb9e4c40da9ac", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume string variable a holds 'Hello' and variable b holds 'Python', then \u2212\n\n\nOperator\nDescription\nExample\n\n\n+\nConcatenation - Adds values on either side of the operator\na + b will give HelloPython\n\n\n*\nRepetition - Creates new strings, concatenating multiple copies of the same\nstring\na*2 will give -HelloHello\n\n\n[]\nSlice - Gives the character from the given index\na[1] will give e\n\n\n[ : ]\nRange Slice - Gives the characters from the given range\na[1:4] will give ell\n\n\nin\nMembership - Returns true if a character exists in the given string\nH in a will give 1\n\n\nnot in \nMembership - Returns true if a character does not exist in the given string\nM not in a will give 1\n\n\nr/R\nRaw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter \"r,\" which precedes the quotation marks. The \"r\" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.\nprint r'\\n' prints \\n and print R'\\n'prints \\n\n\n\n%\nFormat - Performs String formatting\nSee at next section", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9a781504084b4b3b02d34f5e90376c5b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example \u2212\n\n#!/usr/bin/python\n\nprint \"My name is %s and weight is %d kg!\" % ('Zara', 21)\n\nWhen the above code is executed, it produces the following result \u2212\n\nMy name is Zara and weight is 21 kg!\n\nHere is the list of complete set of symbols which can be used along with % \u2212\n\n\nFormat Symbol\nConversion\n\n\n%c\ncharacter\n\n\n%s\nstring conversion via str() prior to formatting\n\n\n%i\nsigned decimal integer\n\n\n%d\nsigned decimal integer\n\n\n%u\nunsigned decimal integer\n\n\n%o\noctal integer\n\n\n%x\nhexadecimal integer (lowercase letters)\n\n\n%X\nhexadecimal integer (UPPERcase letters)\n\n\n%e\nexponential notation (with lowercase 'e')\n\n\n%E\nexponential notation (with UPPERcase 'E')\n\n\n%f\nfloating point real number\n\n\n%g\nthe shorter of %f and %e\n\n\n%G\nthe shorter of %f and %E\n\n\nOther supported symbols and functionality are listed in the following table \u2212\n\n\nSymbol\nFunctionality\n\n\n*\nargument specifies width or precision\n\n\n-\nleft justification\n\n\n+\ndisplay the sign\n\n\n<sp>\nleave a blank space before a positive number\n\n\n#\nadd the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.\n\n\n0\npad from left with zeros (instead of spaces)\n\n\n%\n'%%' leaves you with a single literal '%'\n\n\n(var)\nmapping variable (dictionary arguments)\n\n\nm.n.\nm is the minimum total width and n is the number of digits to display after the decimal point (if appl.)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e6416194c34b7665fcf7b31bf9240468", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.\nThe syntax for triple quotes consists of three consecutive single or double quotes.\n\n#!/usr/bin/python\n\npara_str = \"\"\"this is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( \\t ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [ \\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n\"\"\"\nprint para_str\n\nWhen the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the \"up.\" and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\\n) \u2212\n\nthis is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n\nRaw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it \u2212\n\n#!/usr/bin/python\n\nprint 'C:\\\\nowhere'\n\nWhen the above code is executed, it produces the following result \u2212\n\nC:\\nowhere\n\nNow let's make use of raw string. We would put expression in r'expression' as follows \u2212\n\n#!/usr/bin/python\n\nprint r'C:\\\\nowhere'\n\nWhen the above code is executed, it produces the following result \u2212\n\nC:\\\\nowhere", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1bb82d85ebe25cad5dc5dc8e5e789da5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following \u2212\n\n#!/usr/bin/python\n\nprint u'Hello, world!'\n\nWhen the above code is executed, it produces the following result \u2212\n\nHello, world!\n\nAs you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ab956aee470fa0599ff1b2975fed366d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.\nPython has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.\nThere are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f5ef6cf3a63cfdb04a0102fae5515d6a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.\nCreating a list is as simple as putting different comma-separated values between square brackets. For example \u2212\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5 ];\nlist3 = [\"a\", \"b\", \"c\", \"d\"]\n\nSimilar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "62803e46eebec49e05ab7f31ae5e1a4a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example \u2212\n\n#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]\n\nWhen the above code is executed, it produces the following result \u2212\n\nlist1[0]: physics\nlist2[1:5]: [2, 3, 4, 5]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f4365470cc9a28bef459954dba58ca25", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example \u2212\n\n#!/usr/bin/python\n\nlist = ['physics', 'chemistry', 1997, 2000];\nprint \"Value available at index 2 : \"\nprint list[2]\nlist[2] = 2001;\nprint \"New value available at index 2 : \"\nprint list[2]\n\nNote \u2212 append() method is discussed in subsequent section.\nWhen the above code is executed, it produces the following result \u2212\n\nValue available at index 2 :\n1997\nNew value available at index 2 :\n2001", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9ade256c5050ddab521ed622387a6ee3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example \u2212\n\n#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nprint list1\ndel list1[2];\nprint \"After deleting value at index 2 : \"\nprint list1\n\nWhen the above code is executed, it produces following result \u2212\n\n['physics', 'chemistry', 1997, 2000]\nAfter deleting value at index 2 :\n['physics', 'chemistry', 2000]\n\nNote \u2212 remove() method is discussed in subsequent section.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e2e07d0e8d2a1743909b6308fdd9dc51", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.\nIn fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.\n\n\nPython Expression\nResults\nDescription\n\n\nlen([1, 2, 3])\n3\nLength\n\n\n[1, 2, 3] + [4, 5, 6]\n[1, 2, 3, 4, 5, 6]\nConcatenation\n\n\n['Hi!'] * 4\n['Hi!', 'Hi!', 'Hi!', 'Hi!']\nRepetition\n\n\n3 in [1, 2, 3]\nTrue\nMembership\n\n\nfor x in [1, 2, 3]: print x,\n1 2 3\nIteration", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bf66b0703b515cc9cb9f9818ca9ef005", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.\nAssuming following input \u2212\n\nL = ['spam', 'Spam', 'SPAM!']\n\n\n\n\nPython Expression\nResults\nDescription\n\n\nL[2]\nSPAM!\nOffsets start at zero\n\n\nL[-2]\nSpam\nNegative: count from the right\n\n\nL[1:]\n['Spam', 'SPAM!']\nSlicing fetches sections", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f2ac98c35d728a763c2a98828da8e056", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.\nCreating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example \u2212\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5 );\ntup3 = \"a\", \"b\", \"c\", \"d\";\n\nThe empty tuple is written as two parentheses containing nothing \u2212\n\ntup1 = ();\n\nTo write a tuple containing a single value you have to include a comma, even though there is only one value \u2212\n\ntup1 = (50,);\n\nLike string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8a9e5c5a224852adbc0f8a34e397b47a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0];\nprint \"tup2[1:5]: \", tup2[1:5];\n\nWhen the above code is executed, it produces the following result \u2212\n\ntup1[0]: physics\ntup2[1:5]: [2, 3, 4, 5]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ded61083f6ed4c34b0d6b2646ca3e2a5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates \u2212\n Live Demo\n\n#!/usr/bin/python\n\ntup1 = (12, 34.56);\ntup2 = ('abc', 'xyz');\n\n# Following action is not valid for tuples\n# tup1[0] = 100;\n\n# So let's create a new tuple as follows\ntup3 = tup1 + tup2;\nprint tup3;\n\nWhen the above code is executed, it produces the following result \u2212\n\n(12, 34.56, 'abc', 'xyz')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a6162275626a8a89bb6f74d20f5f2ea6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.\nTo explicitly remove an entire tuple, just use the del statement. For example \u2212\n Live Demo\n\n#!/usr/bin/python\n\ntup = ('physics', 'chemistry', 1997, 2000);\nprint tup;\ndel tup;\nprint \"After deleting tup : \";\nprint tup;\n\nThis produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more \u2212\n\n('physics', 'chemistry', 1997, 2000)\nAfter deleting tup :\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print tup;\nNameError: name 'tup' is not defined", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b0ede1ea0bda54204f07972b51c08fc6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.\nIn fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter \u2212\n\n\nPython Expression\nResults\nDescription\n\n\nlen((1, 2, 3))\n3\nLength\n\n\n(1, 2, 3) + (4, 5, 6)\n(1, 2, 3, 4, 5, 6)\nConcatenation\n\n\n('Hi!',) * 4\n('Hi!', 'Hi!', 'Hi!', 'Hi!')\nRepetition\n\n\n3 in (1, 2, 3)\nTrue\nMembership\n\n\nfor x in (1, 2, 3): print x,\n1 2 3\nIteration", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2f0728dbfff74dbb1968cab5dcc91c2b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input \u2212\n\nL = ('spam', 'Spam', 'SPAM!')\n\n\u00a0\n\n\nPython Expression\nResults\nDescription\n\n\nL[2]\n'SPAM!'\nOffsets start at zero\n\n\nL[-2]\n'Spam'\nNegative: count from the right\n\n\nL[1:]\n['Spam', 'SPAM!']\nSlicing fetches sections", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d4199be6665778874fe9ccb1ac9f14d4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples \u2212\n Live Demo\n\n#!/usr/bin/python\n\nprint 'abc', -4.24e93, 18+6.6j, 'xyz';\nx, y = 1, 2;\nprint \"Value of x , y : \", x,y;\n\nWhen the above code is executed, it produces the following result \u2212\n\nabc -4.24e+93 (18+6.6j) xyz\nValue of x , y : 1 2", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cfe6fac14d5dc0032dae7ffec73b62aa", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.\nKeys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9a37ba36bd1437abbc7d0e656b61f2b5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Name']: Zara\ndict['Age']: 7\n\nIf we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Alice']:\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n print \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3d2ad42ed421af51da5e9a7099ab84d7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Age']: 8\ndict['School']: DPS School", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "94f6b07fc87e34cba99cf5b2f2c76760", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.\nTo explicitly remove an entire dictionary, just use the del statement. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']\n\nThis produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more \u2212\n\ndict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n\nNote \u2212 del() method is discussed in subsequent section.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "05741f619cdbbc0118cccc302e8960bb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.\nThere are two important points to remember about dictionary keys \u2212\n(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Name']: Manni\n\n(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']\n\nWhen the above code is executed, it produces the following result \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 3, in <module>\n dict = {['Name']: 'Zara', 'Age': 7};\nTypeError: unhashable type: 'list'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "817ca8ef032f8ed74bcb2a4e19cab1f9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "96893a8d1d99562266c897a5dd5881f0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 00:00:00 hrs January 1, 1970(epoch).\nThere is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 00:00:00 hrs January 1, 1970(epoch).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b5a3e82629c7cdc39aa5095ff1f76bff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Live Demo\n\n#!/usr/bin/python\nimport time; # This is required to include time module.\n\nticks = time.time()\nprint \"Number of ticks since 12:00am, January 1, 1970:\", ticks\n\nThis would produce a result something as follows \u2212\n\nNumber of ticks since 12:00am, January 1, 1970: 7186862.73399\n\nDate arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a37085262de8813f934ffa52c2b57f8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Many of Python's time functions handle time as a tuple of 9 numbers, as shown below \u2212\n\n\nIndex\nField\nValues\n\n\n0\n4-digit year\n2008\n\n\n1\nMonth\n1 to 12\n\n\n2\nDay\n1 to 31\n\n\n3\nHour\n0 to 23\n\n\n4\nMinute\n0 to 59\n\n\n5\nSecond\n0 to 61 (60 or 61 are leap-seconds)\n\n\n6\nDay of Week\n0 to 6 (0 is Monday)\n\n\n7\nDay of year\n1 to 366 (Julian day)\n\n\n8\nDaylight savings\n-1, 0, 1, -1 means library determines DST\n\n\nThe above tuple is equivalent to struct_time structure. This structure has following attributes \u2212\n\n\nIndex\nAttributes\nValues\n\n\n0\ntm_year\n2008\n\n\n1\ntm_mon\n1 to 12\n\n\n2\ntm_mday\n1 to 31\n\n\n3\ntm_hour\n0 to 23\n\n\n4\ntm_min\n0 to 59\n\n\n5\ntm_sec\n0 to 61 (60 or 61 are leap-seconds)\n\n\n6\ntm_wday\n0 to 6 (0 is Monday)\n\n\n7\ntm_yday\n1 to 366 (Julian day)\n\n\n8\ntm_isdst\n-1, 0, 1, -1 means library determines DST", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b2ea51c5749cd850d34ba98ec719287c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To translate a time instant from a seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid.\n Live Demo\n\n#!/usr/bin/python\nimport time;\n\nlocaltime = time.localtime(time.time())\nprint \"Local current time :\", localtime\n\nThis would produce the following result, which could be formatted in any other presentable form \u2212\n\nLocal current time : time.struct_time(tm_year=2013, tm_mon=7, \ntm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e5fe3f209b828228c87e5fa4c7ecb38d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can format any time as per your requirement, but simple method to get time in readable format is asctime() \u2212\n Live Demo\n\n#!/usr/bin/python\nimport time;\n\nlocaltime = time.asctime( time.localtime(time.time()) )\nprint \"Local current time :\", localtime\n\nThis would produce the following result \u2212\n\nLocal current time : Tue Jan 13 10:17:09 2009", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a253cfaf9684e6f5dfd3e5f96184dcfe", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) \u2212\n Live Demo\n\n#!/usr/bin/python\nimport calendar\n\ncal = calendar.month(2008, 1)\nprint \"Here is the calendar:\"\nprint cal\n\nThis would produce the following result \u2212\n\nHere is the calendar:\n January 2008\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30 31", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "738d1d4b9581da31b0523515b2fb96e0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There is a popular time module available in Python which provides functions for working with times and for converting between representations. Here is the list of all available methods \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ntime.altzone\nThe offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.\n\n\n2\ntime.asctime([tupletime])\nAccepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.\n\n\n3\ntime.clock( )\nReturns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().\n\n\n4\ntime.ctime([secs])\nLike asctime(localtime(secs)) and without arguments is like asctime( )\n\n\n5\ntime.gmtime([secs])\nAccepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note : t.tm_isdst is always 0\n\n\n6\ntime.localtime([secs])\nAccepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).\n\n\n7\ntime.mktime(tupletime)\nAccepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.\n\n\n8\ntime.sleep(secs)\nSuspends the calling thread for secs seconds.\n\n\n9\ntime.strftime(fmt[,tupletime])\nAccepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.\n\n\n10\ntime.strptime(str,fmt='%a %b %d %H:%M:%S %Y')\nParses str according to format string fmt and returns the instant in time-tuple format.\n\n\n11\ntime.time( )\nReturns the current time instant, a floating-point number of seconds since the epoch.\n\n\n12\ntime.tzset()\nResets the time conversion rules used by the library routines. The environment variable TZ specifies how this is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2f239521795c899440cc924e36525d6b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": " done.\n\n\nLet us go through the functions briefly \u2212\nThere are following two important attributes available with time module \u2212\n\n\nSr.No.\nAttribute with Description\n\n\n1\ntime.timezone\nAttribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).\n\n\n2\ntime.tzname\nAttribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0c78253664b6108ebb58780ad151a19f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.\nBy default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function.\nHere is a list of functions available with the calendar module \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ncalendar.calendar(year,w=2,l=1,c=6)\nReturns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.\n\n\n2\ncalendar.firstweekday( )\nReturns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.\n\n\n3\ncalendar.isleap(year)\nReturns True if year is a leap year; otherwise, False.\n\n\n4\ncalendar.leapdays(y1,y2)\nReturns the total number of leap days in the years within range(y1,y2).\n\n\n5\ncalendar.month(year,month,w=2,l=1)\nReturns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.\n\n\n6\ncalendar.monthcalendar(year,month)\nReturns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.\n\n\n7\ncalendar.monthrange(year,month)\nReturns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.\n\n\n8\ncalendar.prcal(year,w=2,l=1,c=6)\nLike print calendar.calendar(year,w,l,c).\n\n\n9\ncalendar.prmonth(year,month,w=2,l=1)\nLike print calendar.month(year,month,w,l).\n\n\n10\ncalendar.setfirstweekday(weekday)\nSets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b52033a39f007c36bc8c4c59a9dd256f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\n\n\n11\ncalendar.timegm(tupletime)\nThe inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.\n\n\n12\ncalendar.weekday(year,month,day)\nReturns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5c918e72fa2b8df4c80353a4a00cabae", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.\nAs you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c063321110f7e0416e16b4a8588cea95", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can define functions to provide the required functionality. Here are simple rules to define a function in Python.\n\nFunction blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).\nAny input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.\nThe first statement of a function can be an optional statement - the documentation string of the function or docstring.\nThe code block within every function starts with a colon (:) and is indented.\nThe statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4f2875ae05cfd48821217b53cc742ad5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "def functionname( parameters ):\n \"function_docstring\"\n function_suite\n return [expression]\n\nBy default, parameters have a positional behavior and you need to inform them in the same order that they were defined.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dec66ac93f3ef569de203a07b2b15102", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following function takes a string as input parameter and prints it on standard screen.\n\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b961ed1ad23da9e600818c618936f724", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.\nOnce the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme(\"I'm first call to user defined function!\")\nprintme(\"Again second call to the same function\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nI'm first call to user defined function!\nAgain second call to the same function", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ebe5b323f1f8033d0c7a3336760ded50", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist.append([1,2,3,4]);\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist\n\nHere, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result \u2212\n\nValues inside the function: [10, 20, 30, [1, 2, 3, 4]]\nValues outside the function: [10, 20, 30, [1, 2, 3, 4]]\n\nThere is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.\n\n#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist = [1,2,3,4]; # This would assig new reference in mylist\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist\n\nThe parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result \u2212\n\nValues inside the function: [1, 2, 3, 4]\nValues outside the function: [10, 20, 30]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b361ab6eef346587616b7f15a7a604ff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can call a function by using the following types of formal arguments \u2212\n\nRequired arguments\nKeyword arguments\nDefault arguments\nVariable-length arguments", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "603229240c137ffd2d07fa59e3f5b7b1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.\nTo call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme()\n\nWhen the above code is executed, it produces the following result \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 11, in <module>\n printme();\nTypeError: printme() takes exactly 1 argument (0 given)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c187975edb92d43e0c1331542a657b6d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.\nThis allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme( str = \"My string\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nMy string\n\nThe following example gives more clear picture. Note that the order of parameters does not matter.\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\n\nWhen the above code is executed, it produces the following result \u2212\n\nName: miki\nAge 50", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5a2f3cadc52618299e566fad43f85d60", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age = 35 ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\nprintinfo( name=\"miki\" )\n\nWhen the above code is executed, it produces the following result \u2212\n\nName: miki\nAge 50\nName: miki\nAge 35", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "678b6014c08397118398c312ec61161c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.\nSyntax for a function with non-keyword variable arguments is this \u2212\n\ndef functionname([formal_args,] *var_args_tuple ):\n \"function_docstring\"\n function_suite\n return [expression]\n\nAn asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( arg1, *vartuple ):\n \"This prints a variable passed arguments\"\n print \"Output is: \"\n print arg1\n for var in vartuple:\n print var\n return;\n\n# Now you can call printinfo function\nprintinfo( 10 )\nprintinfo( 70, 60, 50 )\n\nWhen the above code is executed, it produces the following result \u2212\n\nOutput is:\n10\nOutput is:\n70\n60\n50", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d34b54485b23237de49741a3a2a5804c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.\n\nLambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.\nAn anonymous function cannot be a direct call to print because lambda requires an expression\nLambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.\nAlthough it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4490f78dff6e138831cc21c12f2f79cc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The syntax of lambda functions contains only a single statement, which is as follows \u2212\n\nlambda [arg1 [,arg2,.....argn]]:expression\n\nFollowing is the example to show how lambda form of function works \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\nsum = lambda arg1, arg2: arg1 + arg2;\n\n# Now you can call sum as a function\nprint \"Value of total : \", sum( 10, 20 )\nprint \"Value of total : \", sum( 20, 20 )\n\nWhen the above code is executed, it produces the following result \u2212\n\nValue of total : 30\nValue of total : 40", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e422ae626071d08a0ffd881993c04764", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.\nAll the above examples are not returning any value. You can return a value from a function as follows \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2\n print \"Inside the function : \", total\n return total;\n\n# Now you can call sum function\ntotal = sum( 10, 20 );\nprint \"Outside the function : \", total \n\nWhen the above code is executed, it produces the following result \u2212\n\nInside the function : 30\nOutside the function : 30", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1c82e1b73a3b4cce96225c8bb1ece1a8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.\nThe scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python \u2212\n\nGlobal variables\nLocal variables", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a42b7c22f14a374e903530cfb7789a1f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.\nSimply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8721e3059ed7532d11983e2ab7089ade", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py\n\ndef print_func( par ):\n print \"Hello : \", par\n return", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e7f9d461ed3c9ea8b39a77aa977fa413", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax \u2212\n\nimport module1[, module2[,... moduleN]\n\nWhen the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script \u2212\n\n#!/usr/bin/python\n\n# Import module support\nimport support\n\n# Now you can call defined function that module as follows\nsupport.print_func(\"Zara\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nHello : Zara\n\nA module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "483974e65aee34140a93cea068cf96b4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax \u2212\n\nfrom modname import name1[, name2[, ... nameN]]\n\nFor example, to import the function fibonacci from the module fib, use the following statement \u2212\n\nfrom fib import fibonacci\n\nThis statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ca179536cfbc0388bd37324ed7a922ab", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is also possible to import all names from a module into the current namespace by using the following import statement \u2212\n\nfrom modname import *\n\nThis provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f303a9bb24b4f0a7323f4d52db17f3a3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When you import a module, the Python interpreter searches for the module in the following sequences \u2212\n\nThe current directory.\nIf the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.\nIf all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.\n\nThe module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3b59f075e639aa3cf1252ef959c1c103", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.\nHere is a typical PYTHONPATH from a Windows system \u2212\n\nset PYTHONPATH = c:\\python20\\lib;\n\nAnd here is a typical PYTHONPATH from a UNIX system \u2212\n\nset PYTHONPATH = /usr/local/lib/python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "981b60543ee32b95ec6ac7196dda91d4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).\nA Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.\nEach function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.\nPython makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.\nTherefore, in order to assign a value to a global variable within a function, you must first use the global statement.\nThe statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.\nFor example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.\n\n#!/usr/bin/python\n\nMoney = 2000\ndef AddMoney():\n # Uncomment the following line to fix the code:\n # global Money\n Money = Money + 1\n\nprint Money\nAddMoney()\nprint Money", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f9bc2d3d9a7fcf937fefa4a3ddfec933", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The dir() built-in function returns a sorted list of strings containing the names defined by a module.\nThe list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example \u2212\n\n#!/usr/bin/python\n\n# Import built-in module math\nimport math\n\ncontent = dir(math)\nprint content\n\nWhen the above code is executed, it produces the following result \u2212\n\n['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', \n'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', \n'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',\n'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', \n'sqrt', 'tan', 'tanh']\n\nHere, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d9d35215f55e3d634525db3df4703a6f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.\nIf locals() is called from within a function, it will return all the names that can be accessed locally from that function.\nIf globals() is called from within a function, it will return all the names that can be accessed globally from that function.\nThe return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7aa037050dadd7a9af9b2f5eea8b7aae", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When the module is imported into a script, the code in the top-level portion of a module is executed only once.\nTherefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this \u2212\n\nreload(module_name)\n\nHere, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following \u2212\n\nreload(hello)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2b2d722678e5bf7668ad724c0923b546", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a7f72ac4338331bcb243b732073f91bb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows \u2212\n\n#!/usr/bin/python\n\nprint \"Python is really a great language,\", \"isn't it?\"\n\nThis produces the following result on your standard screen \u2212\n\nPython is really a great language, isn't it?", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5dc0e59bfc267a2a7c0838d13fda04ee", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are \u2212\n\nraw_input\ninput", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8112685bdaf78dc2d13a10cd9af882af", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).\n\n#!/usr/bin/python\n\nstr = raw_input(\"Enter your input: \")\nprint \"Received input is : \", str\n\nThis prompts you to enter any string and it would display same string on the screen. When I typed \"Hello Python!\", its output is like this \u2212\n\nEnter your input: Hello Python\nReceived input is : Hello Python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3365d8fbfd12e90da1992f4c13687c6e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.\n\n#!/usr/bin/python\n\nstr = input(\"Enter your input: \")\nprint \"Received input is : \", str\n\nThis would produce the following result against the entered input \u2212\n\nEnter your input: [x*5 for x in range(2,10,2)]\nRecieved input is : [10, 20, 30, 40]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cee0adeceeaef4a21009b7c2d9bd4bed", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.\nPython provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4cabdf583be65cd7f98fcb2ad0a0827b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "619f0b4c57d280a1104dbd59ea235933", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "file object = open(file_name [, access_mode][, buffering])\n\nHere are parameter details \u2212\n\nfile_name \u2212 The file_name argument is a string value that contains the name of the file that you want to access.\naccess_mode \u2212 The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).\nbuffering \u2212 If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).\n\nHere is a list of the different modes of opening a file \u2212\n\n\nSr.No.\nModes & Description\n\n\n1\nr\nOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.\n\n\n2\nrb\nOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.\n\n\n3\nr+\nOpens a file for both reading and writing. The file pointer placed at the beginning of the file.\n\n\n4\nrb+\nOpens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.\n\n\n5\nw\nOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.\n\n\n6\nwb\nOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.\n\n\n7\nw+\nOpens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.\n\n\n8\nwb+\nOpens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.\n\n\n9\na\nOp", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5d202f9c3fc28ebf4f1322cd3050edd4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "ens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.\n\n\n10\nab\nOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.\n\n\n11\na+\nOpens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.\n\n\n12\nab+\nOpens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7b72603bc8e7f7c8c7b834e11142493c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once a file is opened and you have one file object, you can get various information related to that file.\nHere is a list of all attributes related to file object \u2212\n\n\nSr.No.\nAttribute & Description\n\n\n1\nfile.closed\nReturns true if file is closed, false otherwise.\n\n\n2\nfile.mode\nReturns access mode with which file was opened.\n\n\n3\nfile.name\nReturns name of the file.\n\n\n4\nfile.softspace\nReturns false if space explicitly required with print, true otherwise.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0d8af485c9cd30255dbc49f46d6fb89c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\nprint \"Closed or not : \", fo.closed\nprint \"Opening mode : \", fo.mode\nprint \"Softspace flag : \", fo.softspace\n\nThis produces the following result \u2212\n\nName of the file: foo.txt\nClosed or not : False\nOpening mode : wb\nSoftspace flag : 0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "641f32ba8886414bd806d51238b28035", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.\nPython automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9b9230b8784a710ed6fec157d9c72807", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4637b1d3999fc987016d46916f082429", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\n\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nName of the file: foo.txt", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "81c6c28b3bbe5aa22863c9e47dff881b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8241a0a3dd8e480bc7b1aeefe8c6310e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.\nThe write() method does not add a newline character ('\\n') to the end of the string \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cb4855f15d66202d3ab314fc303a1010", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.write(string)\n\nHere, passed parameter is the content to be written into the opened file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "10afb5455bbcf4f6bda19dfe3e26a190", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nfo.write( \"Python is a great language.\\nYeah its great!!\\n\")\n\n# Close opend file\nfo.close()\n\nThe above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.\n\nPython is a great language.\nYeah its great!!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9e45034eefa5d04d76cd4fbcea817e8a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "be6a313cc0d260bece85b69bd688e106", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.read([count])\n\nHere, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3458ada8647b7107b0002f5143cbf0c0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let's take a file foo.txt, which we created above.\n\n#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10);\nprint \"Read String is : \", str\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nRead String is : Python is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "23d7c3e6441bb0bbc6ee6f484390fefc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.\nThe seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.\nIf from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "630dfe50f078771ae10949363f24f930", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us take a file foo.txt, which we created above.\n\n#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10)\nprint \"Read String is : \", str\n\n# Check current position\nposition = fo.tell()\nprint \"Current file position : \", position\n\n# Reposition pointer at the beginning once again\nposition = fo.seek(0, 0);\nstr = fo.read(10)\nprint \"Again read String is : \", str\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nRead String is : Python is\nCurrent file position : 10\nAgain read String is : Python is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f4f9f72e17e7097730d870999aeca684", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.\nTo use this module you need to import it first and then you can call any related functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b60e80823c183365d8f42d847b6bcf85", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The rename() method takes two arguments, the current filename and the new filename.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a7bba1fcd78ec2c854588fc3b448bb39", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.rename(current_file_name, new_file_name)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8980148f0d85e07d18d01ad50c7541ac", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to rename an existing file test1.txt \u2212\n\n#!/usr/bin/python\nimport os\n\n# Rename a file from test1.txt to test2.txt\nos.rename( \"test1.txt\", \"test2.txt\" )", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0e18ff820a464aa980e195ae4b0296b4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "363f4ce2954d15eab059f3df277df816", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.remove(file_name)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1acfeb30c1e0d443409599bdb6a75101", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to delete an existing file test2.txt \u2212\n\n#!/usr/bin/python\nimport os\n\n# Delete file test2.txt\nos.remove(\"text2.txt\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5db80c98c7c30aef3cb6fc066556d8c1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9cee4ae62cb0b798455c135576c84c79", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "04112dd517c5168545112d61b805e546", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.mkdir(\"newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9a434de786149263590cfce38cbad554", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to create a directory test in the current directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# Create a directory \"test\"\nos.mkdir(\"test\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c58bab165806b318ff2bc9c5baf51745", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a704605500ec6c02f577d2c96f1a6f57", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.chdir(\"newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "02575c332f848b6f34ce8bbbf09dc602", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to go into \"/home/newdir\" directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# Changing a directory to \"/home/newdir\"\nos.chdir(\"/home/newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "62043853110216e13bb9e9168fb26422", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The getcwd() method displays the current working directory.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fe725f7171511a4e09b3526b287a8bd6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.getcwd()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6202e3227dfb6d1a7c071a0cfd05f195", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to give current directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# This would give location of the current directory\nos.getcwd()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "72bee4683124e133d23b67f4652bc699", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The rmdir() method deletes the directory, which is passed as an argument in the method.\nBefore removing a directory, all the contents in it should be removed.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fc504229f41d921a6adcdbf43d73664e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.rmdir('dirname')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "050c479377e9cf622b4c512d49e974c6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to remove \"/tmp/test\" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.\n\n#!/usr/bin/python\nimport os\n\n# This would remove \"/tmp/test\" directory.\nos.rmdir( \"/tmp/test\" )", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cdf31e3e325df90b80a3969689760614", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them \u2212\n\nException Handling \u2212 This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions.\nAssertions \u2212 This would be covered in Assertions in Python tutorial.\n\nList of Standard Exceptions \u2212\n\n\nSr.No.\nException Name & Description\n\n\n1\nException\nBase class for all exceptions\n\n\n2\nStopIteration\nRaised when the next() method of an iterator does not point to any object.\n\n\n3\nSystemExit\nRaised by the sys.exit() function.\n\n\n4\nStandardError\nBase class for all built-in exceptions except StopIteration and SystemExit.\n\n\n5\nArithmeticError\nBase class for all errors that occur for numeric calculation.\n\n\n6\nOverflowError\nRaised when a calculation exceeds maximum limit for a numeric type.\n\n\n7\nFloatingPointError\nRaised when a floating point calculation fails.\n\n\n8\nZeroDivisionError\nRaised when division or modulo by zero takes place for all numeric types.\n\n\n9\nAssertionError\nRaised in case of failure of the Assert statement.\n\n\n10\nAttributeError\nRaised in case of failure of attribute reference or assignment.\n\n\n11\nEOFError\nRaised when there is no input from either the raw_input() or input() function and the end of file is reached.\n\n\n12\nImportError\nRaised when an import statement fails.\n\n\n13\nKeyboardInterrupt\nRaised when the user interrupts program execution, usually by pressing Ctrl+c.\n\n\n14\nLookupError\nBase class for all lookup errors.\n\n\n15\nIndexError\nRaised when an index is not found in a sequence.\n\n\n16\nKeyError\nRaised when the specified key is not found in the dictionary.\n\n\n17\nNameError\nRaised when an identifier is not found in the local or global namespace.\n\n\n18\nUnboundLocalError\nRaised when trying to access a local variable in a function or method but no value has been assigned to it.\n\n\n19\nEnvironmentError\nBase class for all exceptions that occur outside the Python environment.\n\n\n20\nIOError\nRaised when an input/ output operation fails, such as the", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9b23944353851464b94b350927cb82a6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": " print statement or the open() function when trying to open a file that does not exist.\n\n\n21\nIOError\nRaised for operating system-related errors.\n\n\n22\nSyntaxError\nRaised when there is an error in Python syntax.\n\n\n23\nIndentationError\nRaised when indentation is not specified properly.\n\n\n24\nSystemError\nRaised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.\n\n\n25\nSystemExit\nRaised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.\n\n\n26\nTypeError\nRaised when an operation or function is attempted that is invalid for the specified data type.\n\n\n27\nValueError\nRaised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.\n\n\n28\nRuntimeError\nRaised when a generated error does not fall into any category.\n\n\n29\nNotImplementedError\nRaised when an abstract method that needs to be implemented in an inherited class is not actually implemented.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6cb4129ec9b54a028321a8e5e1e361f6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.\nThe easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.\nAssertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.\nProgrammers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7b4c330cff8efbed3b300222850b6f9b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.\nThe syntax for assert is \u2212\n\nassert Expression[, Arguments]\n\nIf the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "edeadb0b8eaa983e562067b0b59d520b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature \u2212\n\n#!/usr/bin/python\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\nprint KelvinToFahrenheit(273)\nprint int(KelvinToFahrenheit(505.78))\nprint KelvinToFahrenheit(-5)\n\nWhen the above code is executed, it produces the following result \u2212\n\n32.0\n451\nTraceback (most recent call last):\nFile \"test.py\", line 9, in <module>\nprint KelvinToFahrenheit(-5)\nFile \"test.py\", line 4, in KelvinToFahrenheit\nassert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0fb2a40a1f2c3b05a9a3f8f877256750", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.\nWhen a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "74a7e09efc525b8a03afea052e1161e4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "be494c9b8fcad01c6e6cde068355d112", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is simple syntax of try....except...else blocks \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept ExceptionI:\n If there is ExceptionI, then execute this block.\nexcept ExceptionII:\n If there is ExceptionII, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n\nHere are few important points about the above-mentioned syntax \u2212\n\nA single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.\nYou can also provide a generic except clause, which handles any exception.\nAfter the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.\nThe else-block is a good place for code that does not need the try: block's protection.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "da8d96461f5f5e0206a26bfae24279a6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"\n fh.close()\n\nThis produces the following result \u2212\n\nWritten content in the file successfully", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "48df28b70714d930ffef263d43c2195d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example tries to open a file where you do not have write permission, so it raises an exception \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"r\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"\n\nThis produces the following result \u2212\n\nError: can't find file or read data", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "56ff687ca900c389c338aacb4f609d19", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can also use the except statement with no exceptions defined as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept:\n If there is any exception, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n\nThis kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a8236406f953573253ce760a9730b6cd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can also use the same except statement to handle multiple exceptions as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept(Exception1[, Exception2[,...ExceptionN]]]):\n If there is any exception from the given exception list, \n then execute this block.\n ......................\nelse:\n If there is no exception then execute this block.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "be800a3fd9d79a7bd697a3cdaa1b748d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block\nraised an exception or not. The syntax of the try-finally statement is this \u2212\n\ntry:\n You do your operations here;\n ......................\n Due to any exception, this may be skipped.\nfinally:\n This would always be executed.\n ......................\n\nYou cannot use else clause as well along with a finally clause.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "460d07bced026a18d004c5ea9f9c1096", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nfinally:\n print \"Error: can\\'t find file or read data\"\n\nIf you do not have permission to open the file in writing mode, then this will produce the following result \u2212\n\nError: can't find file or read data\n\nSame example can be written more cleanly as follows \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n try:\n fh.write(\"This is my test file for exception handling!!\")\n finally:\n print \"Going to close the file\"\n fh.close()\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\n\nWhen an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "07d939b80ab0963edc846771457a164e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept ExceptionType, Argument:\n You can print value of Argument here...\n\nIf you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.\nThis variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6e7718bd6d8a88730afb3852060cc8a5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is an example for a single exception \u2212\n\n#!/usr/bin/python\n\n# Define a function here.\ndef temp_convert(var):\n try:\n return int(var)\n except ValueError, Argument:\n print \"The argument does not contain numbers\\n\", Argument\n\n# Call above function here.\ntemp_convert(\"xyz\");\n\nThis produces the following result \u2212\n\nThe argument does not contain numbers\ninvalid literal for int() with base 10: 'xyz'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "80aebe46495c5e7f0e741f1b3a7dd1da", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a2ef93fe16aa2412b9e5ea87a7669252", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "raise [Exception [, args [, traceback]]]\n\nHere, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.\nThe final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b2cd771b571d22d6e98ff7af515a8355", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows \u2212\n\ndef functionName( level ):\n if level < 1:\n raise \"Invalid level!\", level\n # The code below to this would not be executed\n # if we raise the exception\n\nNote: In order to catch an exception, an \"except\" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows \u2212\n\ntry:\n Business Logic here...\nexcept \"Invalid level!\":\n Exception handling here...\nelse:\n Rest of the code here...", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "983b1154dc316692a391cabd818d0021", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.\nIf you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.\nHowever, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1628f30a55f9f1601d6b9d2319064361", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Class \u2212 A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.\nClass variable \u2212 A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.\nData member \u2212 A class variable or instance variable that holds data associated with a class and its objects.\nFunction overloading \u2212 The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.\nInstance variable \u2212 A variable that is defined inside a method and belongs only to the current instance of a class.\nInheritance \u2212 The transfer of the characteristics of a class to other classes that are derived from it.\nInstance \u2212 An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.\nInstantiation \u2212 The creation of an instance of a class.\nMethod \u2212 A special kind of function that is defined in a class definition.\nObject \u2212 A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.\nOperator overloading \u2212 The assignment of more than one function to a particular operator.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eef4dfda6eaccf2564ebbcbbd7a090bd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows \u2212\n\nclass ClassName:\n 'Optional class documentation string'\n class_suite\n\n\nThe class has a documentation string, which can be accessed via ClassName.__doc__.\nThe class_suite consists of all the component statements defining class members, data attributes and functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "42834f1d5ec7d9e45eeb066177423b3b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example of a simple Python class \u2212\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\n\nThe variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.\nThe first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.\nYou declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1cb9d0602286426037e95ea5cd2204ac", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.\n\n\"This would create first object of Employee class\"\nemp1 = Employee(\"Zara\", 2000)\n\"This would create second object of Employee class\"\nemp2 = Employee(\"Manni\", 5000)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a812ea0e0116fa5eccbecae89f83297", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows \u2212\n\nemp1.displayEmployee()\nemp2.displayEmployee()\nprint \"Total Employee %d\" % Employee.empCount\n\nNow, putting all the concepts together \u2212\n\n#!/usr/bin/python\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\n\"This would create first object of Employee class\"\nemp1 = Employee(\"Zara\", 2000)\n\"This would create second object of Employee class\"\nemp2 = Employee(\"Manni\", 5000)\nemp1.displayEmployee()\nemp2.displayEmployee()\nprint \"Total Employee %d\" % Employee.empCount\n\nWhen the above code is executed, it produces the following result \u2212\n\nName : Zara ,Salary: 2000\nName : Manni ,Salary: 5000\nTotal Employee 2\n\nYou can add, remove, or modify attributes of classes and objects at any time \u2212\n\nemp1.age = 7 # Add an 'age' attribute.\nemp1.age = 8 # Modify 'age' attribute.\ndel emp1.age # Delete 'age' attribute.\n\nInstead of using the normal statements to access attributes, you can use the following functions \u2212\n\nThe getattr(obj, name[, default]) \u2212 to access the attribute of object.\nThe hasattr(obj,name) \u2212 to check if an attribute exists or not.\nThe setattr(obj,name,value) \u2212 to set an attribute. If attribute does not exist, then it would be created.\nThe delattr(obj, name) \u2212 to delete an attribute.\n\n\nhasattr(emp1, 'age') # Returns true if 'age' attribute exists\ngetattr(emp1, 'age') # Returns value of 'age' attribute\nsetattr(emp1, 'age', 8) # Set attribute 'age' at 8\ndelattr(empl, 'age') # Delete attribute 'age'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "73dfa034f4489145105d12b6815e0cbb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute \u2212\n\n__dict__ \u2212 Dictionary containing the class's namespace.\n__doc__ \u2212 Class documentation string or none, if undefined. \n__name__ \u2212 Class name.\n__module__ \u2212 Module name in which the class is defined. This attribute is \"__main__\" in interactive mode. \n__bases__ \u2212 A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.\n\nFor the above class let us try to access all these attributes \u2212\n\n#!/usr/bin/python\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\nprint \"Employee.__doc__:\", Employee.__doc__\nprint \"Employee.__name__:\", Employee.__name__\nprint \"Employee.__module__:\", Employee.__module__\nprint \"Employee.__bases__:\", Employee.__bases__\nprint \"Employee.__dict__:\", Employee.__dict__\n\nWhen the above code is executed, it produces the following result \u2212\n\nEmployee.__doc__: Common base class for all employees\nEmployee.__name__: Employee\nEmployee.__module__: __main__\nEmployee.__bases__: ()\nEmployee.__dict__: {'__module__': '__main__', 'displayCount':\n<function displayCount at 0xb7c84994>, 'empCount': 2, \n'displayEmployee': <function displayEmployee at 0xb7c8441c>, \n'__doc__': 'Common base class for all employees', \n'__init__': <function __init__ at 0xb7c846bc>}", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "220adb8f7204041221b6a9c2023798c1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.\nPython's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.\nAn object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.\n\na = 40 # Create object <40>\nb = a # Increase ref. count of <40> \nc = [b] # Increase ref. count of <40> \n\ndel a # Decrease ref. count of <40>\nb = 100 # Decrease ref. count of <40> \nc[0] = -1 # Decrease ref. count of <40> \n\nYou normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "41159a5e1eb374f3cbacf33bcbc92b01", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This __del__() destructor prints the class name of an instance that is about to be destroyed \u2212\n\n#!/usr/bin/python\n\nclass Point:\n def __init__( self, x=0, y=0):\n self.x = x\n self.y = y\n def __del__(self):\n class_name = self.__class__.__name__\n print class_name, \"destroyed\"\n\npt1 = Point()\npt2 = pt1\npt3 = pt1\nprint id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts\ndel pt1\ndel pt2\ndel pt3\n\nWhen the above code is executed, it produces following result \u2212\n\n3083401324 3083401324 3083401324\nPoint destroyed\n\nNote \u2212 Ideally, you should define your classes in separate file, then you should import them in your main program file using import statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e1e25327b6b2afdbdce84f33dd07c59b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.\nThe child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0dad3da7e90ceb9e377b1701825d3c17", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name \u2212\n\nclass SubClassName (ParentClass1[, ParentClass2, ...]):\n 'Optional class documentation string'\n class_suite", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "17111e88da8ba34d82c2527a7c5f0f1b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Parent: # define parent class\n parentAttr = 100\n def __init__(self):\n print \"Calling parent constructor\"\n\n def parentMethod(self):\n print 'Calling parent method'\n\n def setAttr(self, attr):\n Parent.parentAttr = attr\n\n def getAttr(self):\n print \"Parent attribute :\", Parent.parentAttr\n\nclass Child(Parent): # define child class\n def __init__(self):\n print \"Calling child constructor\"\n\n def childMethod(self):\n print 'Calling child method'\n\nc = Child() # instance of child\nc.childMethod() # child calls its method\nc.parentMethod() # calls parent's method\nc.setAttr(200) # again call parent's method\nc.getAttr() # again call parent's method\n\nWhen the above code is executed, it produces the following result \u2212\n\nCalling child constructor\nCalling child method\nCalling parent method\nParent attribute : 200\n\nSimilar way, you can drive a class from multiple parent classes as follows \u2212\n\nclass A: # define your class A\n.....\n\nclass B: # define your class B\n.....\n\nclass C(A, B): # subclass of A and B\n.....\n\nYou can use issubclass() or isinstance() functions to check a relationships of two classes and instances.\n\nThe issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.\nThe isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9fdc171d7e406896a6181cda04e88596", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fd5dc6199deaf7441da864b11f879427", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Parent: # define parent class\n def myMethod(self):\n print 'Calling parent method'\n\nclass Child(Parent): # define child class\n def myMethod(self):\n print 'Calling child method'\n\nc = Child() # instance of child\nc.myMethod() # child calls overridden method\n\nWhen the above code is executed, it produces the following result \u2212\n\nCalling child method", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1b0105e8973e7d5e47620e385a0267a8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following table lists some generic functionality that you can override in your own classes \u2212\n\n\nSr.No.\nMethod, Description & Sample Call\n\n\n1\n__init__ ( self [,args...] )\nConstructor (with any optional arguments)\nSample Call : obj = className(args)\n\n\n2\n__del__( self )\nDestructor, deletes an object\nSample Call : del obj\n\n\n3\n__repr__( self )\nEvaluable string representation\nSample Call : repr(obj)\n\n\n4\n__str__( self )\nPrintable string representation\nSample Call : str(obj)\n\n\n5\n__cmp__ ( self, x )\nObject comparison\nSample Call : cmp(obj, x)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6038639149eb8c5ebda713280a28c8fe", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.\nYou could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7caeda80eefa1314da1f4d56571a6ddb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Vector:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def __str__(self):\n return 'Vector (%d, %d)' % (self.a, self.b)\n \n def __add__(self,other):\n return Vector(self.a + other.a, self.b + other.b)\n\nv1 = Vector(2,10)\nv2 = Vector(5,-2)\nprint v1 + v2\n\nWhen the above code is executed, it produces the following result \u2212\n\nVector(7,8)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3ed35f9ad3c79c7e9a5226cc7bb2c097", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6bd91fcc97225549d0b7790ef4039a3a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.\nThe Python module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.\nWe would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "960f03a0ec3039fe62c4ec9d9e4866f7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This function attempts to match RE pattern to string with optional flags.\nHere is the syntax for this function \u2212\n\nre.match(pattern, string, flags=0)\n\nHere is the description of the parameters \u2212\n\n\nSr.No.\nParameter & Description\n\n\n1\npattern\nThis is the regular expression to be matched.\n\n\n2\nstring\nThis is the string, which would be searched to match the pattern at the beginning of string.\n\n\n3\nflags\nYou can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.\n\n\nThe re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.\n\n\nSr.No.\nMatch Object Method & Description\n\n\n1\ngroup(num=0)\nThis method returns entire match (or specific subgroup num)\n\n\n2\ngroups()\nThis method returns all matching subgroups in a tuple (empty if there weren't any)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "aeb67d9a614db7f94caafd6a4634f418", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\"\n\nmatchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)\n\nif matchObj:\n print \"matchObj.group() : \", matchObj.group()\n print \"matchObj.group(1) : \", matchObj.group(1)\n print \"matchObj.group(2) : \", matchObj.group(2)\nelse:\n print \"No match!!\"\n\nWhen the above code is executed, it produces following result \u2212\n\nmatchObj.group() : Cats are smarter than dogs\nmatchObj.group(1) : Cats\nmatchObj.group(2) : smarter", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ce0cb91dab32627f6823c3230474d54f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This function searches for first occurrence of RE pattern within string with optional flags.\nHere is the syntax for this function \u2212\n\nre.search(pattern, string, flags=0)\n\nHere is the description of the parameters \u2212\n\n\nSr.No.\nParameter & Description\n\n\n1\npattern\nThis is the regular expression to be matched.\n\n\n2\nstring\nThis is the string, which would be searched to match the pattern anywhere in the string.\n\n\n3\nflags\nYou can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.\n\n\nThe re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression.\n\n\nSr.No.\nMatch Object Methods & Description\n\n\n1\ngroup(num=0)\nThis method returns entire match (or specific subgroup num)\n\n\n2\ngroups()\nThis method returns all matching subgroups in a tuple (empty if there weren't any)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4fe2ab444118533c40065692e19ce157", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\";\n\nsearchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)\n\nif searchObj:\n print \"searchObj.group() : \", searchObj.group()\n print \"searchObj.group(1) : \", searchObj.group(1)\n print \"searchObj.group(2) : \", searchObj.group(2)\nelse:\n print \"Nothing found!!\"\n\nWhen the above code is executed, it produces following result \u2212\n\nsearchObj.group() : Cats are smarter than dogs\nsearchObj.group(1) : Cats\nsearchObj.group(2) : smarter", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4e0d6eac4acbc2935dca4f5ee6f3970e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4a179326323f754a38d0b8e006801114", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\";\n\nmatchObj = re.match( r'dogs', line, re.M|re.I)\nif matchObj:\n print \"match --> matchObj.group() : \", matchObj.group()\nelse:\n print \"No match!!\"\n\nsearchObj = re.search( r'dogs', line, re.M|re.I)\nif searchObj:\n print \"search --> searchObj.group() : \", searchObj.group()\nelse:\n print \"Nothing found!!\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nNo match!!\nsearch --> searchObj.group() : dogs", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c65275c71eafd520dd904fc61f8a481d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "One of the most important re methods that use regular expressions is sub.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b5d3b17d6ee608c9dcbd6755bb46ac3b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "re.sub(pattern, repl, string, max=0)\n\nThis method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2c7b1e24ddbd15a7a9ade346bb9733f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nphone = \"2004-959-559 # This is Phone Number\"\n\n# Delete Python-style comments\nnum = re.sub(r'#.*$', \"\", phone)\nprint \"Phone Num : \", num\n\n# Remove anything other than digits\nnum = re.sub(r'\\D', \"\", phone) \nprint \"Phone Num : \", num\n\nWhen the above code is executed, it produces the following result \u2212\n\nPhone Num : 2004-959-559\nPhone Num : 2004959559", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cc8cc094dec7c4a93e5dfeff16611b13", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these \u2212\n\n\nSr.No.\nModifier & Description\n\n\n1\nre.I\nPerforms case-insensitive matching.\n\n\n2\nre.L\nInterprets words according to the current locale. This interpretation affects the alphabetic group (\\w and \\W), as well as word boundary behavior(\\b and \\B).\n\n\n3\nre.M\nMakes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).\n\n\n4\nre.S\nMakes a period (dot) match any character, including a newline.\n\n\n5\nre.U\nInterprets letters according to the Unicode character set. This flag affects the behavior of \\w, \\W, \\b, \\B.\n\n\n6\nre.X\nPermits \"cuter\" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f7c8aa7a1621060828d2e8bf94d89040", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \\), all characters match themselves. You can escape a control character by preceding it with a backslash.\nFollowing table lists the regular expression syntax that is available in Python \u2212\n\n\nSr.No.\nPattern & Description\n\n\n1\n^\nMatches beginning of line.\n\n\n2\n$\nMatches end of line.\n\n\n3\n.\nMatches any single character except newline. Using m option allows it to match newline as well.\n\n\n4\n[...]\nMatches any single character in brackets.\n\n\n5\n[^...]\nMatches any single character not in brackets\n\n\n6\nre*\nMatches 0 or more occurrences of preceding expression.\n\n\n7\nre+\nMatches 1 or more occurrence of preceding expression.\n\n\n8\nre?\nMatches 0 or 1 occurrence of preceding expression.\n\n\n9\nre{ n}\nMatches exactly n number of occurrences of preceding expression.\n\n\n10\nre{ n,}\nMatches n or more occurrences of preceding expression.\n\n\n11\nre{ n, m}\nMatches at least n and at most m occurrences of preceding expression.\n\n\n12\na| b\nMatches either a or b.\n\n\n13\n(re)\nGroups regular expressions and remembers matched text.\n\n\n14\n(?imx)\nTemporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.\n\n\n15\n(?-imx)\nTemporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.\n\n\n16\n(?: re)\nGroups regular expressions without remembering matched text.\n\n\n17\n(?imx: re)\nTemporarily toggles on i, m, or x options within parentheses.\n\n\n18\n(?-imx: re)\nTemporarily toggles off i, m, or x options within parentheses.\n\n\n19\n(?#...)\nComment.\n\n\n20\n(?= re)\nSpecifies position using a pattern. Doesn't have a range.\n\n\n21\n(?! re)\nSpecifies position using pattern negation. Doesn't have a range.\n\n\n22\n(?> re)\nMatches independent pattern without backtracking.\n\n\n23\n\\w\nMatches word characters.\n\n\n24\n\\W\nMatches nonword characters.\n\n\n25\n\\s\nMatches whitespace. Equivalent to [\\t\\n\\r\\f].\n\n\n26\n\\S\nMatches nonwhitespace.\n\n\n27\n\\d\nMatches digits. Equivalent to [0-9].\n\n\n28\n\\D\nMatches nondigits.\n\n\n29\n\\A\nMatches beginning of string.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "361b33143279596534eb2d8f5f20ebfb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\n\n\n30\n\\Z\nMatches end of string. If a newline exists, it matches just before newline.\n\n\n31\n\\z\nMatches end of string.\n\n\n32\n\\G\nMatches point where last match finished.\n\n\n33\n\\b\nMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.\n\n\n34\n\\B\nMatches nonword boundaries.\n\n\n35\n\\n, \\t, etc.\nMatches newlines, carriage returns, tabs, etc.\n\n\n36\n\\1...\\9\nMatches nth grouped subexpression.\n\n\n37\n\\10\nMatches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c575d374a3b623e943883cf5b8b5e298", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\npython\nMatch \"python\".", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "18deef92c47932f5987608d98cb84d36", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n[Pp]ython\nMatch \"Python\" or \"python\"\n\n\n2\nrub[ye]\nMatch \"ruby\" or \"rube\"\n\n\n3\n[aeiou]\nMatch any one lowercase vowel\n\n\n4\n[0-9]\nMatch any digit; same as [0123456789]\n\n\n5\n[a-z]\nMatch any lowercase ASCII letter\n\n\n6\n[A-Z]\nMatch any uppercase ASCII letter\n\n\n7\n[a-zA-Z0-9]\nMatch any of the above\n\n\n8\n[^aeiou]\nMatch anything other than a lowercase vowel\n\n\n9\n[^0-9]\nMatch anything other than a digit", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f2dfe2bd50c78340a21b0ff2eec32962", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n.\nMatch any character except newline\n\n\n2\n\\d\nMatch a digit: [0-9]\n\n\n3\n\\D\nMatch a nondigit: [^0-9]\n\n\n4\n\\s\nMatch a whitespace character: [ \\t\\r\\n\\f]\n\n\n5\n\\S\nMatch nonwhitespace: [^ \\t\\r\\n\\f]\n\n\n6\n\\w\nMatch a single word character: [A-Za-z0-9_]\n\n\n7\n\\W\nMatch a nonword character: [^A-Za-z0-9_]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c970896d0aa6c22ee4409984bc2f382f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\nruby?\nMatch \"rub\" or \"ruby\": the y is optional\n\n\n2\nruby*\nMatch \"rub\" plus 0 or more ys\n\n\n3\nruby+\nMatch \"rub\" plus 1 or more ys\n\n\n4\n\\d{3}\nMatch exactly 3 digits\n\n\n5\n\\d{3,}\nMatch 3 or more digits\n\n\n6\n\\d{3,5}\nMatch 3, 4, or 5 digits", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "09f35e3ed4feb0b56b1cee20d72f6c8d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This matches the smallest number of repetitions \u2212\n\n\nSr.No.\nExample & Description\n\n\n1\n<.*>\nGreedy repetition: matches \"<python>perl>\"\n\n\n2\n<.*?>\nNongreedy: matches \"<python>\" in \"<python>perl>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4e34c9a5886bf2257ddacbb9c64c3f43", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n\\D\\d+\nNo group: + repeats \\d\n\n\n2\n(\\D\\d)+\nGrouped: + repeats \\D\\d pair\n\n\n3\n([Pp]ython(, )?)+\nMatch \"Python\", \"Python, python, python\", etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cbf5e3ffe8821185449dc5d5bcf1ccfd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This matches a previously matched group again \u2212\n\n\nSr.No.\nExample & Description\n\n\n1\n([Pp])ython&\\1ails\nMatch python&pails or Python&Pails\n\n\n2\n(['\"])[^\\1]*\\1\nSingle or double-quoted string. \\1 matches whatever the 1st group matched. \\2 matches whatever the 2nd group matched, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e2a1d92ab6ee5575d591a9fcb22b2841", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\npython|perl\nMatch \"python\" or \"perl\"\n\n\n2\nrub(y|le))\nMatch \"ruby\" or \"ruble\"\n\n\n3\nPython(!+|\\?)\n\"Python\" followed by one or more ! or one ?", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "aefeead651746e126e61898b57079a27", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This needs to specify match position.\n\n\nSr.No.\nExample & Description\n\n\n1\n^Python\nMatch \"Python\" at the start of a string or internal line\n\n\n2\nPython$\nMatch \"Python\" at the end of a string or line\n\n\n3\n\\APython\nMatch \"Python\" at the start of a string\n\n\n4\nPython\\Z\nMatch \"Python\" at the end of a string\n\n\n5\n\\bPython\\b\nMatch \"Python\" at a word boundary\n\n\n6\n\\brub\\B\n\\B is nonword boundary: match \"rub\" in \"rube\" and \"ruby\" but not alone\n\n\n7\nPython(?=!)\nMatch \"Python\", if followed by an exclamation point.\n\n\n8\nPython(?!!)\nMatch \"Python\", if not followed by an exclamation point.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7ce4fa307112ea4d464c7a249732260c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0482863b34d869176f7db61debfd03b5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.\nThe current version is CGI/1.1 and CGI/1.2 is under progress.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e5a0dba276f67da852d5863efeb62587", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.\n\nYour browser contacts the HTTP web server and demands for the URL, i.e., filename.\nWeb Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.\nWeb browser takes response from web server and displays either the received file or error message.\n\nHowever, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f401cbf8ceafdb16aeb6f86e143f3d88", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well.\nBy default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file \u2212\n\n<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n\n<Directory \"/var/www/cgi-bin\">\nOptions All\n</Directory>\n\nHere, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "32b4d1f4ce96c986a0ffc0ef4b30e5d4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.\n\n#!/usr/bin/python\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint '<html>'\nprint '<head>'\nprint '<title>Hello World - First CGI Program</title>'\nprint '</head>'\nprint '<body>'\nprint '<h2>Hello World! This is my first CGI program</h2>'\nprint '</body>'\nprint '</html>'\n\nIf you click hello.py, then this produces the following output \u2212\n\n\n\nHello World! This is my first CGI program\n\n\n\nThis hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\\r\\n\\r\\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen.\nBy now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3ed95846873f08f29591d09fbf7e14cf", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The line Content-type:text/html\\r\\n\\r\\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form \u2212\n\nHTTP Field Name: Field Content\n\nFor Example\nContent-type: text/html\\r\\n\\r\\n\n\nThere are few other important HTTP headers, which you will use frequently in your CGI Programming.\n\n\nSr.No.\nHeader & Description\n\n\n1\nContent-type:\nA MIME string defining the format of the file being returned. Example is Content-type:text/html\n\n\n2\nExpires: Date\nThe date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.\n\n\n3\nLocation: URL\nThe URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.\n\n\n4\nLast-modified: Date\nThe date of last modification of the resource.\n\n\n5\nContent-length: N\nThe length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.\n\n\n6\nSet-Cookie: String\nSet the cookie passed through the string", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e597580724ea5ea8f4abb1694dc71331", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program.\n\n\nSr.No.\nVariable Name & Description\n\n\n1\nCONTENT_TYPE\nThe data type of the content. Used when the client is sending attached content to the server. For example, file upload.\n\n\n2\nCONTENT_LENGTH\nThe length of the query information. It is available only for POST requests.\n\n\n3\nHTTP_COOKIE\nReturns the set cookies in the form of key & value pair.\n\n\n4\nHTTP_USER_AGENT\nThe User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser.\n\n\n5\nPATH_INFO\nThe path for the CGI script.\n\n\n6\nQUERY_STRING\nThe URL-encoded information that is sent with GET method request.\n\n\n7\nREMOTE_ADDR\nThe IP address of the remote host making the request. This is useful logging or for authentication.\n\n\n8\nREMOTE_HOST\nThe fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address.\n\n\n9\nREQUEST_METHOD\nThe method used to make the request. The most common methods are GET and POST.\n\n\n10\nSCRIPT_FILENAME\nThe full path to the CGI script.\n\n\n11\nSCRIPT_NAME\nThe name of the CGI script.\n\n\n12\nSERVER_NAME\nThe server's hostname or IP Address\n\n\n13\nSERVER_SOFTWARE\nThe name and version of the software the server is running.\n\n\nHere is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment\n\n#!/usr/bin/python\n\nimport os\n\nprint \"Content-type: text/html\\r\\n\\r\\n\";\nprint \"<font size=+1>Environment</font><\\br>\";\nfor param in os.environ.keys():\n print \"<b>%20s</b>: %s<\\br>\" % (param, os.environ[param])", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "44cea043e0e689ebfa8cca1841a5a78e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a6104f977d4a1b69cec9b7b2219aca6e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows \u2212\n\nhttp://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2\n\nThe GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.\nYou can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "06fe7b314843eeb6a2535f19140a4847", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple URL, which passes two values to hello_get.py program using GET method.\n/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI\nBelow is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"\n\nThis would generate the following result \u2212\n\n\n\nHello ZARA ALI", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "03aa21ebc3cfc061db62e73c8278c941", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.\n\n<form action = \"/cgi-bin/hello_get.py\" method = \"get\">\nFirst Name: <input type = \"text\" name = \"first_name\"> <br />\n\nLast Name: <input type = \"text\" name = \"last_name\" />\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nHere is the actual output of the above form, you enter First and Last Name and then click submit button to see the result.\n\nFirst Name: \n\nLast Name:", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dc7ec0bdbd13d60b0f6a73c2650da284", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.\nBelow is same hello_get.py script which handles GET as well as POST method.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"\n\nLet us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.\n\n<form action = \"/cgi-bin/hello_get.py\" method = \"post\">\nFirst Name: <input type = \"text\" name = \"first_name\"><br />\nLast Name: <input type = \"text\" name = \"last_name\" />\n\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nHere is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.\n\nFirst Name: \n\nLast Name:", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cb00e3d9019410b77db4e21c45e67e23", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Checkboxes are used when more than one option is required to be selected.\nHere is example HTML code for a form with two checkboxes \u2212\n\n<form action = \"/cgi-bin/checkbox.cgi\" method = \"POST\" target = \"_blank\">\n<input type = \"checkbox\" name = \"maths\" value = \"on\" /> Maths\n<input type = \"checkbox\" name = \"physics\" value = \"on\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>\n\nThe result of this code is the following form \u2212\n\n Maths\n Physics\n\n\nBelow is checkbox.cgi script to handle input given by web browser for checkbox button.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('maths'):\n math_flag = \"ON\"\nelse:\n math_flag = \"OFF\"\n\nif form.getvalue('physics'):\n physics_flag = \"ON\"\nelse:\n physics_flag = \"OFF\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Checkbox - Third CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> CheckBox Maths is : %s</h2>\" % math_flag\nprint \"<h2> CheckBox Physics is : %s</h2>\" % physics_flag\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2d2d08100a3d167bea7b9c78d816159d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Radio Buttons are used when only one option is required to be selected.\nHere is example HTML code for a form with two radio buttons \u2212\n\n<form action = \"/cgi-bin/radiobutton.py\" method = \"post\" target = \"_blank\">\n<input type = \"radio\" name = \"subject\" value = \"maths\" /> Maths\n<input type = \"radio\" name = \"subject\" value = \"physics\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>\n\nThe result of this code is the following form \u2212\n\n Maths\n Physics\n\n\nBelow is radiobutton.py script to handle input given by web browser for radio button \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('subject'):\n subject = form.getvalue('subject')\nelse:\n subject = \"Not set\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Radio - Fourth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e6b37b8f1b1779536b7aaf9a23985bd3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program.\nHere is example HTML code for a form with a TEXTAREA box \u2212\n\n<form action = \"/cgi-bin/textarea.py\" method = \"post\" target = \"_blank\">\n<textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\nType your text here...\n</textarea>\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nThe result of this code is the following form \u2212\n\nType your text here...\n\n\nBelow is textarea.cgi script to handle input given by web browser \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\";\nprint \"<title>Text Area - Fifth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Entered Text Content is %s</h2>\" % text_content\nprint \"</body>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "be10694b6de36f55bb20391a79ab3577", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Drop Down Box is used when we have many options available but only one or two will be selected.\nHere is example HTML code for a form with one drop down box \u2212\n\n<form action = \"/cgi-bin/dropdown.py\" method = \"post\" target = \"_blank\">\n<select name = \"dropdown\">\n<option value = \"Maths\" selected>Maths</option>\n<option value = \"Physics\">Physics</option>\n</select>\n<input type = \"submit\" value = \"Submit\"/>\n</form>\n\nThe result of this code is the following form \u2212\n\n\nMaths\nPhysics\n\n\n\nBelow is dropdown.py script to handle input given by web browser.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('dropdown'):\n subject = form.getvalue('dropdown')\nelse:\n subject = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Dropdown Box - Sixth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a37e883e770606a921066871d145a01", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages?\nIn many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "39f3398f240c8348669e5f7ef054ba5b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.\nCookies are a plain text data record of 5 variable-length fields \u2212\n\nExpires \u2212 The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.\nDomain \u2212 The domain name of your site.\nPath \u2212 The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.\nSecure \u2212 If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.\nName=Value \u2212 Cookies are set and retrieved in the form of key and value pairs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "98b34838bf373f1aa72c347741ef3d80", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows \u2212\n\n#!/usr/bin/python\n\nprint \"Set-Cookie:UserID = XYZ;\\r\\n\"\nprint \"Set-Cookie:Password = XYZ123;\\r\\n\"\nprint \"Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT\";\\r\\n\"\nprint \"Set-Cookie:Domain = www.tutorialspoint.com;\\r\\n\"\nprint \"Set-Cookie:Path = /perl;\\n\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\n...........Rest of the HTML Content....\n\nFrom this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.\nIt is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68b9ae3c09dc55370f8b5835d9ce7989", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form \u2212\n\nkey1 = value1;key2 = value2;key3 = value3....\n\nHere is an example of how to retrieve cookies.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nfrom os import environ\nimport cgi, cgitb\n\nif environ.has_key('HTTP_COOKIE'):\n for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):\n (key, value ) = split(cookie, '=');\n if key == \"UserID\":\n user_id = value\n\n if key == \"Password\":\n password = value\n\nprint \"User ID = %s\" % user_id\nprint \"Password = %s\" % password\n\nThis produces the following result for the cookies set by above script \u2212\n\nUser ID = XYZ\nPassword = XYZ123", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1ed0d00deae822e1e8399509b2e6f0df", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a \"Browse\" button.\n\n<html>\n<body>\n <form enctype = \"multipart/form-data\" \n action = \"save_file.py\" method = \"post\">\n <p>File: <input type = \"file\" name = \"filename\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n </form>\n</body>\n</html>\n\nThe result of this code is the following form \u2212\n\nFile: \n\n\nAbove example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.\nHere is the script save_file.py to handle file upload \u2212\n\n#!/usr/bin/python\n\nimport cgi, os\nimport cgitb; cgitb.enable()\n\nform = cgi.FieldStorage()\n\n# Get filename here.\nfileitem = form['filename']\n\n# Test if the file was uploaded\nif fileitem.filename:\n # strip leading path from file name to avoid \n # directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('/tmp/' + fn, 'wb').write(fileitem.file.read())\n\n message = 'The file \"' + fn + '\" was uploaded successfully'\n \nelse:\n message = 'No file was uploaded'\n \nprint \"\"\"\\\nContent-Type: text/html\\n\n<html>\n<body>\n <p>%s</p>\n</body>\n</html>\n\"\"\" % (message,)\n\nIf you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.\n\nfn = os.path.basename(fileitem.filename.replace(\"\\\\\", \"/\" ))", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0ff49ae69f94669d993aa6bd24ebc1cb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.\nYou can choose the right database for your application. Python Database API supports a wide range of database servers such as \u2212\n\nGadFly\nmSQL\nMySQL\nPostgreSQL\nMicrosoft SQL Server 2000\nInformix\nInterbase\nOracle\nSybase\n\nHere is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.\nThe DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following \u2212\n\nImporting the API module.\nAcquiring a connection with the database.\nIssuing SQL statements and stored procedures.\nClosing the connection\n\nWe would learn all the concepts using MySQL, so let us talk about MySQLdb module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f7c17693f0ab22c586d7c139f70a9043", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cdad6388cb12115ac037a8f0fc15e1e2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\nIf it produces the following result, then it means MySQLdb module is not installed \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 3, in <module>\n import MySQLdb\nImportError: No module named MySQLdb\n\nTo install MySQLdb module, use the following command \u2212\n\nFor Ubuntu, use the following command -\n$ sudo apt-get install python-pip python-dev libmysqlclient-dev\nFor Fedora, use the following command -\n$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc\nFor Python command prompt, use the following command -\npip install MySQL-python\n\nNote \u2212 Make sure you have root privilege to install above module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b182d565116beaca89eab10130921402", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before connecting to a MySQL database, make sure of the followings \u2212\n\nYou have created a database TESTDB.\nYou have created a table EMPLOYEE in TESTDB.\nThis table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.\nUser ID \"testuser\" and password \"test123\" are set to access TESTDB.\nPython module MySQLdb is installed properly on your machine.\nYou have gone through MySQL tutorial to understand MySQL Basics.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e47084aa7491954275caa04575ffa0d1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example of connecting with MySQL database \"TESTDB\"\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"SELECT VERSION()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nprint \"Database version : %s \" % data\n\n# disconnect from server\ndb.close()\n\nWhile running this script, it is producing the following result in my Linux machine.\n\nDatabase version : 5.0.45\n\nIf a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are released.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "23bdd7e3c4419412c894290a1e6961fd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "98583e8c71c0e040c9ebb3dc1f61703a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us create Database table EMPLOYEE \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Drop table if it already exist using execute() method.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n# Create table as per requirement\nsql = \"\"\"CREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, \n SEX CHAR(1),\n INCOME FLOAT )\"\"\"\n\ncursor.execute(sql)\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "20e9df4d6aa14d86067b104e72f562ec", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is required when you want to create your records into a database table.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e810006f2a759b330c114e75fea83420", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following example, executes SQL INSERT statement to create a record into EMPLOYEE table \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n LAST_NAME, AGE, SEX, INCOME)\n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()\n\nAbove example can be written as follows to create SQL queries dynamically \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"INSERT INTO EMPLOYEE(FIRST_NAME, \\\n LAST_NAME, AGE, SEX, INCOME) \\\n VALUES ('%s', '%s', '%d', '%c', '%d' )\" % \\\n ('Mac', 'Mohan', 20, 'M', 2000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ef319db30ed0d0c85d4ea419cae35967", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following code segment is another form of execution where you can pass parameters directly \u2212\n\n..................................\nuser_id = \"test123\"\npassword = \"password\"\n\ncon.execute('insert into Login values(\"%s\", \"%s\")' % \\\n (user_id, password))\n..................................", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c88c3fea9bf45769066a0dd8628e950d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "READ Operation on any database means to fetch some useful information from the database.\nOnce our database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.\n\nfetchone() \u2212 It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.\nfetchall() \u2212 It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves\nthe remaining rows from the result set.\nrowcount \u2212 This is a read-only attribute and returns the number of rows that were affected by an execute() method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ab48be66ea6f256c4bcf3a2334d5c714", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following procedure queries all the records from EMPLOYEE table having salary more than 1000 \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\nsql = \"SELECT * FROM EMPLOYEE \\\n WHERE INCOME > '%d'\" % (1000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Fetch all the rows in a list of lists.\n results = cursor.fetchall()\n for row in results:\n fname = row[0]\n lname = row[1]\n age = row[2]\n sex = row[3]\n income = row[4]\n # Now print fetched result\n print \"fname=%s,lname=%s,age=%d,sex=%s,income=%d\" % \\\n (fname, lname, age, sex, income )\nexcept:\n print \"Error: unable to fecth data\"\n\n# disconnect from server\ndb.close()\n\nThis will produce the following result \u2212\n\nfname=Mac, lname=Mohan, age=20, sex=M, income=2000", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f83166351c9da7a8d9cba4f0fd3d81c3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "UPDATE Operation on any database means to update one or more records, which are already available in the database.\nThe following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7cda2eaa8336deb8419852054d26d176", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to UPDATE required records\nsql = \"UPDATE EMPLOYEE SET AGE = AGE + 1\n WHERE SEX = '%c'\" % ('M')\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b85faa88f240693e6d0a1cb67e88ee0d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "293879dda4a6641c78aa8c7ca0495116", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4f471001f5f522901fcb31a14617d7d9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Transactions are a mechanism that ensures data consistency. Transactions have the following four properties \u2212\n\nAtomicity \u2212 Either a transaction completes or nothing happens at all.\nConsistency \u2212 A transaction must start in a consistent state and leave the system in a consistent state.\nIsolation \u2212 Intermediate results of a transaction are not visible outside the current transaction.\nDurability \u2212 Once a transaction was committed, the effects are persistent, even after a system failure.\n\nThe Python DB API 2.0 provides two methods to either commit or rollback a transaction.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5c5ad65d18264dec19582474f57d3dc7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You already know how to implement transactions. Here is again similar example \u2212\n\n# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d232d7b43fab239b122490697caec47b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.\nHere is a simple example to call commit method.\n\ndb.commit()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7145582fa35d2eec5b35314c55c5e24d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.\nHere is a simple example to call rollback() method.\n\ndb.rollback()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fb22431e51ee86ed2fd766b2adeaf494", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To disconnect Database connection, use close() method.\n\ndb.close()\n\nIf the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3e65539a02ce326b5d2a74e1ed4b1fb1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.\nPython also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.\nThis chapter gives you understanding on most famous concept in Networking - Socket Programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4f36105790565a8862cc4b4db5481280", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.\nSockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest.\nSockets have their own vocabulary \u2212\n\n\nSr.No.\nTerm & Description\n\n\n1\nDomain\nThe family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.\n\n\n2\ntype\nThe type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.\n\n\n3\nprotocol\nTypically zero, this may be used to identify a variant of a protocol within a domain and type.\n\n\n4\nhostname\nThe identifier of a network interface \u2212\n\nA string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation\nA string \"<broadcast>\", which specifies an INADDR_BROADCAST address.\nA zero-length string, which specifies INADDR_ANY, or\nAn Integer, interpreted as a binary address in host byte order.\n\n\n\n5\nport\nEach server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b74f82be26faeca24a7aae1adbf526bf", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax \u2212\n\ns = socket.socket (socket_family, socket_type, protocol=0)\n\nHere is the description of the parameters \u2212\n\nsocket_family \u2212 This is either AF_UNIX or AF_INET, as explained earlier.\nsocket_type \u2212 This is either SOCK_STREAM or SOCK_DGRAM.\nprotocol \u2212 This is usually left out, defaulting to 0.\n\nOnce you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "66746b68432750719d10df6f219450e2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.bind()\nThis method binds address (hostname, port number pair) to socket.\n\n\n2\ns.listen()\nThis method sets up and start TCP listener.\n\n\n3\ns.accept()\nThis passively accept TCP client connection, waiting until connection arrives (blocking).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e273ea06ac63e2ad0928cc14c2bfe06f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.connect()\nThis method actively initiates TCP server connection.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eec74c37aad48b3ee8619b5948a2dcdc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.recv()\nThis method receives TCP message\n\n\n2\ns.send()\nThis method transmits TCP message\n\n\n3\ns.recvfrom()\nThis method receives UDP message\n\n\n4\ns.sendto()\nThis method transmits UDP message\n\n\n5\ns.close()\nThis method closes socket\n\n\n6\nsocket.gethostname()\nReturns the hostname.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4a34ebeced97ba78deae20eaf222e531", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.\nNow call bind(hostname, port) function to specify a port for your service on the given host.\nNext, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.\n\n#!/usr/bin/python # This is server.py file\n\nimport socket # Import socket module\n\ns = socket.socket() # Create a socket object\nhost = socket.gethostname() # Get local machine name\nport = 12345 # Reserve a port for your service.\ns.bind((host, port)) # Bind to the port\n\ns.listen(5) # Now wait for client connection.\nwhile True:\n c, addr = s.accept() # Establish connection with client.\n print 'Got connection from', addr\n c.send('Thank you for connecting')\n c.close() # Close the connection", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e36b92901a2818bef9ae4d904d4f4d86", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python's socket module function.\nThe socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.\nThe following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits \u2212\n\n#!/usr/bin/python # This is client.py file\n\nimport socket # Import socket module\n\ns = socket.socket() # Create a socket object\nhost = socket.gethostname() # Get local machine name\nport = 12345 # Reserve a port for your service.\n\ns.connect((host, port))\nprint s.recv(1024)\ns.close() # Close the socket when done\n\nNow run this server.py in background and then run above client.py to see the result.\n\n# Following would start a server in background.\n$ python server.py & \n\n# Once server is started run client as follows:\n$ python client.py\n\nThis would produce following result \u2212\n\nGot connection from ('127.0.0.1', 48437)\nThank you for connecting", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "17637cdae20e51201427292e275ba52a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A list of some important modules in Python Network/Internet programming.\n\n\nProtocol\nCommon function\nPort No\nPython module\n\n\nHTTP\nWeb pages\n80\nhttplib, urllib, xmlrpclib\n\n\nNNTP\nUsenet news\n119\nnntplib\n\n\nFTP\nFile transfers\n20\nftplib, urllib\n\n\nSMTP\nSending email\n25\nsmtplib\n\n\nPOP3\nFetching email\n110\npoplib\n\n\nIMAP4\nFetching email\n143\nimaplib\n\n\nTelnet\nCommand lines\n23\ntelnetlib\n\n\nGopher\nDocument transfers\n70\ngopherlib, urllib\n\n\nPlease check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "154b236ddae2d0a0ec224e09ec11123c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.\nPython provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.\nHere is a simple syntax to create one SMTP object, which can later be used to send an e-mail \u2212\n\nimport smtplib\n\nsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )\n\nHere is the detail of the parameters \u2212\n\nhost \u2212 This is the host running your SMTP server. You can specify IP address of the host or a domain name like tutorialspoint.com. This is optional argument.\nport \u2212 If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25.\nlocal_hostname \u2212 If your SMTP server is running on your local machine, then you can specify just localhost as of this option.\n\nAn SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. It takes three parameters \u2212\n\nThe sender \u2212 A string with the address of the sender.\nThe receivers \u2212 A list of strings, one for each recipient.\nThe message \u2212 A message as a string formatted as specified in the various RFCs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2098a7f06392ced607435c096b2ec35f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple way to send one e-mail using Python script. Try it once \u2212\n\n#!/usr/bin/python\n\nimport smtplib\n\nsender = '[email protected]'\nreceivers = ['[email protected]']\n\nmessage = \"\"\"From: From Person <[email protected]>\nTo: To Person <[email protected]>\nSubject: SMTP e-mail test\n\nThis is a test e-mail message.\n\"\"\"\n\ntry:\n smtpObj = smtplib.SMTP('localhost')\n smtpObj.sendmail(sender, receivers, message) \n print \"Successfully sent email\"\nexcept SMTPException:\n print \"Error: unable to send email\"\n\nHere, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From, To, and Subject header, separated from the body of the e-mail with a blank line.\nTo send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).\nIf you are not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider must have provided you with outgoing mail server details that you can supply them, as follows \u2212\n\nsmtplib.SMTP('mail.your-domain.com', 25)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "13897d24b7d07f03b96af1cd4334bf17", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.\nWhile sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3819dff763c7b98c248983e0e0886123", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to send HTML content as an e-mail. Try it once \u2212\n\n#!/usr/bin/python\n\nimport smtplib\n\nmessage = \"\"\"From: From Person <[email protected]>\nTo: To Person <[email protected]>\nMIME-Version: 1.0\nContent-type: text/html\nSubject: SMTP HTML e-mail test\n\nThis is an e-mail message to be sent in HTML format\n\n<b>This is HTML message.</b>\n<h1>This is headline.</h1>\n\"\"\"\n\ntry:\n smtpObj = smtplib.SMTP('localhost')\n smtpObj.sendmail(sender, receivers, message) \n print \"Successfully sent email\"\nexcept SMTPException:\n print \"Error: unable to send email\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "386cc07181c62c2f31376a6457f5f97d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.\nA boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.\nAttached files should be encoded with the pack(\"m\") function to have base64 encoding before transmission.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "867a54166bd16f61e238ddd9a009fd38", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Running several threads is similar to running several different programs concurrently, but with the following benefits \u2212\n\nMultiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.\nThreads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.\n\nA thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running.\n\nIt can be pre-empted (interrupted)\nIt can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "01f1fd252aa2ee6e1501867f34397438", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To spawn another thread, you need to call following method available in thread module \u2212\n\nthread.start_new_thread ( function, args[, kwargs] )\n\nThis method call enables a fast and efficient way to create new threads in both Linux and Windows.\nThe method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.\nHere, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3e0acbe9a6d79976ef66d1d59af1406b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport thread\nimport time\n\n# Define a function for the thread\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print \"%s: %s\" % ( threadName, time.ctime(time.time()) )\n\n# Create two threads as follows\ntry:\n thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print \"Error: unable to start thread\"\n\nwhile 1:\n pass\n\nWhen the above code is executed, it produces the following result \u2212\n\nThread-1: Thu Jan 22 15:42:17 2009\nThread-1: Thu Jan 22 15:42:19 2009\nThread-2: Thu Jan 22 15:42:19 2009\nThread-1: Thu Jan 22 15:42:21 2009\nThread-2: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:25 2009\nThread-2: Thu Jan 22 15:42:27 2009\nThread-2: Thu Jan 22 15:42:31 2009\nThread-2: Thu Jan 22 15:42:35 2009\n\nAlthough it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "068c83841bf7be1df60b5a539056ca37", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.\nThe threading module exposes all the methods of the thread module and provides some additional methods \u2212\n\nthreading.activeCount() \u2212 Returns the number of thread objects that are active.\nthreading.currentThread() \u2212 Returns the number of thread objects in the caller's thread control.\nthreading.enumerate() \u2212 Returns a list of all thread objects that are currently active.\n\nIn addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows \u2212\n\nrun() \u2212 The run() method is the entry point for a thread.\nstart() \u2212 The start() method starts a thread by calling the run method.\n join([time]) \u2212 The join() waits for threads to terminate.\n isAlive() \u2212 The isAlive() method checks whether a thread is still executing.\n getName() \u2212 The getName() method returns the name of a thread.\n setName() \u2212 The setName() method sets the name of a thread.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "13dd0ef27335c5c5a91a37251c4e8b7d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To implement a new thread using the threading module, you have to do the following \u2212\n\nDefine a new subclass of the Thread class.\nOverride the __init__(self [,args]) method to add additional arguments.\nThen, override the run(self [,args]) method to implement what the thread should do when started.\n\nOnce you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "975e1e275e34fec89dcae2bbddbb539b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n print_time(self.name, 5, self.counter)\n print \"Exiting \" + self.name\n\ndef print_time(threadName, counter, delay):\n while counter:\n if exitFlag:\n threadName.exit()\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\nprint \"Exiting Main Thread\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nStarting Thread-1\nStarting Thread-2\nExiting Main Thread\nThread-1: Thu Mar 21 09:10:03 2013\nThread-1: Thu Mar 21 09:10:04 2013\nThread-2: Thu Mar 21 09:10:04 2013\nThread-1: Thu Mar 21 09:10:05 2013\nThread-1: Thu Mar 21 09:10:06 2013\nThread-2: Thu Mar 21 09:10:06 2013\nThread-1: Thu Mar 21 09:10:07 2013\nExiting Thread-1\nThread-2: Thu Mar 21 09:10:08 2013\nThread-2: Thu Mar 21 09:10:10 2013\nThread-2: Thu Mar 21 09:10:12 2013\nExiting Thread-2", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "effd4409c57e4fc5612f0011231fd0b1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.\nThe acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.\nIf blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.\nThe release() method of the new lock object is used to release the lock when it is no longer required.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ee44d91c89dd65a6c39a0c85cab108e1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n # Get lock to synchronize threads\n threadLock.acquire()\n print_time(self.name, self.counter, 3)\n # Free lock to release next thread\n threadLock.release()\n\ndef print_time(threadName, delay, counter):\n while counter:\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\nthreadLock = threading.Lock()\nthreads = []\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\n# Add threads to thread list\nthreads.append(thread1)\nthreads.append(thread2)\n\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nStarting Thread-1\nStarting Thread-2\nThread-1: Thu Mar 21 09:11:28 2013\nThread-1: Thu Mar 21 09:11:29 2013\nThread-1: Thu Mar 21 09:11:30 2013\nThread-2: Thu Mar 21 09:11:32 2013\nThread-2: Thu Mar 21 09:11:34 2013\nThread-2: Thu Mar 21 09:11:36 2013\nExiting Main Thread", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3f75ae99a0dabb75e7dac9c6edbb3111", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue \u2212\n\nget() \u2212 The get() removes and returns an item from the queue.\nput() \u2212 The put adds item to a queue.\nqsize() \u2212 The qsize() returns the number of items that are currently in the queue.\nempty() \u2212 The empty( ) returns True if queue is empty; otherwise, False.\nfull() \u2212 the full() returns True if queue is full; otherwise, False.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e62ee675512f7f8f8fd14efaa3b96cee", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "390975e142b2740cd8f1b8141fa43210", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.\nXML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1ac4fa8da25ccc39eb8a458005bc436e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python standard library provides a minimal but useful set of interfaces to work with XML.\nThe two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.\n\nSimple API for XML (SAX) \u2212 Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk and the entire file is never stored in memory.\nDocument Object Model (DOM) API \u2212 This is a World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.\n\n\nSAX obviously cannot process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files.\nSAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other, there is no reason why you cannot use them both for large projects.\nFor all our XML code examples, let's use a simple XML file movies.xml as an input \u2212\n\n<collection shelf=\"New Arrivals\">\n<movie title=\"Enemy Behind\">\n <type>War, Thriller</type>\n <format>DVD</format>\n <year>2003</year>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Talk about a US-Japan war</description>\n</movie>\n<movie title=\"Transformers\">\n <type>Anime, Science Fiction</type>\n <format>DVD</format>\n <year>1989</year>\n <rating>R</rating>\n <stars>8</stars>\n <description>A schientific fiction</description>\n</movie>\n <movie title=\"Trigun\">\n <type>Anime, Action</type>\n <format>DVD</format>\n <episodes>4</episodes>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Vash the Stampede!</description>\n</movie>\n<movie title=\"Ishtar\">\n <type>Comedy</type>\n <format>VHS</format>\n <rating>PG</rating>\n <stars>2</stars>\n <description>Viewable boredom</description>\n</movie>\n</collection>", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bac5fcfd0c59b94942d227d422d6e453", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.ContentHandler.\nYour ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file.\nThe methods startDocument and endDocument are called at the start and the end of the XML file. The method characters(text) is passed character data of the XML file via the parameter text.\nThe ContentHandler is called at the start and end of each element. If the parser is not in namespace mode, the methods startElement(tag, attributes) and endElement(tag) are called; otherwise, the corresponding methods startElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an Attributes object.\nHere are other important methods to understand before proceeding \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bc5bd2481e543a55e65e9bb83d1e5d77", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following method creates a new parser object and returns it. The parser object created will be of the first parser type the system finds.\n\nxml.sax.make_parser( [parser_list] )\n\nHere is the detail of the parameters \u2212\n\nparser_list \u2212 The optional argument consisting of a list of parsers to use which must all implement the make_parser method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f33d1cb620c95038299c8d60443bfb89", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following method creates a SAX parser and uses it to parse a document.\n\nxml.sax.parse( xmlfile, contenthandler[, errorhandler])\n\nHere is the detail of the parameters \u2212\n\nxmlfile \u2212 This is the name of the XML file to read from.\ncontenthandler \u2212 This must be a ContentHandler object.\nerrorhandler \u2212 If specified, errorhandler must be a SAX ErrorHandler object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5fb396648c05e015147afa8d5768891c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There is one more method to create a SAX parser and to parse the specified XML string.\n\nxml.sax.parseString(xmlstring, contenthandler[, errorhandler])\n\nHere is the detail of the parameters \u2212\n\nxmlstring \u2212 This is the name of the XML string to read from.\ncontenthandler \u2212 This must be a ContentHandler object.\nerrorhandler \u2212 If specified, errorhandler must be a SAX ErrorHandler object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0acec9eccdc8275b743af5f1c40fae16", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport xml.sax\n\nclass MovieHandler( xml.sax.ContentHandler ):\n def __init__(self):\n self.CurrentData = \"\"\n self.type = \"\"\n self.format = \"\"\n self.year = \"\"\n self.rating = \"\"\n self.stars = \"\"\n self.description = \"\"\n\n # Call when an element starts\n def startElement(self, tag, attributes):\n self.CurrentData = tag\n if tag == \"movie\":\n print \"*****Movie*****\"\n title = attributes[\"title\"]\n print \"Title:\", title\n\n # Call when an elements ends\n def endElement(self, tag):\n if self.CurrentData == \"type\":\n print \"Type:\", self.type\n elif self.CurrentData == \"format\":\n print \"Format:\", self.format\n elif self.CurrentData == \"year\":\n print \"Year:\", self.year\n elif self.CurrentData == \"rating\":\n print \"Rating:\", self.rating\n elif self.CurrentData == \"stars\":\n print \"Stars:\", self.stars\n elif self.CurrentData == \"description\":\n print \"Description:\", self.description\n self.CurrentData = \"\"\n\n # Call when a character is read\n def characters(self, content):\n if self.CurrentData == \"type\":\n self.type = content\n elif self.CurrentData == \"format\":\n self.format = content\n elif self.CurrentData == \"year\":\n self.year = content\n elif self.CurrentData == \"rating\":\n self.rating = content\n elif self.CurrentData == \"stars\":\n self.stars = content\n elif self.CurrentData == \"description\":\n self.description = content\n \nif ( __name__ == \"__main__\"):\n \n # create an XMLReader\n parser = xml.sax.make_parser()\n # turn off namepsaces\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n\n # override the default ContextHandler\n Handler = MovieHandler()\n parser.setContentHandler( Handler )\n \n parser.parse(\"movies.xml\")\n\nThis would produce following result \u2212\n\n*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nYear: 2003\nRating: PG\nStars: 10\nDescription: Talk ", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "65d2b6eafc66228d54f9444dd136f853", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nYear: 1989\nRating: R\nStars: 8\nDescription: A schientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nFormat: DVD\nRating: PG\nStars: 10\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nStars: 2\nDescription: Viewable boredom\n\nFor a complete detail on SAX API documentation, please refer to standard Python SAX APIs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c086bb9fa88a600e2028c744ee15ddfd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.\n\nTkinter \u2212 Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter.\nwxPython \u2212 This is an open-source Python interface for wxWindows http://wxpython.org.\nJPython \u2212 JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org.\n\nThere are many other interfaces available, which you can find them on the net.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c04018d651212e5ca2b7a5e41ca5292c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.\nCreating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps \u2212\n\nImport the Tkinter module.\nCreate the GUI application main window.\nAdd one or more of the above-mentioned widgets to the GUI application.\nEnter the main event loop to take action against each event triggered by the user.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eded8ac25063578396fb167ccb128ca9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport Tkinter\ntop = Tkinter.Tk()\n# Code to add widgets will go here...\ntop.mainloop()\n\nThis would create a following window \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b6b3783261922ed51a776c48ea26a219", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.\nThere are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table \u2212\n\n\nSr.No.\nOperator & Description\n\n\n1\nButton\nThe Button widget is used to display buttons in your application.\n\n\n2\nCanvas\nThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.\n\n\n3\nCheckbutton\nThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.\n\n\n4\nEntry\nThe Entry widget is used to display a single-line text field for accepting values from a user.\n\n\n5\nFrame\nThe Frame widget is used as a container widget to organize other widgets.\n\n\n6\nLabel\nThe Label widget is used to provide a single-line caption for other widgets. It can also contain images.\n\n\n7\nListbox\nThe Listbox widget is used to provide a list of options to a user.\n\n\n8\nMenubutton\nThe Menubutton widget is used to display menus in your application.\n\n\n9\nMenu\nThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.\n\n\n10\nMessage\nThe Message widget is used to display multiline text fields for accepting values from a user.\n\n\n11\nRadiobutton\nThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.\n\n\n12\nScale\nThe Scale widget is used to provide a slider widget.\n\n\n13\nScrollbar\nThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.\n\n\n14\nText\nThe Text widget is used to display text in multiple lines.\n\n\n15\nToplevel\nThe Toplevel widget is used to provide a separate window container.\n\n\n16\nSpinbox\nThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.\n\n\n17\nPanedWindow\nA PanedWindow is a container widget that may contain any number of panes, ar", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7a5ed0c3be49804906c266399266e5f6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "ranged horizontally or vertically.\n\n\n18\nLabelFrame\nA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.\n\n\n19\ntkMessageBox\nThis module is used to display message boxes in your applications.\n\n\nLet us study these widgets in detail \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "518cb2d55b6d48789b13fe3727fcb159", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified.\n\nDimensions\nColors\nFonts\nAnchors\nRelief styles\nBitmaps\nCursors\n\nLet us study them briefly \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1dbe4073dc04655537ed9aeb417d9e92", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an \"extension.\"\nA Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for shared object). On Windows machines, you typically see .dll (for dynamically linked library).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2cc6cb729122770651ded2fba1c70441", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To start writing your extension, you are going to need the Python header files.\n\nOn Unix machines, this usually requires installing a developer-specific package such as python2.5-dev.\nWindows users get these headers as part of the package when they use the binary Python installer.\n\nAdditionally, it is assumed that you have good knowledge of C or C++ to write any Python Extension using C programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8890d217bd799e578c8cea1091fc26ec", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "For your first look at a Python extension module, you need to group your code into four part \u2212\n\nThe header file Python.h.\nThe C functions you want to expose as the interface from your module.\nA table mapping the names of your functions as Python developers see them to C functions inside the extension module.\nAn initialization function.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a4774b9d4005c0d2dd5f0aadbc88d11", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You need include Python.h header file in your C source file, which gives you access to the internal Python API used to hook your module into the interpreter.\nMake sure to include Python.h before any other headers you might need. You need to follow the includes with the functions you want to call from Python.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4a7ec1a20ffb6b1f5469c42cd1c771cb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The signatures of the C implementation of your functions always takes one of the following three forms \u2212\n\nstatic PyObject *MyFunction( PyObject *self, PyObject *args );\n\nstatic PyObject *MyFunctionWithKeywords(PyObject *self,\n PyObject *args,\n PyObject *kw);\n\nstatic PyObject *MyFunctionWithNoArgs( PyObject *self );\n\nEach one of the preceding declarations returns a Python object. There is no such thing as a void function in Python as there is in C. If you do not want your functions to return a value, return the C equivalent of Python's None value. The Python headers define a macro, Py_RETURN_NONE, that does this for us.\nThe names of your C functions can be whatever you like as they are never seen outside of the extension module. They are defined as static function.\nYour C functions usually are named by combining the Python module and function names together, as shown here \u2212\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Do your stuff here. */\n Py_RETURN_NONE;\n}\n\nThis is a Python function called func inside of the module module. You will be putting pointers to your C functions into the method table for the module that usually comes next in your source code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5ec18859df21831167ee3d8fc902f758", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This method table is a simple array of PyMethodDef structures. That structure looks something like this \u2212\n\nstruct PyMethodDef {\n char *ml_name;\n PyCFunction ml_meth;\n int ml_flags;\n char *ml_doc;\n};\n\nHere is the description of the members of this structure \u2212\n\nml_name \u2212 This is the name of the function as the Python interpreter presents when it is used in Python programs.\nml_meth \u2212 This must be the address to a function that has any one of the signatures described in previous seection.\nml_flags \u2212 This tells the interpreter which of the three signatures ml_meth is using.\n\nThis flag usually has a value of METH_VARARGS.\nThis flag can be bitwise OR'ed with METH_KEYWORDS if you want to allow keyword arguments into your function.\nThis can also have a value of METH_NOARGS that indicates you do not want to accept any arguments.\n\n\nml_doc \u2212 This is the docstring for the function, which could be NULL if you do not feel like writing one.\n\nThis table needs to be terminated with a sentinel that consists of NULL and 0 values for the appropriate members.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "99422a32c3a95de0e40da95e678ae3c1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "For the above-defined function, we have following method mapping table \u2212\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { NULL, NULL, 0, NULL }\n};", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2255b08eb948951fc21c16c139cae068", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The last part of your extension module is the initialization function. This function is called by the Python interpreter when the module is loaded. It is required that the function be named initModule, where Module is the name of the module.\nThe initialization function needs to be exported from the library you will be building. The Python headers define PyMODINIT_FUNC to include the appropriate incantations for that to happen for the particular environment in which we're compiling. All you have to do is use it when defining the function.\nYour C initialization function generally has the following overall structure \u2212\n\nPyMODINIT_FUNC initModule() {\n Py_InitModule3(func, module_methods, \"docstring...\");\n}\n\nHere is the description of Py_InitModule3 function \u2212\n\nfunc \u2212 This is the function to be exported.\nmodule_methods \u2212 This is the mapping table name defined above.\ndocstring \u2212 This is the comment you want to give in your extension.\n\nPutting this all together looks like the following \u2212\n\n#include <Python.h>\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Do your stuff here. */\n Py_RETURN_NONE;\n}\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { NULL, NULL, 0, NULL }\n};\n\nPyMODINIT_FUNC initModule() {\n Py_InitModule3(func, module_methods, \"docstring...\");\n}", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "89e4d6501d710fe667d48be49e81246c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A simple example that makes use of all the above concepts \u2212\n\n#include <Python.h>\n\nstatic PyObject* helloworld(PyObject* self) {\n return Py_BuildValue(\"s\", \"Hello, Python extensions!!\");\n}\n\nstatic char helloworld_docs[] =\n \"helloworld( ): Any message you want to put here!!\\n\";\n\nstatic PyMethodDef helloworld_funcs[] = {\n {\"helloworld\", (PyCFunction)helloworld, \n METH_NOARGS, helloworld_docs},\n {NULL}\n};\n\nvoid inithelloworld(void) {\n Py_InitModule3(\"helloworld\", helloworld_funcs,\n \"Extension module example!\");\n}\n\nHere the Py_BuildValue function is used to build a Python value. Save above code in hello.c file. We would see how to compile and install this module to be called from Python script.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5f507d0a9ee5f2c79b80f602756c7208", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The distutils package makes it very easy to distribute Python modules, both pure Python and extension modules, in a standard way. Modules are distributed in source form and built and installed via a setup script usually called setup.py as follows.\nFor the above module, you need to prepare following setup.py script \u2212\n\nfrom distutils.core import setup, Extension\nsetup(name='helloworld', version='1.0', \\\n ext_modules=[Extension('helloworld', ['hello.c'])])\n\nNow, use the following command, which would perform all needed compilation and linking steps, with the right compiler and linker commands and flags, and copies the resulting dynamic library into an appropriate directory \u2212\n\n$ python setup.py install\n\nOn Unix-based systems, you'll most likely need to run this command as root in order to have permissions to write to the site-packages directory. This usually is not a problem on Windows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dd89727357661f7ae5992d67c13cc189", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once you installed your extension, you would be able to import and call that extension in your Python script as follows \u2212\n\n#!/usr/bin/python\nimport helloworld\n\nprint helloworld.helloworld()\n\nThis would produce the following result \u2212\n\nHello, Python extensions!!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c52df000643bd9325f17e8a085df39a1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "As you will most likely want to define functions that accept arguments, you can use one of the other signatures for your C functions. For example, following function, that accepts some number of parameters, would be defined like this \u2212\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Parse args and do something interesting here. */\n Py_RETURN_NONE;\n}\n\nThe method table containing an entry for the new function would look like this \u2212\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { \"func\", module_func, METH_VARARGS, NULL },\n { NULL, NULL, 0, NULL }\n};\n\nYou can use API PyArg_ParseTuple function to extract the arguments from the one PyObject pointer passed into your C function.\nThe first argument to PyArg_ParseTuple is the args argument. This is the object you will be parsing. The second argument is a format string describing the arguments as you expect them to appear. Each argument is represented by one or more characters in the format string as follows.\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n int i;\n double d;\n char *s;\n\n if (!PyArg_ParseTuple(args, \"ids\", &i, &d, &s)) {\n return NULL;\n }\n \n /* Do something interesting here. */\n Py_RETURN_NONE;\n}\n\nCompiling the new version of your module and importing it enables you to invoke the new function with any number of arguments of any type \u2212\n\nmodule.func(1, s=\"three\", d=2.0)\nmodule.func(i=1, d=2.0, s=\"three\")\nmodule.func(s=\"three\", d=2.0, i=1)\n\nYou can probably come up with even more variations.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "94cc8e5dae485372e3333fa6818d7b1d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is the standard signature for PyArg_ParseTuple function \u2212\n\nint PyArg_ParseTuple(PyObject* tuple,char* format,...)\n\nThis function returns 0 for errors, and a value not equal to 0 for success. tuple is the PyObject* that was the C function's second argument. Here format is a C string that describes mandatory and optional arguments.\nHere is a list of format codes for PyArg_ParseTuple function \u2212\n\n\nCode\nC type\nMeaning\n\n\nc\nchar\n A Python string of length 1 becomes a C char.\n\nd\ndouble\nA Python float becomes a C double.\n\nf\nfloat\nA Python float becomes a C float.\n\ni\nint\nA Python int becomes a C int.\n\nl\nlong\nA Python int becomes a C long.\n\nL\nlong long\nA Python int becomes a C long long\n\nO\nPyObject*\nGets non-NULL borrowed reference to Python argument.\n\ns\nchar*\nPython string without embedded nulls to C char*.\n\ns#\nchar*+int\nAny Python string to C address and length.\n\nt#\nchar*+int\nRead-only single-segment buffer to C address and length.\n\nu\nPy_UNICODE*\nPython Unicode without embedded nulls to C.\n\nu#\nPy_UNICODE*+int\nAny Python Unicode C address and length.\n\nw#\nchar*+int\nRead/write single-segment buffer to C address and length.\n\nz\nchar*\nLike s, also accepts None (sets C char* to NULL).\n\nz#\nchar*+int\nLike s#, also accepts None (sets C char* to NULL).\n\n(...)\nas per ...\nA Python sequence is treated as one argument per item.\n\n|\n\u00a0\nThe following arguments are optional.\n\n:\n\u00a0\nFormat end, followed by function name for error messages.\n\n;\n\u00a0\nFormat end, followed by entire error message text.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e1c3904c71fb7abc625520db18afa2f2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Py_BuildValue takes in a format string much like PyArg_ParseTuple does. Instead of passing in the addresses of the values you are building, you pass in the actual values. Here's an example showing how to implement an add function \u2212\n\nstatic PyObject *foo_add(PyObject *self, PyObject *args) {\n int a;\n int b;\n\n if (!PyArg_ParseTuple(args, \"ii\", &a, &b)) {\n return NULL;\n }\n return Py_BuildValue(\"i\", a + b);\n}\n\nThis is what it would look like if implemented in Python \u2212\n\ndef add(a, b):\n return (a + b)\n\nYou can return two values from your function as follows, this would be cauptured using a list in Python.\n\nstatic PyObject *foo_add_subtract(PyObject *self, PyObject *args) {\n int a;\n int b;\n\n if (!PyArg_ParseTuple(args, \"ii\", &a, &b)) {\n return NULL;\n }\n return Py_BuildValue(\"ii\", a + b, a - b);\n}\n\nThis is what it would look like if implemented in Python \u2212\n\ndef add_subtract(a, b):\n return (a + b, a - b)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0412f1954c5ca82da286c8384b02d1ae", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.\n\nPython is Interpreted \u2212 Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.\nPython is Interactive \u2212 You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.\nPython is Object-Oriented \u2212 Python supports Object-Oriented style or technique of programming that encapsulates code within objects.\nPython is a Beginner's Language \u2212 Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "077744d3b2ea6b664b17ebeec35e0294", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.\nPython is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.\nPython is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).\nPython is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "45eec423e30f19da975bc4ebc07a21c8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's features include \u2212\n\nEasy-to-learn \u2212 Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.\nEasy-to-read \u2212 Python code is more clearly defined and visible to the eyes.\nEasy-to-maintain \u2212 Python's source code is fairly easy-to-maintain.\nA broad standard library \u2212 Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.\nInteractive Mode \u2212 Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.\nPortable \u2212 Python can run on a wide variety of hardware platforms and has the same interface on all platforms.\nExtendable \u2212 You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.\nDatabases \u2212 Python provides interfaces to all major commercial databases.\nGUI Programming \u2212 Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.\nScalable \u2212 Python provides a better structure and support for large programs than shell scripting.\n\nApart from the above-mentioned features, Python has a big list of good features, few are listed below \u2212\n\nIt supports functional and structured programming methods as well as OOP.\nIt can be used as a scripting language or can be compiled to byte-code for building large applications.\nIt provides very high-level dynamic data types and supports dynamic type checking.\nIt supports automatic garbage collection.\nIt can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "43a05fac26768bc2047698e83a2e0a9c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "11ce389eed7b9f0d690d09d777335caf", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Open a terminal window and type \"python\" to find out if it is already installed and which version is installed.\n\nUnix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)\nWin 9x/NT/2000\nMacintosh (Intel, PPC, 68K)\nOS/2\nDOS (multiple versions)\nPalmOS\nNokia mobile phones\nWindows CE\nAcorn/RISC OS\nBeOS\nAmiga\nVMS/OpenVMS\nQNX\nVxWorks\nPsion\nPython has also been ported to the Java and .NET virtual machines", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "05e458cec2cef1e0f35f8bf85e81995d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/\nYou can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4cbf3092d3ff744abd603242a52f4542", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.\nIf the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.\nHere is a quick overview of installing Python on various platforms \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6daf2fa9031ee3d2de38ea58be76a605", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are the simple steps to install Python on Unix/Linux machine.\n\nOpen a Web browser and go to https://www.python.org/downloads/.\nFollow the link to download zipped source code available for Unix/Linux.\nDownload and extract files.\nEditing the Modules/Setup file if you want to customize some options.\nrun ./configure script\nmake\nmake install\n\nThis installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fc3a97b7a9e3a7b799c2492ff7d2ddde", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are the steps to install Python on Windows machine.\n\nOpen a Web browser and go to https://www.python.org/downloads/.\nFollow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.\nTo use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.\nRun the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "80ce92ad886896d249a7cc13c93c30e6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available.\nJack Jansen maintains it and you can have full access to the entire documentation at his website \u2212 http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d94157bb5aebb0f85af8b74295dd76f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.\nThe path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.\nThe path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).\nIn Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8a0d31c036733dcf188f7e9474befe8e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To add the Python directory to the path for a particular session in Unix \u2212\n\nIn the csh shell \u2212 type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter.\nIn the bash shell (Linux) \u2212 type export PATH=\"$PATH:/usr/local/bin/python\" and press Enter.\nIn the sh or ksh shell \u2212 type PATH=\"$PATH:/usr/local/bin/python\" and press Enter.\nNote \u2212 /usr/local/bin/python is the path of the Python directory", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4de1e8a4f521ff0bad2a910d903d7fde", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To add the Python directory to the path for a particular session in Windows \u2212\nAt the command prompt \u2212 type path %path%;C:\\Python and press Enter.\nNote \u2212 C:\\Python is the path of the Python directory", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bf26fa78cce6a41a2803924e34884d47", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are important environment variables, which can be recognized by Python \u2212\n\n\nSr.No.\nVariable & Description\n\n\n1\nPYTHONPATH\nIt has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.\n\n\n2\nPYTHONSTARTUP\nIt contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it\ncontains commands that load utilities or modify PYTHONPATH.\n\n\n3\nPYTHONCASEOK\nIt is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.\n\n\n4\nPYTHONHOME\nIt is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eae96ceb6f1e4e36c1903b4f6dee960f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are three different ways to start Python \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "937939b5c0bdc8f6929a2513e0a8b6c7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.\nEnter python the command line.\nStart coding right away in the interactive interpreter.\n\n$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n\nHere is the list of all the available command line options \u2212\n\n\n\nSr.No.\nOption & Description\n\n\n1\n-d\nIt provides debug output.\n\n\n2\n-O\nIt generates optimized bytecode (resulting in .pyo files).\n\n\n3\n-S\nDo not run import site to look for Python paths on startup.\n\n\n4\n-v\nverbose output (detailed trace on import statements).\n\n\n5\n-X\ndisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.\n\n\n6\n-c cmd\nrun Python script sent in as cmd string\n\n\n7\nfile\nrun Python script from given file", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4c26d8c94a4d18c378c5306af530c2ee", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following \u2212\n\n$python script.py # Unix/Linux\n\nor\n\npython% script.py # Unix/Linux\n\nor \n\nC: >python script.py # Windows/DOS\n\nNote \u2212 Be sure the file permission mode allows execution.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "de17235f6fb647bbcc5429e853dfa21d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.\n\nUnix \u2212 IDLE is the very first Unix IDE for Python.\nWindows \u2212 PythonWin is the first Windows interface for Python and is an IDE with a GUI.\nMacintosh \u2212 The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.\n\nIf you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine.\nNote \u2212 All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux.\nWe already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eb83a471c640e323ef28cf15486e050d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0c4067234d96109b8a6d791ad9e629a4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us execute programs in different modes of programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c2ac7d3d5eaa9358e4d4746655b649ad", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Invoking the interpreter without passing a script file as a parameter brings up the following prompt \u2212\n\n$ python\nPython 2.4.3 (#1, Nov 11 2010, 13:34:43)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n\nType the following text at the Python prompt and press the Enter \u2212\n\n>>> print \"Hello, Python!\"\n\nIf you are running new version of Python, then you would need to use print statement with parenthesis as in print (\"Hello, Python!\");. However in Python version 2.4.3, this produces the following result \u2212\n\nHello, Python!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "93d84a756ed9cf4058d28c76702261e2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.\nLet us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file \u2212\n\nprint \"Hello, Python!\"\n\nWe assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows \u2212\n\n$ python test.py\n\nThis produces the following result \u2212\n\nHello, Python!\n\nLet us try another way to execute a Python script. Here is the modified test.py file \u2212\n\n#!/usr/bin/python\n\nprint \"Hello, Python!\"\n\nWe assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows \u2212\n\n$ chmod +x test.py # This is to make file executable\n$./test.py\n\nThis produces the following result \u2212\n\nHello, Python!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "275def292d55465f2e15ab638e705468", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).\nPython does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.\nHere are naming conventions for Python identifiers \u2212\n\nClass names start with an uppercase letter. All other identifiers start with a lowercase letter.\nStarting an identifier with a single leading underscore indicates that the identifier is private.\nStarting an identifier with two leading underscores indicates a strongly private identifier.\nIf the identifier also ends with two trailing underscores, the identifier is a language-defined special name.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eac1ace6ae56af99ea2bc144858e1835", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.\n\n\nand\nexec\nnot\n\n\nassert\nfinally\nor\n\n\nbreak\nfor\npass\n\n\nclass\nfrom\nprint\n\n\ncontinue\nglobal\nraise\n\n\ndef\nif\nreturn\n\n\ndel\nimport\ntry\n\n\nelif\nin\nwhile\n\n\nelse\nis\nwith \n\n\nexcept\nlambda\nyield", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "65c91ff8634568d213bc73247fa89dea", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.\nThe number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example \u2212\n\nif True:\n print \"True\"\nelse:\n print \"False\"\n\nHowever, the following block generates an error \u2212\n\nif True:\nprint \"Answer\"\nprint \"True\"\nelse:\nprint \"Answer\"\nprint \"False\"\n\nThus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks \u2212\nNote \u2212 Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.\n\n#!/usr/bin/python\n\nimport sys\n\ntry:\n # open file stream\n file = open(file_name, \"w\")\nexcept IOError:\n print \"There was an error writing to\", file_name\n sys.exit()\nprint \"Enter '\", file_finish,\nprint \"' When finished\"\nwhile file_text != file_finish:\n file_text = raw_input(\"Enter text: \")\n if file_text == file_finish:\n # close the file\n file.close\n break\n file.write(file_text)\n file.write(\"\\n\")\nfile.close()\nfile_name = raw_input(\"Enter filename: \")\nif len(file_name) == 0:\n print \"Next time please enter something\"\n sys.exit()\ntry:\n file = open(file_name, \"r\")\nexcept IOError:\n print \"There was an error reading file\"\n sys.exit()\nfile_text = file.read()\nfile.close()\nprint file_text", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a206a577569c5d865e2d6e329f2136f6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\\) to denote that the line should continue. For example \u2212\n\ntotal = item_one + \\\n item_two + \\\n item_three\n\nStatements contained within the [], {}, or () brackets do not need to use the line continuation character. For example \u2212\n\ndays = ['Monday', 'Tuesday', 'Wednesday',\n 'Thursday', 'Friday']", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5cf8d83c9d617ff26ebbbc16f723ddc4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python accepts single ('), double (\") and triple (''' or \"\"\") quotes to denote string literals, as long as the same type of quote starts and ends the string.\nThe triple quotes are used to span the string across multiple lines. For example, all the following are legal \u2212\n\nword = 'word'\nsentence = \"This is a sentence.\"\nparagraph = \"\"\"This is a paragraph. It is\nmade up of multiple lines and sentences.\"\"\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9c32993345a8f16734e27deb26327772", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.\n\n#!/usr/bin/python\n\n# First comment\nprint \"Hello, Python!\" # second comment\n\nThis produces the following result \u2212\n\nHello, Python!\n\nYou can type a comment on the same line after a statement or expression \u2212\n\nname = \"Madisetti\" # This is again comment\n\nYou can comment multiple lines as follows \u2212\n\n# This is a comment.\n# This is a comment, too.\n# This is a comment, too.\n# I said that already.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6b8b27741b03179f84e3fc5ebe4814c5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.\nIn an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8d3eb1776332bee05149ad32b6e3ba87", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following line of the program displays the prompt, the statement saying \u201cPress the enter key to exit\u201d, and waits for the user to take action \u2212\n\n#!/usr/bin/python\n\nraw_input(\"\\n\\nPress the enter key to exit.\")\n\nHere, \"\\n\\n\" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "720ee8c17d3002bda25fd51fddc789b2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon \u2212\n\nimport sys; x = 'foo'; sys.stdout.write(x + '\\n')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c69d189e526453f3216a1bb7da3bc8e3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.\nHeader lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example \u2212\n\nif expression : \n suite\nelif expression : \n suite \nelse : \n suite", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d00a82caafbe78d7c0c7305f330c3643", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h \u2212\n\n$ python -h\nusage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...\nOptions and arguments (and corresponding environment variables):\n-c cmd : program passed in as string (terminates option list)\n-d : debug output from parser (also PYTHONDEBUG=x)\n-E : ignore environment variables (such as PYTHONPATH)\n-h : print this help message and exit\n\n[ etc. ]\n\nYou can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5405e2916c21329e3645c6ac7b159027", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.\nBased on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ca82c09fd62594f4e7eb55a4e0738821", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.\nThe operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example \u2212\n\n#!/usr/bin/python\n\ncounter = 100 # An integer assignment\nmiles = 1000.0 # A floating point\nname = \"John\" # A string\n\nprint counter\nprint miles\nprint name\n\nHere, 100, 1000.0 and \"John\" are the values assigned to counter, miles, and name variables, respectively. This produces the following result \u2212\n\n100\n1000.0\nJohn", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c5a78de3d51b533e385faae81f9a8a34", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python allows you to assign a single value to several variables simultaneously. For example \u2212\n\na = b = c = 1\n\nHere, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example \u2212\n\na,b,c = 1,2,\"john\"\n\nHere, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value \"john\" is assigned to the variable c.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4ea958a1cf5255de4bd8f223646dead1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.\nPython has five standard data types \u2212\n\nNumbers\nString\nList\nTuple\nDictionary", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a9af1d20e07a1ee65fd49bcb7c617e36", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Number data types store numeric values. Number objects are created when you assign a value to them. For example \u2212\n\nvar1 = 1\nvar2 = 10\n\nYou can also delete the reference to a number object by using the del statement. The syntax of the del statement is \u2212\n\ndel var1[,var2[,var3[....,varN]]]]\n\nYou can delete a single object or multiple objects by using the del statement. For example \u2212\n\ndel var\ndel var_a, var_b\n\nPython supports four different numerical types \u2212\n\nint (signed integers)\nlong (long integers, they can also be represented in octal and hexadecimal)\nfloat (floating point real values)\ncomplex (complex numbers)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "282de79bdecf35609431f6845799a44e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are some examples of numbers \u2212\n\n\nint\nlong\nfloat\ncomplex\n\n\n10\n51924361L\n0.0\n3.14j\n\n\n100\n-0x19323L\n15.20\n45.j\n\n\n-786\n0122L\n-21.9\n9.322e-36j\n\n\n080\n0xDEFABCECBDAECBFBAEl\n32.3+e18\n.876j\n\n\n-0490\n535633629843L\n-90.\n-.6545+0J\n\n\n-0x260\n-052318172735L\n-32.54e100\n3e+26J\n\n\n0x69\n-4721885298529L\n70.2-E12\n4.53e-7j\n\n\n\nPython allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.\nA complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f9c339fd89c2e717b443bb0c3ac9fc15", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.\nThe plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example \u2212\n\n#!/usr/bin/python\n\nstr = 'Hello World!'\n\nprint str # Prints complete string\nprint str[0] # Prints first character of the string\nprint str[2:5] # Prints characters starting from 3rd to 5th\nprint str[2:] # Prints string starting from 3rd character\nprint str * 2 # Prints string two times\nprint str + \"TEST\" # Prints concatenated string\n\nThis will produce the following result \u2212\n\nHello World!\nH\nllo\nllo World!\nHello World!Hello World!\nHello World!TEST", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b143b4cd4e845d6b20bb069f40e6b4bd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.\nThe values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example \u2212\n\n#!/usr/bin/python\n\nlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntinylist = [123, 'john']\n\nprint list # Prints complete list\nprint list[0] # Prints first element of the list\nprint list[1:3] # Prints elements starting from 2nd till 3rd \nprint list[2:] # Prints elements starting from 3rd element\nprint tinylist * 2 # Prints list two times\nprint list + tinylist # Prints concatenated lists\n\nThis produce the following result \u2212\n\n['abcd', 786, 2.23, 'john', 70.2]\nabcd\n[786, 2.23]\n[2.23, 'john', 70.2]\n[123, 'john', 123, 'john']\n['abcd', 786, 2.23, 'john', 70.2, 123, 'john']", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "abf3a5d04216b0492eba4cc54106d197", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.\nThe main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example \u2212\n\n#!/usr/bin/python\n\ntuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )\ntinytuple = (123, 'john')\n\nprint tuple # Prints the complete tuple\nprint tuple[0] # Prints first element of the tuple\nprint tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd \nprint tuple[2:] # Prints elements of the tuple starting from 3rd element\nprint tinytuple * 2 # Prints the contents of the tuple twice\nprint tuple + tinytuple # Prints concatenated tuples\n\nThis produce the following result \u2212\n\n('abcd', 786, 2.23, 'john', 70.2)\nabcd\n(786, 2.23)\n(2.23, 'john', 70.2)\n(123, 'john', 123, 'john')\n('abcd', 786, 2.23, 'john', 70.2, 123, 'john')\n\nThe following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists \u2212\n\n#!/usr/bin/python\n\ntuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )\nlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntuple[2] = 1000 # Invalid syntax with tuple\nlist[2] = 1000 # Valid syntax with list", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "34a42804eb8d4fc77c0e2bbc14636f82", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.\nDictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example \u2212\n\n#!/usr/bin/python\n\ndict = {}\ndict['one'] = \"This is one\"\ndict[2] = \"This is two\"\n\ntinydict = {'name': 'john','code':6734, 'dept': 'sales'}\n\n\nprint dict['one'] # Prints value for 'one' key\nprint dict[2] # Prints value for 2 key\nprint tinydict # Prints complete dictionary\nprint tinydict.keys() # Prints all the keys\nprint tinydict.values() # Prints all the values\n\nThis produce the following result \u2212\n\nThis is one\nThis is two\n{'dept': 'sales', 'code': 6734, 'name': 'john'}\n['dept', 'code', 'name']\n['sales', 6734, 'john']\n\nDictionaries have no concept of order among elements. It is incorrect to say that the elements are \"out of order\"; they are simply unordered.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1fa0de096bef3d2836f4a239f71e2e82", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.\nThere are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.\n\n\nSr.No.\nFunction & Description\n\n\n1\nint(x [,base])\nConverts x to an integer. base specifies the base if x is a string.\n\n\n\n2\n\nlong(x [,base] )\nConverts x to a long integer. base specifies the base if x is a string.\n\n\n\n3\n\nfloat(x)\nConverts x to a floating-point number.\n\n\n\n4\n\ncomplex(real [,imag])\nCreates a complex number.\n\n\n\n5\n\nstr(x)\nConverts object x to a string representation.\n\n\n\n6\n\nrepr(x)\nConverts object x to an expression string.\n\n\n\n7\n\neval(str)\nEvaluates a string and returns an object.\n\n\n\n8\n\ntuple(s)\nConverts s to a tuple.\n\n\n\n9\n\nlist(s)\nConverts s to a list.\n\n\n\n10\n\nset(s)\nConverts s to a set.\n\n\n\n11\n\ndict(d)\nCreates a dictionary. d must be a sequence of (key,value) tuples.\n\n\n\n12\n\nfrozenset(s)\nConverts s to a frozen set.\n\n\n\n13\n\nchr(x)\nConverts an integer to a character.\n\n\n\n14\n\nunichr(x)\nConverts an integer to a Unicode character.\n\n\n\n15\n\nord(x)\nConverts a single character to its integer value.\n\n\n\n16\n\nhex(x)\nConverts an integer to a hexadecimal string.\n\n\n\n17\n\noct(x)\nConverts an integer to an octal string.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d5c419727f377b998efa0dcd7229fd8f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Operators are the constructs which can manipulate the value of operands.\nConsider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "342246f850dd33539ab457f4a0f2c419", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python language supports the following types of operators.\n\nArithmetic Operators\nComparison (Relational) Operators\nAssignment Operators\nLogical Operators\nBitwise Operators\nMembership Operators\nIdentity Operators\n\nLet us have a look on all operators one by one.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0e62e9540c84f918d73b642875a888df", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n+ Addition\nAdds values on either side of the operator.\na + b = 30\n\n\n- Subtraction\nSubtracts right hand operand from left hand operand.\na \u2013 b = -10\n\n\n* Multiplication\nMultiplies values on either side of the operator\na * b = 200\n\n\n/ Division\nDivides left hand operand by right hand operand\nb / a = 2\n\n\n% Modulus\nDivides left hand operand by right hand operand and returns remainder\nb % a = 0\n\n\n** Exponent\nPerforms exponential (power) calculation on operators\na**b =10 to the power 20\n\n\n//\nFloor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) \u2212\n9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "da718a71a79bec324474907977cbd815", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.\nAssume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n==\nIf the values of two operands are equal, then the condition becomes true.\n(a == b) is not true.\n\n\n!=\nIf values of two operands are not equal, then condition becomes true.\n(a != b) is true.\n\n\n<>\nIf values of two operands are not equal, then condition becomes true.\n(a <> b) is true. This is similar to != operator.\n\n\n>\nIf the value of left operand is greater than the value of right operand, then condition becomes true.\n(a > b) is not true.\n\n\n<\nIf the value of left operand is less than the value of right operand, then condition becomes true.\n(a < b) is true.\n\n\n>=\nIf the value of left operand is greater than or equal to the value of right operand, then condition becomes true.\n(a >= b) is not true.\n\n\n<=\nIf the value of left operand is less than or equal to the value of right operand, then condition becomes true.\n(a <= b) is true.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e059dcf6e80d9ee729413e7815e495b0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume variable a holds 10 and variable b holds 20, then \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n=\nAssigns values from right side operands to left side operand\nc = a + b assigns value of a + b into c\n\n\n+= Add AND\nIt adds right operand to the left operand and assign the result to left operand\nc += a is equivalent to c = c + a\n\n\n-= Subtract AND\nIt subtracts right operand from the left operand and assign the result to left operand\nc -= a is equivalent to c = c - a\n\n\n*= Multiply AND\nIt multiplies right operand with the left operand and assign the result to left operand\nc *= a is equivalent to c = c * a\n\n\n/= Divide AND\nIt divides left operand with the right operand and assign the result to left operand\nc /= a is equivalent to c = c / a\n\n\n%= Modulus AND\nIt takes modulus using two operands and assign the result to left operand\nc %= a is equivalent to c = c % a\n\n\n**= Exponent AND\nPerforms exponential (power) calculation on operators and assign value to the left operand\nc **= a is equivalent to c = c ** a\n\n\n//= Floor Division\nIt performs floor division on operators and assign value to the left operand\nc //= a is equivalent to c = c // a", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "70987db9042c1e3d41d8095141f00df7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands \u2212\na = 0011 1100\nb = 0000 1101\n-----------------\na&b = 0000 1100\na|b = 0011 1101\na^b = 0011 0001\n~a\u00a0 = 1100 0011\nThere are following Bitwise operators supported by Python language\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\n& Binary AND\nOperator copies a bit to the result if it exists in both operands\n(a & b) (means 0000 1100)\n\n\n| Binary OR\nIt copies a bit if it exists in either operand.\n(a | b) = 61 (means 0011 1101)\n\n\n^ Binary XOR\nIt copies the bit if it is set in one operand but not both.\n(a ^ b) = 49 (means 0011 0001)\n\n\n~ Binary Ones Complement\nIt is unary and has the effect of 'flipping' bits.\n(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.\n\n\n<< Binary Left Shift\nThe left operands value is moved left by the number of bits specified by the right operand.\na << 2 = 240 (means 1111 0000)\n\n\n>> Binary Right Shift\nThe left operands value is moved right by the number of bits specified by the right operand.\na >> 2 = 15 (means 0000 1111)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a1fd739ad46a7514408c28ac19563de", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nand Logical AND\nIf both the operands are true then condition becomes true.\n(a and b) is true.\n\n\nor Logical OR\nIf any of the two operands are non-zero then condition becomes true.\n(a or b) is true.\n\n\nnot Logical NOT\nUsed to reverse the logical state of its operand.\nNot(a and b) is false.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "05923cee9718fa2b18c63a0214f233e1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python\u2019s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nin\nEvaluates to true if it finds a variable in the specified sequence and false otherwise.\nx in y, here in results in a 1 if x is a member of sequence y.\n\n\nnot in\nEvaluates to true if it does not finds a variable in the specified sequence and false otherwise.\nx not in y, here not in results in a 1 if x is not a member of sequence y.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "27e6c66cdfa3e6ff443ae70471cf84c2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Identity operators compare the memory locations of two objects. There are two Identity operators explained below \u2212\n[ Show Example ]\n\n\nOperator\nDescription\nExample\n\n\nis\nEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.\nx is y, here is results in 1 if id(x) equals id(y).\n\n\nis not\nEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.\nx is not y, here is not results in 1 if id(x) is not equal to id(y).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e50ac7d1f513a1011ca19c40090a2588", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following table lists all operators from highest precedence to lowest.\n[ Show Example ]\n\n\nSr.No.\nOperator & Description\n\n\n1\n**\nExponentiation (raise to the power)\n\n\n2\n~ + -\nComplement, unary plus and minus (method names for the last two are +@ and -@)\n\n\n3\n* / % //\nMultiply, divide, modulo and floor division\n\n\n4\n+ -\nAddition and subtraction\n\n\n5\n>> <<\nRight and left bitwise shift\n\n\n6\n&\nBitwise 'AND'\n\n\n7\n^ |\nBitwise exclusive `OR' and regular `OR'\n\n\n8\n<= < > >=\nComparison operators\n\n\n9\n<> == !=\nEquality operators\n\n\n10\n= %= /= //= -= += *= **=\nAssignment operators\n\n\n11\nis is not\nIdentity operators\n\n\n12\nin not in\nMembership operators\n\n\n13\nnot or and\nLogical operators", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fe18d911b1d1d0add1f8f83e2d00070e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.\nDecision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.\nFollowing is the general form of a typical decision making structure found in most of the programming languages \u2212\n\nPython programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.\nPython programming language provides following types of decision making statements. Click the following links to check their detail.\n\n\nSr.No.\nStatement & Description\n\n\n1\nif statements\nAn if statement consists of a boolean expression followed by one or more statements.\n\n\n2\nif...else statements\nAn if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.\n\n\n3\nnested if statements\nYou can use one if or else if statement inside another if or else if statement(s).\n\n\nLet us go through each decision making briefly \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e5315f0728594efdb99fe17f90bbedfe", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.\nHere is an example of a one-line if clause \u2212\n\n#!/usr/bin/python\n\nvar = 100\nif ( var == 100 ) : print \"Value of expression is 100\"\nprint \"Good bye!\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nValue of expression is 100\nGood bye!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "26d1e2b000da4c9bf5793a1f9e606a9c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.\nProgramming languages provide various control structures that allow for more complicated execution paths.\nA loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement \u2212\n\nPython programming language provides following types of loops to handle looping requirements.\n\n\nSr.No.\nLoop Type & Description\n\n\n1\nwhile loop\nRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.\n\n\n2\nfor loop\nExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.\n\n\n3\nnested loops\nYou can use one or more loop inside any another while, for or do..while loop.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "52d1c0d64f315dfc44f388435459963c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.\nPython supports the following control statements. Click the following links to check their detail.\nLet us go through the loop control statements briefly\n\n\nSr.No.\nControl Statement & Description\n\n\n1\nbreak statement\nTerminates the loop statement and transfers execution to the statement immediately following the loop.\n\n\n2\ncontinue statement\nCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.\n\n\n3\npass statement\nThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "108d611c4fc0e6a3b732afcf16b45268", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.\nNumber objects are created when you assign a value to them. For example \u2212\n\nvar1 = 1\nvar2 = 10\n\nYou can also delete the reference to a number object by using the del statement. The syntax of the del statement is \u2212\n\ndel var1[,var2[,var3[....,varN]]]]\n\nYou can delete a single object or multiple objects by using the del statement. For example \u2212\n\ndel var\ndel var_a, var_b\n\nPython supports four different numerical types \u2212\n\nint (signed integers) \u2212 They are often called just integers or ints, are positive or negative whole numbers with no decimal point.\nlong (long integers ) \u2212 Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.\nfloat (floating point real values) \u2212 Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).\ncomplex (complex numbers) \u2212 are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b8dbb88479fbb66e527abc5cc6c6d33c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here are some examples of numbers\n\n\nint\nlong\nfloat\ncomplex\n\n\n10\n51924361L\n0.0\n3.14j\n\n\n100\n-0x19323L\n15.20\n45.j\n\n\n-786\n0122L\n-21.9\n9.322e-36j\n\n\n080\n0xDEFABCECBDAECBFBAEL\n32.3+e18\n.876j\n\n\n-0490\n535633629843L\n-90.\n-.6545+0J\n\n\n-0x260\n-052318172735L\n-32.54e100\n3e+26J\n\n\n0x69\n-4721885298529L\n70.2-E12\n4.53e-7j\n\n\n\nPython allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.\nA complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "266bf68a20270245127d5e6ebea85c13", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.\n\nType int(x) to convert x to a plain integer.\nType long(x) to convert x to a long integer.\nType float(x) to convert x to a floating-point number.\nType complex(x) to convert x to a complex number with real part x and imaginary part zero.\nType complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "933f0e9b6e193f9fbc1552f8ca41cccd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes following functions that perform mathematical calculations.\n\n\nSr.No.\nFunction & Returns ( description )\n\n\n1\nabs(x)\nThe absolute value of x: the (positive) distance between x and zero.\n\n\n2\nceil(x)\nThe ceiling of x: the smallest integer not less than x\n\n\n3\ncmp(x, y)\n-1 if x < y, 0 if x == y, or 1 if x > y\n\n\n4\nexp(x)\nThe exponential of x: ex\n\n\n5\nfabs(x)\nThe absolute value of x.\n\n\n6\nfloor(x)\nThe floor of x: the largest integer not greater than x\n\n\n7\nlog(x)\nThe natural logarithm of x, for x> 0\n\n\n8\nlog10(x)\nThe base-10 logarithm of x for x> 0.\n\n\n9\nmax(x1, x2,...)\nThe largest of its arguments: the value closest to positive infinity\n\n\n10\nmin(x1, x2,...)\nThe smallest of its arguments: the value closest to negative infinity\n\n\n11\nmodf(x)\nThe fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.\n\n\n12\npow(x, y)\nThe value of x**y.\n\n\n13\nround(x [,n])\nx rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.\n\n\n14\nsqrt(x)\nThe square root of x for x > 0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6593b948d7b67e9e1b704982ee06f4b5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.\n\n\nSr.No.\nFunction & Description\n\n\n1\nchoice(seq)\nA random item from a list, tuple, or string.\n\n\n2\nrandrange ([start,] stop [,step])\nA randomly selected element from range(start, stop, step)\n\n\n3\nrandom()\nA random float r, such that 0 is less than or equal to r and r is less than 1\n\n\n4\nseed([x])\nSets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.\n\n\n5\nshuffle(lst)\nRandomizes the items of a list in place. Returns None.\n\n\n6\nuniform(x, y)\nA random float r, such that x is less than or equal to r and r is less than y", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7e7046d8939df55e459b4b83521b7ab4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes following functions that perform trigonometric calculations.\n\n\nSr.No.\nFunction & Description\n\n\n1\nacos(x)\nReturn the arc cosine of x, in radians.\n\n\n2\nasin(x)\nReturn the arc sine of x, in radians.\n\n\n3\natan(x)\nReturn the arc tangent of x, in radians.\n\n\n4\natan2(y, x)\nReturn atan(y / x), in radians.\n\n\n5\ncos(x)\nReturn the cosine of x radians.\n\n\n6\nhypot(x, y)\nReturn the Euclidean norm, sqrt(x*x + y*y).\n\n\n7\nsin(x)\nReturn the sine of x radians.\n\n\n8\ntan(x)\nReturn the tangent of x radians.\n\n\n9\ndegrees(x)\nConverts angle x from radians to degrees.\n\n\n10\nradians(x)\nConverts angle x from degrees to radians.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1bb1ae0ca4a88944b3e8daa58f8de2f9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The module also defines two mathematical constants \u2212\n\n\nSr.No.\nConstants & Description\n\n\n1\npi\nThe mathematical constant pi.\n\n\n2\ne\nThe mathematical constant e.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "91901941fba98466fbb49f75e5496f2c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example \u2212\n\nvar1 = 'Hello World!'\nvar2 = \"Python Programming\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b0ec2635e4ba915cf3c9ddeb73c9d7a9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python does not support a character type; these are treated as strings of length one, thus also considered a substring.\nTo access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example \u2212\n\n#!/usr/bin/python\n\nvar1 = 'Hello World!'\nvar2 = \"Python Programming\"\n\nprint \"var1[0]: \", var1[0]\nprint \"var2[1:5]: \", var2[1:5]\n\nWhen the above code is executed, it produces the following result \u2212\n\nvar1[0]: H\nvar2[1:5]: ytho", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7142ba98fe018993f6eb6226b3642b18", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can \"update\" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example \u2212\n\n#!/usr/bin/python\n\nvar1 = 'Hello World!'\nprint \"Updated String :- \", var1[:6] + 'Python'\n\nWhen the above code is executed, it produces the following result \u2212\n\nUpdated String :- Hello Python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c5a6e88b4f1ee8b552ea6ba02928841c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following table is a list of escape or non-printable characters that can be represented with backslash notation.\nAn escape character gets interpreted; in a single quoted as well as double quoted strings.\n\n\nBackslash notation\nHexadecimal character\nDescription\n\n\n\\a\n0x07\nBell or alert\n\n\n\\b\n0x08\nBackspace\n\n\n\\cx\n\u00a0\nControl-x\n\n\n\\C-x\n\u00a0\nControl-x\n\n\n\\e\n0x1b\nEscape\n\n\n\\f\n0x0c\nFormfeed\n\n\n\\M-\\C-x\n\u00a0\nMeta-Control-x\n\n\n\\n\n0x0a\nNewline\n\n\n\\nnn\n\u00a0\nOctal notation, where n is in the range 0.7\n\n\n\\r\n0x0d\nCarriage return\n\n\n\\s\n0x20\nSpace\n\n\n\\t\n0x09\nTab\n\n\n\\v\n0x0b\nVertical tab\n\n\n\\x\n\u00a0\nCharacter x\n\n\n\\xnn\n\u00a0\nHexadecimal notation, where n is in the range 0.9, a.f, or A.F", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f7f51c9c20b522002086e60b9838ead4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Assume string variable a holds 'Hello' and variable b holds 'Python', then \u2212\n\n\nOperator\nDescription\nExample\n\n\n+\nConcatenation - Adds values on either side of the operator\na + b will give HelloPython\n\n\n*\nRepetition - Creates new strings, concatenating multiple copies of the same\nstring\na*2 will give -HelloHello\n\n\n[]\nSlice - Gives the character from the given index\na[1] will give e\n\n\n[ : ]\nRange Slice - Gives the characters from the given range\na[1:4] will give ell\n\n\nin\nMembership - Returns true if a character exists in the given string\nH in a will give 1\n\n\nnot in \nMembership - Returns true if a character does not exist in the given string\nM not in a will give 1\n\n\nr/R\nRaw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter \"r,\" which precedes the quotation marks. The \"r\" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.\nprint r'\\n' prints \\n and print R'\\n'prints \\n\n\n\n%\nFormat - Performs String formatting\nSee at next section", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dc68ed8c48f5050ce597809be7d8b6f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example \u2212\n\n#!/usr/bin/python\n\nprint \"My name is %s and weight is %d kg!\" % ('Zara', 21)\n\nWhen the above code is executed, it produces the following result \u2212\n\nMy name is Zara and weight is 21 kg!\n\nHere is the list of complete set of symbols which can be used along with % \u2212\n\n\nFormat Symbol\nConversion\n\n\n%c\ncharacter\n\n\n%s\nstring conversion via str() prior to formatting\n\n\n%i\nsigned decimal integer\n\n\n%d\nsigned decimal integer\n\n\n%u\nunsigned decimal integer\n\n\n%o\noctal integer\n\n\n%x\nhexadecimal integer (lowercase letters)\n\n\n%X\nhexadecimal integer (UPPERcase letters)\n\n\n%e\nexponential notation (with lowercase 'e')\n\n\n%E\nexponential notation (with UPPERcase 'E')\n\n\n%f\nfloating point real number\n\n\n%g\nthe shorter of %f and %e\n\n\n%G\nthe shorter of %f and %E\n\n\nOther supported symbols and functionality are listed in the following table \u2212\n\n\nSymbol\nFunctionality\n\n\n*\nargument specifies width or precision\n\n\n-\nleft justification\n\n\n+\ndisplay the sign\n\n\n<sp>\nleave a blank space before a positive number\n\n\n#\nadd the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.\n\n\n0\npad from left with zeros (instead of spaces)\n\n\n%\n'%%' leaves you with a single literal '%'\n\n\n(var)\nmapping variable (dictionary arguments)\n\n\nm.n.\nm is the minimum total width and n is the number of digits to display after the decimal point (if appl.)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "95c38ab2ceeaac6528635d73519f3083", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.\nThe syntax for triple quotes consists of three consecutive single or double quotes.\n\n#!/usr/bin/python\n\npara_str = \"\"\"this is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( \\t ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [ \\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n\"\"\"\nprint para_str\n\nWhen the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the \"up.\" and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\\n) \u2212\n\nthis is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n\nRaw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it \u2212\n\n#!/usr/bin/python\n\nprint 'C:\\\\nowhere'\n\nWhen the above code is executed, it produces the following result \u2212\n\nC:\\nowhere\n\nNow let's make use of raw string. We would put expression in r'expression' as follows \u2212\n\n#!/usr/bin/python\n\nprint r'C:\\\\nowhere'\n\nWhen the above code is executed, it produces the following result \u2212\n\nC:\\\\nowhere", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c96a949246a3a94aba960ab503aa10ad", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following \u2212\n\n#!/usr/bin/python\n\nprint u'Hello, world!'\n\nWhen the above code is executed, it produces the following result \u2212\n\nHello, world!\n\nAs you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "12f2d17b1dd1dfe522278fbe8a7be580", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes the following built-in methods to manipulate strings \u2212\n\n\nSr.No.\nMethods with Description\n\n\n1\ncapitalize()\nCapitalizes first letter of string\n\n\n2\ncenter(width, fillchar)\nReturns a space-padded string with the original string centered to a total of width columns.\n\n\n3\ncount(str, beg= 0,end=len(string))\nCounts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.\n\n\n4\ndecode(encoding='UTF-8',errors='strict')\nDecodes the string using the codec registered for encoding. encoding defaults to the default string encoding.\n\n\n5\nencode(encoding='UTF-8',errors='strict')\nReturns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.\n\n\n6\nendswith(suffix, beg=0, end=len(string))\nDetermines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.\n\n\n7\nexpandtabs(tabsize=8)\nExpands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.\n\n\n8\nfind(str, beg=0 end=len(string))\nDetermine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.\n\n\n9\nindex(str, beg=0, end=len(string))\nSame as find(), but raises an exception if str not found.\n\n\n10\nisalnum()\nReturns true if string has at least 1 character and all characters are alphanumeric and false otherwise.\n\n\n11\nisalpha()\nReturns true if string has at least 1 character and all characters are alphabetic and false otherwise.\n\n\n12\nisdigit()\nReturns true if string contains only digits and false otherwise.\n\n\n13\nislower()\nReturns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.\n\n\n14\nisnumeric()\nReturns true if a unicode string contains only numeric characters and false otherwise.\n\n\n15\nisspace()\nReturns true if string contains only whitespace characters and false otherwise.\n\n\n16", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2446be82f02cf154c89f87d104a0192d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\nistitle()\nReturns true if string is properly \"titlecased\" and false otherwise.\n\n\n17\nisupper()\nReturns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.\n\n\n18\njoin(seq)\nMerges (concatenates) the string representations of elements in sequence seq into a string, with separator string.\n\n\n19\nlen(string)\nReturns the length of the string\n\n\n20\nljust(width[, fillchar])\nReturns a space-padded string with the original string left-justified to a total of width columns.\n\n\n21\nlower()\nConverts all uppercase letters in string to lowercase.\n\n\n22\nlstrip()\nRemoves all leading whitespace in string.\n\n\n23\nmaketrans()\nReturns a translation table to be used in translate function.\n\n\n24\nmax(str)\nReturns the max alphabetical character from the string str.\n\n\n25\nmin(str)\nReturns the min alphabetical character from the string str.\n\n\n26\nreplace(old, new [, max])\nReplaces all occurrences of old in string with new or at most max occurrences if max given.\n\n\n27\nrfind(str, beg=0,end=len(string))\nSame as find(), but search backwards in string.\n\n\n28\nrindex( str, beg=0, end=len(string))\nSame as index(), but search backwards in string.\n\n\n29\nrjust(width,[, fillchar])\nReturns a space-padded string with the original string right-justified to a total of width columns.\n\n\n30\nrstrip()\nRemoves all trailing whitespace of string.\n\n\n31\nsplit(str=\"\", num=string.count(str))\nSplits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.\n\n\n32\nsplitlines( num=string.count('\\n'))\nSplits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.\n\n\n33\nstartswith(str, beg=0,end=len(string))\nDetermines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.\n\n\n34\nstrip([chars])\nPerforms both lstrip() and rstrip() on string.\n\n\n35\nswapcase()\nInverts case for all letters in string.\n\n\n36\ntitle()\nReturns \"titlecased", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "42b89ee06fdea542a4f499bddecc299f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\" version of string, that is, all words begin with uppercase and the rest are lowercase.\n\n\n37\ntranslate(table, deletechars=\"\")\nTranslates string according to translation table str(256 chars), removing those in the del string.\n\n\n38\nupper()\nConverts lowercase letters in string to uppercase.\n\n\n39\nzfill (width)\nReturns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).\n\n\n40\nisdecimal()\nReturns true if a unicode string contains only decimal characters and false otherwise.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "05f4ad73d3460c7a68f2c38931ee8911", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.\nPython has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.\nThere are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fe24e88850dd6b06e1da2fd27fa7f89a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.\nCreating a list is as simple as putting different comma-separated values between square brackets. For example \u2212\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5 ];\nlist3 = [\"a\", \"b\", \"c\", \"d\"]\n\nSimilar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "54a4e5337da75224909964c23f0d4109", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example \u2212\n\n#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]\n\nWhen the above code is executed, it produces the following result \u2212\n\nlist1[0]: physics\nlist2[1:5]: [2, 3, 4, 5]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c69fc2cce7d7cd7b302934e5d1e6a3b3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example \u2212\n\n#!/usr/bin/python\n\nlist = ['physics', 'chemistry', 1997, 2000];\nprint \"Value available at index 2 : \"\nprint list[2]\nlist[2] = 2001;\nprint \"New value available at index 2 : \"\nprint list[2]\n\nNote \u2212 append() method is discussed in subsequent section.\nWhen the above code is executed, it produces the following result \u2212\n\nValue available at index 2 :\n1997\nNew value available at index 2 :\n2001", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d63639b98390d1f1282813ad0c8a9b32", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example \u2212\n\n#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nprint list1\ndel list1[2];\nprint \"After deleting value at index 2 : \"\nprint list1\n\nWhen the above code is executed, it produces following result \u2212\n\n['physics', 'chemistry', 1997, 2000]\nAfter deleting value at index 2 :\n['physics', 'chemistry', 2000]\n\nNote \u2212 remove() method is discussed in subsequent section.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "caa154259ff1ffff7424c3e305115bed", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.\nIn fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.\n\n\nPython Expression\nResults\nDescription\n\n\nlen([1, 2, 3])\n3\nLength\n\n\n[1, 2, 3] + [4, 5, 6]\n[1, 2, 3, 4, 5, 6]\nConcatenation\n\n\n['Hi!'] * 4\n['Hi!', 'Hi!', 'Hi!', 'Hi!']\nRepetition\n\n\n3 in [1, 2, 3]\nTrue\nMembership\n\n\nfor x in [1, 2, 3]: print x,\n1 2 3\nIteration", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7ec8078624ed76180321a54d4542deaa", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.\nAssuming following input \u2212\n\nL = ['spam', 'Spam', 'SPAM!']\n\n\n\n\nPython Expression\nResults\nDescription\n\n\nL[2]\nSPAM!\nOffsets start at zero\n\n\nL[-2]\nSpam\nNegative: count from the right\n\n\nL[1:]\n['Spam', 'SPAM!']\nSlicing fetches sections", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "18aabb1d10eb363c6ab73ebbf8eac53b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes the following list functions \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ncmp(list1, list2)\nCompares elements of both lists.\n\n\n2\nlen(list)\nGives the total length of the list.\n\n\n3\nmax(list)\nReturns item from the list with max value.\n\n\n4\nmin(list)\nReturns item from the list with min value.\n\n\n5\nlist(seq)\nConverts a tuple into list.\n\n\nPython includes following list methods\n\n\nSr.No.\nMethods with Description\n\n\n1\nlist.append(obj)\nAppends object obj to list\n\n\n2\nlist.count(obj)\nReturns count of how many times obj occurs in list\n\n\n3\nlist.extend(seq)\nAppends the contents of seq to list\n\n\n4\nlist.index(obj)\nReturns the lowest index in list that obj appears\n\n\n5\nlist.insert(index, obj)\nInserts object obj into list at offset index\n\n\n6\nlist.pop(obj=list[-1])\nRemoves and returns last object or obj from list\n\n\n7\nlist.remove(obj)\nRemoves object obj from list\n\n\n8\nlist.reverse()\nReverses objects of list in place\n\n\n9\nlist.sort([func])\nSorts objects of list, use compare func if given", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3286140cf20f8a845981b593ab088b57", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A tuple is an immutable sequence of Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.\nCreating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example \u2212\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5 );\ntup3 = \"a\", \"b\", \"c\", \"d\";\n\nThe empty tuple is written as two parentheses containing nothing \u2212\n\ntup1 = ();\n\nTo write a tuple containing a single value you have to include a comma, even though there is only one value \u2212\n\ntup1 = (50,);\n\nLike string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "11f64398422d9dac7fe8afa305e8d86b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example \u2212\n\n#!/usr/bin/python\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0];\nprint \"tup2[1:5]: \", tup2[1:5];\n\nWhen the above code is executed, it produces the following result \u2212\n\ntup1[0]: physics\ntup2[1:5]: [2, 3, 4, 5]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f674e140ae54a46fcc9e930ae848b60f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates \u2212\n\n#!/usr/bin/python\n\ntup1 = (12, 34.56);\ntup2 = ('abc', 'xyz');\n\n# Following action is not valid for tuples\n# tup1[0] = 100;\n\n# So let's create a new tuple as follows\ntup3 = tup1 + tup2;\nprint tup3;\n\nWhen the above code is executed, it produces the following result \u2212\n\n(12, 34.56, 'abc', 'xyz')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "154e71cd91fe362f328419aadfda2c6c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.\nTo explicitly remove an entire tuple, just use the del statement. For example \u2212\n\n#!/usr/bin/python\n\ntup = ('physics', 'chemistry', 1997, 2000);\nprint tup;\ndel tup;\nprint \"After deleting tup : \";\nprint tup;\n\nThis produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more \u2212\n\n('physics', 'chemistry', 1997, 2000)\nAfter deleting tup :\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print tup;\nNameError: name 'tup' is not defined", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4cdceac6d8e764cf32b30c8ee0734fa6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.\nIn fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter \u2212\n\n\nPython Expression\nResults\nDescription\n\n\nlen((1, 2, 3))\n3\nLength\n\n\n(1, 2, 3) + (4, 5, 6)\n(1, 2, 3, 4, 5, 6)\nConcatenation\n\n\n('Hi!',) * 4\n('Hi!', 'Hi!', 'Hi!', 'Hi!')\nRepetition\n\n\n3 in (1, 2, 3)\nTrue\nMembership\n\n\nfor x in (1, 2, 3): print x,\n1 2 3\nIteration", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b8fefefc60c7537d58603738c0e39905", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input \u2212\n\nL = ('spam', 'Spam', 'SPAM!')\n\n\u00a0\n\n\nPython Expression\nResults\nDescription\n\n\nL[2]\n'SPAM!'\nOffsets start at zero\n\n\nL[-2]\n'Spam'\nNegative: count from the right\n\n\nL[1:]\n['Spam', 'SPAM!']\nSlicing fetches sections", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "295ddf2f68147beea828e18b5fcc2026", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples \u2212\n\n#!/usr/bin/python\n\nprint 'abc', -4.24e93, 18+6.6j, 'xyz';\nx, y = 1, 2;\nprint \"Value of x , y : \", x,y;\n\nWhen the above code is executed, it produces the following result \u2212\n\nabc -4.24e+93 (18+6.6j) xyz\nValue of x , y : 1 2", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cc1c5efafad0e97ee34638fb18edb09d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes the following tuple functions \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ncmp(tuple1, tuple2)\nCompares elements of both tuples.\n\n\n2\nlen(tuple)\nGives the total length of the tuple.\n\n\n3\nmax(tuple)\nReturns item from the tuple with max value.\n\n\n4\nmin(tuple)\nReturns item from the tuple with min value.\n\n\n5\ntuple(seq)\nConverts a list into tuple.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "24f1d5a1cdddb44b47d9967918877eb2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.\nKeys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9ab65f9a6f5ad330bb851521d727c3bd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Name']: Zara\ndict['Age']: 7\n\nIf we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Alice']:\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n print \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "701c53e9781e4e16f9aacaa9c012c91b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Age']: 8\ndict['School']: DPS School", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f62856bb42337d404ec0c0e438043448", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.\nTo explicitly remove an entire dictionary, just use the del statement. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']\n\nThis produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more \u2212\n\ndict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n\nNote \u2212 del() method is discussed in subsequent section.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "54f380afa81b50459afea1a276584732", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.\nThere are two important points to remember about dictionary keys \u2212\n(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example \u2212\n\n#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']\n\nWhen the above code is executed, it produces the following result \u2212\n\ndict['Name']: Manni\n\n(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']\n\nWhen the above code is executed, it produces the following result \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 3, in <module>\n dict = {['Name']: 'Zara', 'Age': 7};\nTypeError: unhashable type: 'list'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bc311358933eae94c2c53d2c1214a187", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python includes the following dictionary functions \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ncmp(dict1, dict2)\nCompares elements of both dict.\n\n\n2\nlen(dict)\nGives the total length of the dictionary. This would be equal to the number of items in the dictionary.\n\n\n3\nstr(dict)\nProduces a printable string representation of a dictionary\n\n\n4\ntype(variable)\nReturns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.\n\n\nPython includes following dictionary methods \u2212\n\n\nSr.No.\nMethods with Description\n\n\n1\ndict.clear()\nRemoves all elements of dictionary dict\n\n\n2\ndict.copy()\nReturns a shallow copy of dictionary dict\n\n\n3\ndict.fromkeys()\nCreate a new dictionary with keys from seq and values set to value.\n\n\n4\ndict.get(key, default=None)\nFor key key, returns value or default if key not in dictionary\n\n\n5\ndict.has_key(key)\nReturns true if key in dictionary dict, false otherwise\n\n\n6\ndict.items()\nReturns a list of dict's (key, value) tuple pairs\n\n\n7\ndict.keys()\nReturns list of dictionary dict's keys\n\n\n8\ndict.setdefault(key, default=None)\nSimilar to get(), but will set dict[key]=default if key is not already in dict\n\n\n9\ndict.update(dict2)\nAdds dictionary dict2's key-values pairs to dict\n\n\n10\ndict.values()\nReturns list of dictionary dict's values", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6ddd87c3d11bc663a4c2c226580a0dc2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "899c956e3cbbdfebb85c8d85a137b31b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 00:00:00 hrs January 1, 1970(epoch).\nThere is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 00:00:00 hrs January 1, 1970(epoch).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4c571ef1da6dff1fb3d0a2dc9c8f447f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport time; # This is required to include time module.\n\nticks = time.time()\nprint \"Number of ticks since 12:00am, January 1, 1970:\", ticks\n\nThis would produce a result something as follows \u2212\n\nNumber of ticks since 12:00am, January 1, 1970: 7186862.73399\n\nDate arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5eb2985e816131c7a374e6f1646f9051", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Many of Python's time functions handle time as a tuple of 9 numbers, as shown below \u2212\n\n\nIndex\nField\nValues\n\n\n0\n4-digit year\n2008\n\n\n1\nMonth\n1 to 12\n\n\n2\nDay\n1 to 31\n\n\n3\nHour\n0 to 23\n\n\n4\nMinute\n0 to 59\n\n\n5\nSecond\n0 to 61 (60 or 61 are leap-seconds)\n\n\n6\nDay of Week\n0 to 6 (0 is Monday)\n\n\n7\nDay of year\n1 to 366 (Julian day)\n\n\n8\nDaylight savings\n-1, 0, 1, -1 means library determines DST\n\n\nThe above tuple is equivalent to struct_time structure. This structure has following attributes \u2212\n\n\nIndex\nAttributes\nValues\n\n\n0\ntm_year\n2008\n\n\n1\ntm_mon\n1 to 12\n\n\n2\ntm_mday\n1 to 31\n\n\n3\ntm_hour\n0 to 23\n\n\n4\ntm_min\n0 to 59\n\n\n5\ntm_sec\n0 to 61 (60 or 61 are leap-seconds)\n\n\n6\ntm_wday\n0 to 6 (0 is Monday)\n\n\n7\ntm_yday\n1 to 366 (Julian day)\n\n\n8\ntm_isdst\n-1, 0, 1, -1 means library determines DST", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "63094e49ba4a0f94532f9c72ca0e905a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To translate a time instant from a seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid.\n\n#!/usr/bin/python\nimport time;\n\nlocaltime = time.localtime(time.time())\nprint \"Local current time :\", localtime\n\nThis would produce the following result, which could be formatted in any other presentable form \u2212\n\nLocal current time : time.struct_time(tm_year=2013, tm_mon=7, \ntm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fb11a4db121ca52027a69f1b1a84456d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can format any time as per your requirement, but simple method to get time in readable format is asctime() \u2212\n\n#!/usr/bin/python\nimport time;\n\nlocaltime = time.asctime( time.localtime(time.time()) )\nprint \"Local current time :\", localtime\n\nThis would produce the following result \u2212\n\nLocal current time : Tue Jan 13 10:17:09 2009", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "12a92a437d9ef802e048d0aac311c8b5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) \u2212\n\n#!/usr/bin/python\nimport calendar\n\ncal = calendar.month(2008, 1)\nprint \"Here is the calendar:\"\nprint cal\n\nThis would produce the following result \u2212\n\nHere is the calendar:\n January 2008\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30 31", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "09dd52140fa9570e7999808c604a7845", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There is a popular time module available in Python which provides functions for working with times and for converting between representations. Here is the list of all available methods \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ntime.altzone\nThe offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.\n\n\n2\ntime.asctime([tupletime])\nAccepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.\n\n\n3\ntime.clock( )\nReturns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().\n\n\n4\ntime.ctime([secs])\nLike asctime(localtime(secs)) and without arguments is like asctime( )\n\n\n5\ntime.gmtime([secs])\nAccepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note : t.tm_isdst is always 0\n\n\n6\ntime.localtime([secs])\nAccepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).\n\n\n7\ntime.mktime(tupletime)\nAccepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.\n\n\n8\ntime.sleep(secs)\nSuspends the calling thread for secs seconds.\n\n\n9\ntime.strftime(fmt[,tupletime])\nAccepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.\n\n\n10\ntime.strptime(str,fmt='%a %b %d %H:%M:%S %Y')\nParses str according to format string fmt and returns the instant in time-tuple format.\n\n\n11\ntime.time( )\nReturns the current time instant, a floating-point number of seconds since the epoch.\n\n\n12\ntime.tzset()\nResets the time conversion rules used by the library routines. The environment variable TZ specifies how this is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "adbb801fe0132224c07bcdefd7e186d4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": " done.\n\n\nLet us go through the functions briefly \u2212\nThere are following two important attributes available with time module \u2212\n\n\nSr.No.\nAttribute with Description\n\n\n1\ntime.timezone\nAttribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).\n\n\n2\ntime.tzname\nAttribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "86b21a58848701ec32eed9ae56ea92e7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.\nBy default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function.\nHere is a list of functions available with the calendar module \u2212\n\n\nSr.No.\nFunction with Description\n\n\n1\ncalendar.calendar(year,w=2,l=1,c=6)\nReturns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.\n\n\n2\ncalendar.firstweekday( )\nReturns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.\n\n\n3\ncalendar.isleap(year)\nReturns True if year is a leap year; otherwise, False.\n\n\n4\ncalendar.leapdays(y1,y2)\nReturns the total number of leap days in the years within range(y1,y2).\n\n\n5\ncalendar.month(year,month,w=2,l=1)\nReturns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.\n\n\n6\ncalendar.monthcalendar(year,month)\nReturns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.\n\n\n7\ncalendar.monthrange(year,month)\nReturns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.\n\n\n8\ncalendar.prcal(year,w=2,l=1,c=6)\nLike print calendar.calendar(year,w,l,c).\n\n\n9\ncalendar.prmonth(year,month,w=2,l=1)\nLike print calendar.month(year,month,w,l).\n\n\n10\ncalendar.setfirstweekday(weekday)\nSets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dc11f5cf656fe91cb0b65a5abab2b579", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\n\n\n11\ncalendar.timegm(tupletime)\nThe inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.\n\n\n12\ncalendar.weekday(year,month,day)\nReturns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ac12f91b2b6c1f0d981e325c443a47e4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If you are interested, then here you would find a list of other important modules and functions to play with date & time in Python \u2212\n\nThe datetime Module\nThe pytz Module\nThe dateutil Module", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d51883223032f66f1ffaeb3c60f92dff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.\nAs you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7f16e822994f0561c7551a5f0ddbaa0b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can define functions to provide the required functionality. Here are simple rules to define a function in Python.\n\nFunction blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).\nAny input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.\nThe first statement of a function can be an optional statement - the documentation string of the function or docstring.\nThe code block within every function starts with a colon (:) and is indented.\nThe statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7ef95f6f8152ba1e8f3bce7d795f6e9c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "def functionname( parameters ):\n \"function_docstring\"\n function_suite\n return [expression]\n\nBy default, parameters have a positional behavior and you need to inform them in the same order that they were defined.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8349aa32b3a979315c88f9ca07778915", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following function takes a string as input parameter and prints it on standard screen.\n\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "047075b437cafbfba80c03aaffe45c2a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.\nOnce the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme(\"I'm first call to user defined function!\")\nprintme(\"Again second call to the same function\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nI'm first call to user defined function!\nAgain second call to the same function", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "87808fad7c2ab756f0c228911c58af1e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist.append([1,2,3,4]);\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist\n\nHere, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result \u2212\n\nValues inside the function: [10, 20, 30, [1, 2, 3, 4]]\nValues outside the function: [10, 20, 30, [1, 2, 3, 4]]\n\nThere is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.\n\n#!/usr/bin/python\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist = [1,2,3,4]; # This would assig new reference in mylist\n print \"Values inside the function: \", mylist\n return\n\n# Now you can call changeme function\nmylist = [10,20,30];\nchangeme( mylist );\nprint \"Values outside the function: \", mylist\n\nThe parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result \u2212\n\nValues inside the function: [1, 2, 3, 4]\nValues outside the function: [10, 20, 30]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "77c76d41cccb1138bca52ac75f644afa", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can call a function by using the following types of formal arguments \u2212\n\nRequired arguments\nKeyword arguments\nDefault arguments\nVariable-length arguments", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6b39428eb327ac6cbb033723aaf93e52", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.\nTo call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme()\n\nWhen the above code is executed, it produces the following result \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 11, in <module>\n printme();\nTypeError: printme() takes exactly 1 argument (0 given)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f7d2d6926da26bf85953188ec3f39f23", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.\nThis allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print str\n return;\n\n# Now you can call printme function\nprintme( str = \"My string\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nMy string\n\nThe following example gives more clear picture. Note that the order of parameters does not matter.\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\n\nWhen the above code is executed, it produces the following result \u2212\n\nName: miki\nAge 50", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "738901327bd2e17d3cb9d2f70a1234cc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( name, age = 35 ):\n \"This prints a passed info into this function\"\n print \"Name: \", name\n print \"Age \", age\n return;\n\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\nprintinfo( name=\"miki\" )\n\nWhen the above code is executed, it produces the following result \u2212\n\nName: miki\nAge 50\nName: miki\nAge 35", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c95c8cdc4202c6787da9d33bff9b1105", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.\nSyntax for a function with non-keyword variable arguments is this \u2212\n\ndef functionname([formal_args,] *var_args_tuple ):\n \"function_docstring\"\n function_suite\n return [expression]\n\nAn asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef printinfo( arg1, *vartuple ):\n \"This prints a variable passed arguments\"\n print \"Output is: \"\n print arg1\n for var in vartuple:\n print var\n return;\n\n# Now you can call printinfo function\nprintinfo( 10 )\nprintinfo( 70, 60, 50 )\n\nWhen the above code is executed, it produces the following result \u2212\n\nOutput is:\n10\nOutput is:\n70\n60\n50", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "768d146aa7193cbc175694822c591ae1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.\n\nLambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.\nAn anonymous function cannot be a direct call to print because lambda requires an expression\nLambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.\nAlthough it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9fa1438934fa41108b9ee1a6c4e3e6d1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The syntax of lambda functions contains only a single statement, which is as follows \u2212\n\nlambda [arg1 [,arg2,.....argn]]:expression\n\nFollowing is the example to show how lambda form of function works \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\nsum = lambda arg1, arg2: arg1 + arg2;\n\n# Now you can call sum as a function\nprint \"Value of total : \", sum( 10, 20 )\nprint \"Value of total : \", sum( 20, 20 )\n\nWhen the above code is executed, it produces the following result \u2212\n\nValue of total : 30\nValue of total : 40", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "808b03112562b7e7bb8b8372782b18fe", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.\nAll the above examples are not returning any value. You can return a value from a function as follows \u2212\n\n#!/usr/bin/python\n\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2\n print \"Inside the function : \", total\n return total;\n\n# Now you can call sum function\ntotal = sum( 10, 20 );\nprint \"Outside the function : \", total \n\nWhen the above code is executed, it produces the following result \u2212\n\nInside the function : 30\nOutside the function : 30", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0a6320a8484ca3e97dcf67e4f7252fb1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.\nThe scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python \u2212\n\nGlobal variables\nLocal variables", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a43a5d2b100278ad085bdb85f0f565d6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.\nThis means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example \u2212\n\n#!/usr/bin/python\n\ntotal = 0; # This is global variable.\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2; # Here total is local variable.\n print \"Inside the function local total : \", total\n return total;\n\n# Now you can call sum function\nsum( 10, 20 );\nprint \"Outside the function global total : \", total \n\nWhen the above code is executed, it produces the following result \u2212\n\nInside the function local total : 30\nOutside the function global total : 0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e414140227f17c76c8282146e5487629", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.\nSimply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6c69794286b0e94506c1d2634e2c5d72", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py\n\ndef print_func( par ):\n print \"Hello : \", par\n return", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a8ebee7458aa99b0df8c67259239bcf1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax \u2212\n\nimport module1[, module2[,... moduleN]\n\nWhen the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script \u2212\n\n#!/usr/bin/python\n\n# Import module support\nimport support\n\n# Now you can call defined function that module as follows\nsupport.print_func(\"Zara\")\n\nWhen the above code is executed, it produces the following result \u2212\n\nHello : Zara\n\nA module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "374450754f3fc619cbc4d1c4c61ea7ef", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax \u2212\n\nfrom modname import name1[, name2[, ... nameN]]\n\nFor example, to import the function fibonacci from the module fib, use the following statement \u2212\n\nfrom fib import fibonacci\n\nThis statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8bb31ff1ff3ec767331de9f04951039a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is also possible to import all names from a module into the current namespace by using the following import statement \u2212\n\nfrom modname import *\n\nThis provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "499d2d81d8942a9923ab7e1c2341c5f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When you import a module, the Python interpreter searches for the module in the following sequences \u2212\n\nThe current directory.\nIf the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.\nIf all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.\n\nThe module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "299625a503adf7907fe80dca69d45dff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.\nHere is a typical PYTHONPATH from a Windows system \u2212\n\nset PYTHONPATH = c:\\python20\\lib;\n\nAnd here is a typical PYTHONPATH from a UNIX system \u2212\n\nset PYTHONPATH = /usr/local/lib/python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ff17727ca122f1cb267195bd5911f4f8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).\nA Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.\nEach function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.\nPython makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.\nTherefore, in order to assign a value to a global variable within a function, you must first use the global statement.\nThe statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.\nFor example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.\n\n#!/usr/bin/python\n\nMoney = 2000\ndef AddMoney():\n # Uncomment the following line to fix the code:\n # global Money\n Money = Money + 1\n\nprint Money\nAddMoney()\nprint Money", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3efef7b3a83b3829e129652f6787b2b3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The dir() built-in function returns a sorted list of strings containing the names defined by a module.\nThe list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example \u2212\n\n#!/usr/bin/python\n\n# Import built-in module math\nimport math\n\ncontent = dir(math)\nprint content\n\nWhen the above code is executed, it produces the following result \u2212\n\n['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', \n'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', \n'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',\n'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', \n'sqrt', 'tan', 'tanh']\n\nHere, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b6d85540760d0a9f5db4e4a3d2a9a037", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.\nIf locals() is called from within a function, it will return all the names that can be accessed locally from that function.\nIf globals() is called from within a function, it will return all the names that can be accessed globally from that function.\nThe return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4ecb3de0d30beff619960bb4a0d1f3b5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When the module is imported into a script, the code in the top-level portion of a module is executed only once.\nTherefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this \u2212\n\nreload(module_name)\n\nHere, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following \u2212\n\nreload(hello)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "202b34d589fadee0d8908a7290c18b73", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.\nConsider a file Pots.py available in Phone directory. This file has following line of source code \u2212\n\n#!/usr/bin/python\n\ndef Pots():\n print \"I'm Pots Phone\"\n\nSimilar way, we have another two files having different functions with the same name as above \u2212\n\nPhone/Isdn.py file having function Isdn()\nPhone/G3.py file having function G3()\n\nNow, create one more file __init__.py in Phone directory \u2212\n\nPhone/__init__.py\n\nTo make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows \u2212\n\nfrom Pots import Pots\nfrom Isdn import Isdn\nfrom G3 import G3\n\nAfter you add these lines to __init__.py, you have all of these classes available when you import the Phone package.\n\n#!/usr/bin/python\n\n# Now import your Phone Package.\nimport Phone\n\nPhone.Pots()\nPhone.Isdn()\nPhone.G3()\n\nWhen the above code is executed, it produces the following result \u2212\n\nI'm Pots Phone\nI'm 3G Phone\nI'm ISDN Phone\n\nIn the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "24cfae812ecc2cebbeabc7ed5ba92161", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5b30f4babeeb2d880e806b9bdca53286", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows \u2212\n\n#!/usr/bin/python\n\nprint \"Python is really a great language,\", \"isn't it?\"\n\nThis produces the following result on your standard screen \u2212\n\nPython is really a great language, isn't it?", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0c3202036d32d4516b89abc96af19867", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are \u2212\n\nraw_input\ninput", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2a5d05a0bb8a9ddd8dc332e6e549bf51", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).\n\n#!/usr/bin/python\n\nstr = raw_input(\"Enter your input: \")\nprint \"Received input is : \", str\n\nThis prompts you to enter any string and it would display same string on the screen. When I typed \"Hello Python!\", its output is like this \u2212\n\nEnter your input: Hello Python\nReceived input is : Hello Python", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a4253f0cebb41b86b53a9c43eda5d1f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.\n\n#!/usr/bin/python\n\nstr = input(\"Enter your input: \")\nprint \"Received input is : \", str\n\nThis would produce the following result against the entered input \u2212\n\nEnter your input: [x*5 for x in range(2,10,2)]\nRecieved input is : [10, 20, 30, 40]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68d7d16f29f78641991cd19a76f0ffd7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.\nPython provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2add783cb1fdd971b67a870a42a40dfb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d8ec515bf7f8a0524aec158b910e8c4e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "file object = open(file_name [, access_mode][, buffering])\n\nHere are parameter details \u2212\n\nfile_name \u2212 The file_name argument is a string value that contains the name of the file that you want to access.\naccess_mode \u2212 The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).\nbuffering \u2212 If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).\n\nHere is a list of the different modes of opening a file \u2212\n\n\nSr.No.\nModes & Description\n\n\n1\nr\nOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.\n\n\n2\nrb\nOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.\n\n\n3\nr+\nOpens a file for both reading and writing. The file pointer placed at the beginning of the file.\n\n\n4\nrb+\nOpens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.\n\n\n5\nw\nOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.\n\n\n6\nwb\nOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.\n\n\n7\nw+\nOpens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.\n\n\n8\nwb+\nOpens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.\n\n\n9\na\nOp", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "08f913677964ca443688eade68b64b5f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "ens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.\n\n\n10\nab\nOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.\n\n\n11\na+\nOpens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.\n\n\n12\nab+\nOpens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "30caef452e3749415688ba6532c51d43", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once a file is opened and you have one file object, you can get various information related to that file.\nHere is a list of all attributes related to file object \u2212\n\n\nSr.No.\nAttribute & Description\n\n\n1\nfile.closed\nReturns true if file is closed, false otherwise.\n\n\n2\nfile.mode\nReturns access mode with which file was opened.\n\n\n3\nfile.name\nReturns name of the file.\n\n\n4\nfile.softspace\nReturns false if space explicitly required with print, true otherwise.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4c9c18399f7f54931fc9f374a5e20175", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\nprint \"Closed or not : \", fo.closed\nprint \"Opening mode : \", fo.mode\nprint \"Softspace flag : \", fo.softspace\n\nThis produces the following result \u2212\n\nName of the file: foo.txt\nClosed or not : False\nOpening mode : wb\nSoftspace flag : 0", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1bc9d529163af497dbdd4864a59eac4b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.\nPython automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a47d4620126c2ff8db0383b2195b50de", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0744e7b2f34ca69b63862a8686bd50d4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\n\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nName of the file: foo.txt", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "80d71633967f5d2f2f626b85028bacff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "51129430b292fc1b8db3b43181de2198", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.\nThe write() method does not add a newline character ('\\n') to the end of the string \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "40d9cdda433c20acada7700b5c9cc18f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.write(string)\n\nHere, passed parameter is the content to be written into the opened file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7f4fbcb2059b44ccbb0e5f07c6a35719", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nfo.write( \"Python is a great language.\\nYeah its great!!\\n\")\n\n# Close opend file\nfo.close()\n\nThe above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.\n\nPython is a great language.\nYeah its great!!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e8f070814309dbc323f3c924a383ff7e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6aafee8ad1aa0fc0beb5b0c7efb92193", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "fileObject.read([count])\n\nHere, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "285b5a4da8664e0e62e528a30774522f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let's take a file foo.txt, which we created above.\n\n#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10);\nprint \"Read String is : \", str\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nRead String is : Python is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e14a76a6455de437378c580a7f9386e7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.\nThe seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.\nIf from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8ec1d4b67055813c745d5a595a8ab9d3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us take a file foo.txt, which we created above.\n\n#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"r+\")\nstr = fo.read(10)\nprint \"Read String is : \", str\n\n# Check current position\nposition = fo.tell()\nprint \"Current file position : \", position\n\n# Reposition pointer at the beginning once again\nposition = fo.seek(0, 0);\nstr = fo.read(10)\nprint \"Again read String is : \", str\n# Close opend file\nfo.close()\n\nThis produces the following result \u2212\n\nRead String is : Python is\nCurrent file position : 10\nAgain read String is : Python is", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2957fc46a62c6679751dee4be316622a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.\nTo use this module you need to import it first and then you can call any related functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "15db43df152789b40b7c2e68d76fe13c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The rename() method takes two arguments, the current filename and the new filename.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dc6c1d9a300bd8dba6a6f20a4420f792", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.rename(current_file_name, new_file_name)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8e04b1409cbe918e38b5b9c722574aa6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to rename an existing file test1.txt \u2212\n\n#!/usr/bin/python\nimport os\n\n# Rename a file from test1.txt to test2.txt\nos.rename( \"test1.txt\", \"test2.txt\" )", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bbbdb04692a39aace44ba331710c4cc0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b336209c495dfd346a6619a7d27f0d3a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.remove(file_name)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d164b1c5c3d1aab83fdf597da5dda167", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to delete an existing file test2.txt \u2212\n\n#!/usr/bin/python\nimport os\n\n# Delete file test2.txt\nos.remove(\"text2.txt\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0585bd91577ebf9f412037d2903b6367", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cf27a0bb86fe47f6d2d18daf6f4efe8e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6d24f3e5f8312b846d9a38051a128539", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.mkdir(\"newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cb8a8dbb890175d4ee15f0e957e471ca", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to create a directory test in the current directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# Create a directory \"test\"\nos.mkdir(\"test\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b05392c20911b9e9810a1936a5614b5d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "839caf493eaf14bf5d50dbbc11a011b8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.chdir(\"newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "06a7f4d875e15b79bccc1f464fca65be", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to go into \"/home/newdir\" directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# Changing a directory to \"/home/newdir\"\nos.chdir(\"/home/newdir\")", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2a6b22b27dbeead0cd03eae6ec57d84f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The getcwd() method displays the current working directory.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e768514cb6b0733774c449085e0a4d7b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.getcwd()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dd4c605edfc2befaa92b2b498e2ab27a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to give current directory \u2212\n\n#!/usr/bin/python\nimport os\n\n# This would give location of the current directory\nos.getcwd()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1a7c4d14b36eebed50e1e747ed9a968b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The rmdir() method deletes the directory, which is passed as an argument in the method.\nBefore removing a directory, all the contents in it should be removed.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c5df7683c83b5d8d8de7f9185a4859b4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "os.rmdir('dirname')", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dbf8e19975179db3df88119c922de23e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to remove \"/tmp/test\" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.\n\n#!/usr/bin/python\nimport os\n\n# This would remove \"/tmp/test\" directory.\nos.rmdir( \"/tmp/test\" )", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "52ddbc5a23bf11a4b308916845784c1c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows \u2212\n\nFile Object Methods: The file object provides functions to manipulate files.\nOS Object Methods: This provides methods to process files as well as directories.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b0be61ab69344969f44710207e0dac85", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them \u2212\n\nException Handling \u2212 This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions.\nAssertions \u2212 This would be covered in Assertions in Python tutorial.\n\nList of Standard Exceptions \u2212\n\n\nSr.No.\nException Name & Description\n\n\n1\nException\nBase class for all exceptions\n\n\n2\nStopIteration\nRaised when the next() method of an iterator does not point to any object.\n\n\n3\nSystemExit\nRaised by the sys.exit() function.\n\n\n4\nStandardError\nBase class for all built-in exceptions except StopIteration and SystemExit.\n\n\n5\nArithmeticError\nBase class for all errors that occur for numeric calculation.\n\n\n6\nOverflowError\nRaised when a calculation exceeds maximum limit for a numeric type.\n\n\n7\nFloatingPointError\nRaised when a floating point calculation fails.\n\n\n8\nZeroDivisionError\nRaised when division or modulo by zero takes place for all numeric types.\n\n\n9\nAssertionError\nRaised in case of failure of the Assert statement.\n\n\n10\nAttributeError\nRaised in case of failure of attribute reference or assignment.\n\n\n11\nEOFError\nRaised when there is no input from either the raw_input() or input() function and the end of file is reached.\n\n\n12\nImportError\nRaised when an import statement fails.\n\n\n13\nKeyboardInterrupt\nRaised when the user interrupts program execution, usually by pressing Ctrl+c.\n\n\n14\nLookupError\nBase class for all lookup errors.\n\n\n15\nIndexError\nRaised when an index is not found in a sequence.\n\n\n16\nKeyError\nRaised when the specified key is not found in the dictionary.\n\n\n17\nNameError\nRaised when an identifier is not found in the local or global namespace.\n\n\n18\nUnboundLocalError\nRaised when trying to access a local variable in a function or method but no value has been assigned to it.\n\n\n19\nEnvironmentError\nBase class for all exceptions that occur outside the Python environment.\n\n\n20\nIOError\nRaised when an input/ output operation fails, such as the", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "98c8d5e964f246e42493f8a1fc32d5a0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": " print statement or the open() function when trying to open a file that does not exist.\n\n\n21\nIOError\nRaised for operating system-related errors.\n\n\n22\nSyntaxError\nRaised when there is an error in Python syntax.\n\n\n23\nIndentationError\nRaised when indentation is not specified properly.\n\n\n24\nSystemError\nRaised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.\n\n\n25\nSystemExit\nRaised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.\n\n\n26\nTypeError\nRaised when an operation or function is attempted that is invalid for the specified data type.\n\n\n27\nValueError\nRaised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.\n\n\n28\nRuntimeError\nRaised when a generated error does not fall into any category.\n\n\n29\nNotImplementedError\nRaised when an abstract method that needs to be implemented in an inherited class is not actually implemented.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fab5008d225391879c73c7d3ad4b4fb2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.\nThe easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.\nAssertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.\nProgrammers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ae3f72462ad08be6669acc2ac40ae574", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.\nThe syntax for assert is \u2212\n\nassert Expression[, Arguments]\n\nIf the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "72e7cb01dfbb00eb70164e229df68fc5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature \u2212\n\n#!/usr/bin/python\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\nprint KelvinToFahrenheit(273)\nprint int(KelvinToFahrenheit(505.78))\nprint KelvinToFahrenheit(-5)\n\nWhen the above code is executed, it produces the following result \u2212\n\n32.0\n451\nTraceback (most recent call last):\nFile \"test.py\", line 9, in <module>\nprint KelvinToFahrenheit(-5)\nFile \"test.py\", line 4, in KelvinToFahrenheit\nassert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a2fdd8de03ebc53b02c35664b6964d6d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.\nWhen a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4a0caaf88a9fa36cfbdf47d7a39e12ef", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "36951a47140f60428aca2482bf7a6079", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is simple syntax of try....except...else blocks \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept ExceptionI:\n If there is ExceptionI, then execute this block.\nexcept ExceptionII:\n If there is ExceptionII, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n\nHere are few important points about the above-mentioned syntax \u2212\n\nA single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.\nYou can also provide a generic except clause, which handles any exception.\nAfter the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.\nThe else-block is a good place for code that does not need the try: block's protection.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d19cad5cff24f3e6509ab51251532bda", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"\n fh.close()\n\nThis produces the following result \u2212\n\nWritten content in the file successfully", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "90d739cd03ff0636952a9851c15477c6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example tries to open a file where you do not have write permission, so it raises an exception \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"r\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"\n\nThis produces the following result \u2212\n\nError: can't find file or read data", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8f2fd41463cea54026ebf86a96d26619", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can also use the except statement with no exceptions defined as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept:\n If there is any exception, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n\nThis kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fe8af57c8453316ae082cc68a31b6e88", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can also use the same except statement to handle multiple exceptions as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept(Exception1[, Exception2[,...ExceptionN]]]):\n If there is any exception from the given exception list, \n then execute this block.\n ......................\nelse:\n If there is no exception then execute this block.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a6033bd1d83b981955e6a9074b17f21e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block\nraised an exception or not. The syntax of the try-finally statement is this \u2212\n\ntry:\n You do your operations here;\n ......................\n Due to any exception, this may be skipped.\nfinally:\n This would always be executed.\n ......................\n\nYou cannot use else clause as well along with a finally clause.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "754f6bbe0718b1bbc0c40c1acbb8c1ee", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nfinally:\n print \"Error: can\\'t find file or read data\"\n\nIf you do not have permission to open the file in writing mode, then this will produce the following result \u2212\n\nError: can't find file or read data\n\nSame example can be written more cleanly as follows \u2212\n\n#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n try:\n fh.write(\"This is my test file for exception handling!!\")\n finally:\n print \"Going to close the file\"\n fh.close()\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\n\nWhen an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "df20753143163bbdd0cb21e5b3e41a93", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows \u2212\n\ntry:\n You do your operations here;\n ......................\nexcept ExceptionType, Argument:\n You can print value of Argument here...\n\nIf you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.\nThis variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cf09f1456f689443223773bf7b8b21f5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is an example for a single exception \u2212\n\n#!/usr/bin/python\n\n# Define a function here.\ndef temp_convert(var):\n try:\n return int(var)\n except ValueError, Argument:\n print \"The argument does not contain numbers\\n\", Argument\n\n# Call above function here.\ntemp_convert(\"xyz\");\n\nThis produces the following result \u2212\n\nThe argument does not contain numbers\ninvalid literal for int() with base 10: 'xyz'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c12c7778e489988a71555cf86b211cc1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8f528534fc78c8e2c1380345bcc47db7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "raise [Exception [, args [, traceback]]]\n\nHere, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.\nThe final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "27e99eb324f821ec01f92b68f32035a5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows \u2212\n\ndef functionName( level ):\n if level < 1:\n raise \"Invalid level!\", level\n # The code below to this would not be executed\n # if we raise the exception\n\nNote: In order to catch an exception, an \"except\" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows \u2212\n\ntry:\n Business Logic here...\nexcept \"Invalid level!\":\n Exception handling here...\nelse:\n Rest of the code here...", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9fdf8860d9621d2b520dfe76b5bb1e5f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.\nHere is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.\nIn the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.\n\nclass Networkerror(RuntimeError):\n def __init__(self, arg):\n self.args = arg\n\nSo once you defined above class, you can raise the exception as follows \u2212\n\ntry:\n raise Networkerror(\"Bad hostname\")\nexcept Networkerror,e:\n print e.args", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "951d1a4ff1c1ca3fae94e755750f1e49", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.\nIf you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.\nHowever, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8ca0bfb7a1cafe1dbcbbb990510c3fc4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Class \u2212 A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.\nClass variable \u2212 A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.\nData member \u2212 A class variable or instance variable that holds data associated with a class and its objects.\nFunction overloading \u2212 The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.\nInstance variable \u2212 A variable that is defined inside a method and belongs only to the current instance of a class.\nInheritance \u2212 The transfer of the characteristics of a class to other classes that are derived from it.\nInstance \u2212 An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.\nInstantiation \u2212 The creation of an instance of a class.\nMethod \u2212 A special kind of function that is defined in a class definition.\nObject \u2212 A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.\nOperator overloading \u2212 The assignment of more than one function to a particular operator.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "23706ed490e60d3eb5b7519a25bfe1f5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows \u2212\n\nclass ClassName:\n 'Optional class documentation string'\n class_suite\n\n\nThe class has a documentation string, which can be accessed via ClassName.__doc__.\nThe class_suite consists of all the component statements defining class members, data attributes and functions.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a72849fbd9a5487847b9f5f032e94826", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example of a simple Python class \u2212\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\n\nThe variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.\nThe first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.\nYou declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2c1886e94c9490e8503ba3172246aa8f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.\n\n\"This would create first object of Employee class\"\nemp1 = Employee(\"Zara\", 2000)\n\"This would create second object of Employee class\"\nemp2 = Employee(\"Manni\", 5000)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7ed4aed69c4e36690d6ccbc777294f28", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows \u2212\n\nemp1.displayEmployee()\nemp2.displayEmployee()\nprint \"Total Employee %d\" % Employee.empCount\n\nNow, putting all the concepts together \u2212\n\n#!/usr/bin/python\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\n\"This would create first object of Employee class\"\nemp1 = Employee(\"Zara\", 2000)\n\"This would create second object of Employee class\"\nemp2 = Employee(\"Manni\", 5000)\nemp1.displayEmployee()\nemp2.displayEmployee()\nprint \"Total Employee %d\" % Employee.empCount\n\nWhen the above code is executed, it produces the following result \u2212\n\nName : Zara ,Salary: 2000\nName : Manni ,Salary: 5000\nTotal Employee 2\n\nYou can add, remove, or modify attributes of classes and objects at any time \u2212\n\nemp1.age = 7 # Add an 'age' attribute.\nemp1.age = 8 # Modify 'age' attribute.\ndel emp1.age # Delete 'age' attribute.\n\nInstead of using the normal statements to access attributes, you can use the following functions \u2212\n\nThe getattr(obj, name[, default]) \u2212 to access the attribute of object.\nThe hasattr(obj,name) \u2212 to check if an attribute exists or not.\nThe setattr(obj,name,value) \u2212 to set an attribute. If attribute does not exist, then it would be created.\nThe delattr(obj, name) \u2212 to delete an attribute.\n\n\nhasattr(emp1, 'age') # Returns true if 'age' attribute exists\ngetattr(emp1, 'age') # Returns value of 'age' attribute\nsetattr(emp1, 'age', 8) # Set attribute 'age' at 8\ndelattr(empl, 'age') # Delete attribute 'age'", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cf6929ab6228dc63d6e7f7f31c6b4ef8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute \u2212\n\n__dict__ \u2212 Dictionary containing the class's namespace.\n__doc__ \u2212 Class documentation string or none, if undefined. \n__name__ \u2212 Class name.\n__module__ \u2212 Module name in which the class is defined. This attribute is \"__main__\" in interactive mode. \n__bases__ \u2212 A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.\n\nFor the above class let us try to access all these attributes \u2212\n\n#!/usr/bin/python\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0\n\n def __init__(self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n \n def displayCount(self):\n print \"Total Employee %d\" % Employee.empCount\n\n def displayEmployee(self):\n print \"Name : \", self.name, \", Salary: \", self.salary\n\nprint \"Employee.__doc__:\", Employee.__doc__\nprint \"Employee.__name__:\", Employee.__name__\nprint \"Employee.__module__:\", Employee.__module__\nprint \"Employee.__bases__:\", Employee.__bases__\nprint \"Employee.__dict__:\", Employee.__dict__\n\nWhen the above code is executed, it produces the following result \u2212\n\nEmployee.__doc__: Common base class for all employees\nEmployee.__name__: Employee\nEmployee.__module__: __main__\nEmployee.__bases__: ()\nEmployee.__dict__: {'__module__': '__main__', 'displayCount':\n<function displayCount at 0xb7c84994>, 'empCount': 2, \n'displayEmployee': <function displayEmployee at 0xb7c8441c>, \n'__doc__': 'Common base class for all employees', \n'__init__': <function __init__ at 0xb7c846bc>}", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "618adb6303139802634d9f01f78f1d43", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.\nPython's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.\nAn object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.\n\na = 40 # Create object <40>\nb = a # Increase ref. count of <40> \nc = [b] # Increase ref. count of <40> \n\ndel a # Decrease ref. count of <40>\nb = 100 # Decrease ref. count of <40> \nc[0] = -1 # Decrease ref. count of <40> \n\nYou normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fd477911a643df6f7e6c25082e7deae2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This __del__() destructor prints the class name of an instance that is about to be destroyed \u2212\n\n#!/usr/bin/python\n\nclass Point:\n def __init__( self, x=0, y=0):\n self.x = x\n self.y = y\n def __del__(self):\n class_name = self.__class__.__name__\n print class_name, \"destroyed\"\n\npt1 = Point()\npt2 = pt1\npt3 = pt1\nprint id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts\ndel pt1\ndel pt2\ndel pt3\n\nWhen the above code is executed, it produces following result \u2212\n\n3083401324 3083401324 3083401324\nPoint destroyed\n\nNote \u2212 Ideally, you should define your classes in separate file, then you should import them in your main program file using import statement.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68801b1319968d2534f752a27e493235", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.\nThe child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "46509a56011417a691454eed7ba29ccc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name \u2212\n\nclass SubClassName (ParentClass1[, ParentClass2, ...]):\n 'Optional class documentation string'\n class_suite", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0bda6229337f619a8f10969485e28496", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Parent: # define parent class\n parentAttr = 100\n def __init__(self):\n print \"Calling parent constructor\"\n\n def parentMethod(self):\n print 'Calling parent method'\n\n def setAttr(self, attr):\n Parent.parentAttr = attr\n\n def getAttr(self):\n print \"Parent attribute :\", Parent.parentAttr\n\nclass Child(Parent): # define child class\n def __init__(self):\n print \"Calling child constructor\"\n\n def childMethod(self):\n print 'Calling child method'\n\nc = Child() # instance of child\nc.childMethod() # child calls its method\nc.parentMethod() # calls parent's method\nc.setAttr(200) # again call parent's method\nc.getAttr() # again call parent's method\n\nWhen the above code is executed, it produces the following result \u2212\n\nCalling child constructor\nCalling child method\nCalling parent method\nParent attribute : 200\n\nSimilar way, you can drive a class from multiple parent classes as follows \u2212\n\nclass A: # define your class A\n.....\n\nclass B: # define your class B\n.....\n\nclass C(A, B): # subclass of A and B\n.....\n\nYou can use issubclass() or isinstance() functions to check a relationships of two classes and instances.\n\nThe issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.\nThe isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4219e63ba63bd7b9d22e01485b4b3d30", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cdfbdfe134eabab80d35b752b29dad15", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Parent: # define parent class\n def myMethod(self):\n print 'Calling parent method'\n\nclass Child(Parent): # define child class\n def myMethod(self):\n print 'Calling child method'\n\nc = Child() # instance of child\nc.myMethod() # child calls overridden method\n\nWhen the above code is executed, it produces the following result \u2212\n\nCalling child method", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "051ab1101dc9f20ee25a8c99e284dc70", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following table lists some generic functionality that you can override in your own classes \u2212\n\n\nSr.No.\nMethod, Description & Sample Call\n\n\n1\n__init__ ( self [,args...] )\nConstructor (with any optional arguments)\nSample Call : obj = className(args)\n\n\n2\n__del__( self )\nDestructor, deletes an object\nSample Call : del obj\n\n\n3\n__repr__( self )\nEvaluable string representation\nSample Call : repr(obj)\n\n\n4\n__str__( self )\nPrintable string representation\nSample Call : str(obj)\n\n\n5\n__cmp__ ( self, x )\nObject comparison\nSample Call : cmp(obj, x)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1e35a2b1fd4e9d36b0d2d218f7f74c44", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.\nYou could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "db238cff54373a08f5392bc5d6fab49d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass Vector:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def __str__(self):\n return 'Vector (%d, %d)' % (self.a, self.b)\n \n def __add__(self,other):\n return Vector(self.a + other.a, self.b + other.b)\n\nv1 = Vector(2,10)\nv2 = Vector(5,-2)\nprint v1 + v2\n\nWhen the above code is executed, it produces the following result \u2212\n\nVector(7,8)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f3927e7341f02b77b8fd065ed8957be9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a739080b06aec75aa736b4a378378b41", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nclass JustCounter:\n __secretCount = 0\n \n def count(self):\n self.__secretCount += 1\n print self.__secretCount\n\ncounter = JustCounter()\ncounter.count()\ncounter.count()\nprint counter.__secretCount\n\nWhen the above code is executed, it produces the following result \u2212\n\n1\n2\nTraceback (most recent call last):\n File \"test.py\", line 12, in <module>\n print counter.__secretCount\nAttributeError: JustCounter instance has no attribute '__secretCount'\n\nPython protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you \u2212\n\n.........................\nprint counter._JustCounter__secretCount\n\nWhen the above code is executed, it produces the following result \u2212\n\n1\n2\n2", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1e191321ebd7dfe6fd7975b905ec5714", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.\nThe module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or\nusing a regular expression.\nWe would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5c7aa8523480970e9d8f0497748313cf", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This function attempts to match RE pattern to string with optional flags.\nHere is the syntax for this function \u2212\n\nre.match(pattern, string, flags=0)\n\nHere is the description of the parameters \u2212\n\n\nSr.No.\nParameter & Description\n\n\n1\npattern\nThis is the regular expression to be matched.\n\n\n2\nstring\nThis is the string, which would be searched to match the pattern at the beginning of string.\n\n\n3\nflags\nYou can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.\n\n\nThe re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.\n\n\nSr.No.\nMatch Object Method & Description\n\n\n1\ngroup(num=0)\nThis method returns entire match (or specific subgroup num)\n\n\n2\ngroups()\nThis method returns all matching subgroups in a tuple (empty if there weren't any)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "06b90e5cca0f5db680b6e5ce9d233bf1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\"\n\nmatchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)\n\nif matchObj:\n print \"matchObj.group() : \", matchObj.group()\n print \"matchObj.group(1) : \", matchObj.group(1)\n print \"matchObj.group(2) : \", matchObj.group(2)\nelse:\n print \"No match!!\"\n\nWhen the above code is executed, it produces following result \u2212\n\nmatchObj.group() : Cats are smarter than dogs\nmatchObj.group(1) : Cats\nmatchObj.group(2) : smarter", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5461009c1f7596302a3f64b3f87c1398", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This function searches for first occurrence of RE pattern within string with optional flags.\nHere is the syntax for this function \u2212\n\nre.search(pattern, string, flags=0)\n\nHere is the description of the parameters \u2212\n\n\nSr.No.\nParameter & Description\n\n\n1\npattern\nThis is the regular expression to be matched.\n\n\n2\nstring\nThis is the string, which would be searched to match the pattern anywhere in the string.\n\n\n3\nflags\nYou can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.\n\n\nThe re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression.\n\n\nSr.No.\nMatch Object Methods & Description\n\n\n1\ngroup(num=0)\nThis method returns entire match (or specific subgroup num)\n\n\n2\ngroups()\nThis method returns all matching subgroups in a tuple (empty if there weren't any)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "554e0304896776598c37351bf406b047", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\";\n\nsearchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)\n\nif searchObj:\n print \"searchObj.group() : \", searchObj.group()\n print \"searchObj.group(1) : \", searchObj.group(1)\n print \"searchObj.group(2) : \", searchObj.group(2)\nelse:\n print \"Nothing found!!\"\n\nWhen the above code is executed, it produces following result \u2212\n\nsearchObj.group() : Cats are smarter than dogs\nsearchObj.group(1) : Cats\nsearchObj.group(2) : smarter", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5dfbeaf888cb2cc2119885f793cd3c97", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "60779084fc80a5a4b18b23c51063f40e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nline = \"Cats are smarter than dogs\";\n\nmatchObj = re.match( r'dogs', line, re.M|re.I)\nif matchObj:\n print \"match --> matchObj.group() : \", matchObj.group()\nelse:\n print \"No match!!\"\n\nsearchObj = re.search( r'dogs', line, re.M|re.I)\nif searchObj:\n print \"search --> searchObj.group() : \", searchObj.group()\nelse:\n print \"Nothing found!!\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nNo match!!\nsearch --> searchObj.group() : dogs", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3b361f8eeca7e714ff8a8c873cdad252", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "One of the most important re methods that use regular expressions is sub.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "94eb1da87d6c4fe756ef461e4f7351ba", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "re.sub(pattern, repl, string, max=0)\n\nThis method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f3a74cb346e454573fde078c365db34d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport re\n\nphone = \"2004-959-559 # This is Phone Number\"\n\n# Delete Python-style comments\nnum = re.sub(r'#.*$', \"\", phone)\nprint \"Phone Num : \", num\n\n# Remove anything other than digits\nnum = re.sub(r'\\D', \"\", phone) \nprint \"Phone Num : \", num\n\nWhen the above code is executed, it produces the following result \u2212\n\nPhone Num : 2004-959-559\nPhone Num : 2004959559", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "36d72193530f625c0a8916b9e5ae715e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these \u2212\n\n\nSr.No.\nModifier & Description\n\n\n1\nre.I\nPerforms case-insensitive matching.\n\n\n2\nre.L\nInterprets words according to the current locale. This interpretation affects the alphabetic group (\\w and \\W), as well as word boundary behavior(\\b and \\B).\n\n\n3\nre.M\nMakes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).\n\n\n4\nre.S\nMakes a period (dot) match any character, including a newline.\n\n\n5\nre.U\nInterprets letters according to the Unicode character set. This flag affects the behavior of \\w, \\W, \\b, \\B.\n\n\n6\nre.X\nPermits \"cuter\" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6aa21a6175f262d35dfff655ceedcb87", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \\), all characters match themselves. You can escape a control character by preceding it with a backslash.\nFollowing table lists the regular expression syntax that is available in Python \u2212\n\n\nSr.No.\nPattern & Description\n\n\n1\n^\nMatches beginning of line.\n\n\n2\n$\nMatches end of line.\n\n\n3\n.\nMatches any single character except newline. Using m option allows it to match newline as well.\n\n\n4\n[...]\nMatches any single character in brackets.\n\n\n5\n[^...]\nMatches any single character not in brackets\n\n\n6\nre*\nMatches 0 or more occurrences of preceding expression.\n\n\n7\nre+\nMatches 1 or more occurrence of preceding expression.\n\n\n8\nre?\nMatches 0 or 1 occurrence of preceding expression.\n\n\n9\nre{ n}\nMatches exactly n number of occurrences of preceding expression.\n\n\n10\nre{ n,}\nMatches n or more occurrences of preceding expression.\n\n\n11\nre{ n, m}\nMatches at least n and at most m occurrences of preceding expression.\n\n\n12\na| b\nMatches either a or b.\n\n\n13\n(re)\nGroups regular expressions and remembers matched text.\n\n\n14\n(?imx)\nTemporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.\n\n\n15\n(?-imx)\nTemporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.\n\n\n16\n(?: re)\nGroups regular expressions without remembering matched text.\n\n\n17\n(?imx: re)\nTemporarily toggles on i, m, or x options within parentheses.\n\n\n18\n(?-imx: re)\nTemporarily toggles off i, m, or x options within parentheses.\n\n\n19\n(?#...)\nComment.\n\n\n20\n(?= re)\nSpecifies position using a pattern. Doesn't have a range.\n\n\n21\n(?! re)\nSpecifies position using pattern negation. Doesn't have a range.\n\n\n22\n(?> re)\nMatches independent pattern without backtracking.\n\n\n23\n\\w\nMatches word characters.\n\n\n24\n\\W\nMatches nonword characters.\n\n\n25\n\\s\nMatches whitespace. Equivalent to [\\t\\n\\r\\f].\n\n\n26\n\\S\nMatches nonwhitespace.\n\n\n27\n\\d\nMatches digits. Equivalent to [0-9].\n\n\n28\n\\D\nMatches nondigits.\n\n\n29\n\\A\nMatches beginning of string.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dec631a415cdb36cc84f6a19e6900f4f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "\n\n\n30\n\\Z\nMatches end of string. If a newline exists, it matches just before newline.\n\n\n31\n\\z\nMatches end of string.\n\n\n32\n\\G\nMatches point where last match finished.\n\n\n33\n\\b\nMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.\n\n\n34\n\\B\nMatches nonword boundaries.\n\n\n35\n\\n, \\t, etc.\nMatches newlines, carriage returns, tabs, etc.\n\n\n36\n\\1...\\9\nMatches nth grouped subexpression.\n\n\n37\n\\10\nMatches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "efb9ad66ef6210585c9a49cad3d179cc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\npython\nMatch \"python\".", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2534db2af54422e6de442b606009bb83", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n[Pp]ython\nMatch \"Python\" or \"python\"\n\n\n2\nrub[ye]\nMatch \"ruby\" or \"rube\"\n\n\n3\n[aeiou]\nMatch any one lowercase vowel\n\n\n4\n[0-9]\nMatch any digit; same as [0123456789]\n\n\n5\n[a-z]\nMatch any lowercase ASCII letter\n\n\n6\n[A-Z]\nMatch any uppercase ASCII letter\n\n\n7\n[a-zA-Z0-9]\nMatch any of the above\n\n\n8\n[^aeiou]\nMatch anything other than a lowercase vowel\n\n\n9\n[^0-9]\nMatch anything other than a digit", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6a00ac6854d48c924f49b4d290076e3a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n.\nMatch any character except newline\n\n\n2\n\\d\nMatch a digit: [0-9]\n\n\n3\n\\D\nMatch a nondigit: [^0-9]\n\n\n4\n\\s\nMatch a whitespace character: [ \\t\\r\\n\\f]\n\n\n5\n\\S\nMatch nonwhitespace: [^ \\t\\r\\n\\f]\n\n\n6\n\\w\nMatch a single word character: [A-Za-z0-9_]\n\n\n7\n\\W\nMatch a nonword character: [^A-Za-z0-9_]", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a180bb1673997987071a98b828d87bbd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\nruby?\nMatch \"rub\" or \"ruby\": the y is optional\n\n\n2\nruby*\nMatch \"rub\" plus 0 or more ys\n\n\n3\nruby+\nMatch \"rub\" plus 1 or more ys\n\n\n4\n\\d{3}\nMatch exactly 3 digits\n\n\n5\n\\d{3,}\nMatch 3 or more digits\n\n\n6\n\\d{3,5}\nMatch 3, 4, or 5 digits", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "55456ede7cb6b6da651c02140a912c8c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This matches the smallest number of repetitions \u2212\n\n\nSr.No.\nExample & Description\n\n\n1\n<.*>\nGreedy repetition: matches \"<python>perl>\"\n\n\n2\n<.*?>\nNongreedy: matches \"<python>\" in \"<python>perl>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d5b3ca4a11147a9a83173e2bcad1880e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\n\\D\\d+\nNo group: + repeats \\d\n\n\n2\n(\\D\\d)+\nGrouped: + repeats \\D\\d pair\n\n\n3\n([Pp]ython(, )?)+\nMatch \"Python\", \"Python, python, python\", etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7606a4e0aeb70829aa9b5af43c1f73bb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This matches a previously matched group again \u2212\n\n\nSr.No.\nExample & Description\n\n\n1\n([Pp])ython&\\1ails\nMatch python&pails or Python&Pails\n\n\n2\n(['\"])[^\\1]*\\1\nSingle or double-quoted string. \\1 matches whatever the 1st group matched. \\2 matches whatever the 2nd group matched, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1e8e65d2b368bd01a33e1e8f70bb908d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\npython|perl\nMatch \"python\" or \"perl\"\n\n\n2\nrub(y|le))\nMatch \"ruby\" or \"ruble\"\n\n\n3\nPython(!+|\\?)\n\"Python\" followed by one or more ! or one ?", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6e7a0f220c1221e3aa3345eab6f3542f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This needs to specify match position.\n\n\nSr.No.\nExample & Description\n\n\n1\n^Python\nMatch \"Python\" at the start of a string or internal line\n\n\n2\nPython$\nMatch \"Python\" at the end of a string or line\n\n\n3\n\\APython\nMatch \"Python\" at the start of a string\n\n\n4\nPython\\Z\nMatch \"Python\" at the end of a string\n\n\n5\n\\bPython\\b\nMatch \"Python\" at a word boundary\n\n\n6\n\\brub\\B\n\\B is nonword boundary: match \"rub\" in \"rube\" and \"ruby\" but not alone\n\n\n7\nPython(?=!)\nMatch \"Python\", if followed by an exclamation point.\n\n\n8\nPython(?!!)\nMatch \"Python\", if not followed by an exclamation point.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bd4b98c7e6a5f1deb257d3f1b593c04f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nExample & Description\n\n\n1\nR(?#comment)\nMatches \"R\". All the rest is a comment\n\n\n2\nR(?i)uby\nCase-insensitive while matching \"uby\"\n\n\n3\nR(?i:uby)\nSame as above\n\n\n4\nrub(?:y|le))\nGroup only without creating \\1 backreference", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "01c756eef485edf874754c275d5ac913", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c92ee60f313419ded36f41b61770f125", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.\nThe current version is CGI/1.1 and CGI/1.2 is under progress.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1674c8c030987831067d0ceb0753f72d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.\n\nYour browser contacts the HTTP web server and demands for the URL, i.e., filename.\nWeb Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.\nWeb browser takes response from web server and displays either the received file or error message.\n\nHowever, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fb7e148c2e3a2c42bd04f80bc96e4eb3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well.\nBy default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file \u2212\n\n<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n\n<Directory \"/var/www/cgi-bin\">\nOptions All\n</Directory>\n\nHere, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eafc9f2896b0d35aa9ab7774ab10c091", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.\n\n#!/usr/bin/python\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint '<html>'\nprint '<head>'\nprint '<title>Hello World - First CGI Program</title>'\nprint '</head>'\nprint '<body>'\nprint '<h2>Hello World! This is my first CGI program</h2>'\nprint '</body>'\nprint '</html>'\n\nIf you click hello.py, then this produces the following output \u2212\n\n\n\nHello World! This is my first CGI program\n\n\n\nThis hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\\r\\n\\r\\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen.\nBy now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fbfd61fe7cbbb9aa333f39c6c9132e74", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The line Content-type:text/html\\r\\n\\r\\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form \u2212\n\nHTTP Field Name: Field Content\n\nFor Example\nContent-type: text/html\\r\\n\\r\\n\n\nThere are few other important HTTP headers, which you will use frequently in your CGI Programming.\n\n\nSr.No.\nHeader & Description\n\n\n1\nContent-type:\nA MIME string defining the format of the file being returned. Example is Content-type:text/html\n\n\n2\nExpires: Date\nThe date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.\n\n\n3\nLocation: URL\nThe URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.\n\n\n4\nLast-modified: Date\nThe date of last modification of the resource.\n\n\n5\nContent-length: N\nThe length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.\n\n\n6\nSet-Cookie: String\nSet the cookie passed through the string", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5007d9beafefbf52954fec2c9c8fb9ca", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program.\n\n\nSr.No.\nVariable Name & Description\n\n\n1\nCONTENT_TYPE\nThe data type of the content. Used when the client is sending attached content to the server. For example, file upload.\n\n\n2\nCONTENT_LENGTH\nThe length of the query information. It is available only for POST requests.\n\n\n3\nHTTP_COOKIE\nReturns the set cookies in the form of key & value pair.\n\n\n4\nHTTP_USER_AGENT\nThe User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser.\n\n\n5\nPATH_INFO\nThe path for the CGI script.\n\n\n6\nQUERY_STRING\nThe URL-encoded information that is sent with GET method request.\n\n\n7\nREMOTE_ADDR\nThe IP address of the remote host making the request. This is useful logging or for authentication.\n\n\n8\nREMOTE_HOST\nThe fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address.\n\n\n9\nREQUEST_METHOD\nThe method used to make the request. The most common methods are GET and POST.\n\n\n10\nSCRIPT_FILENAME\nThe full path to the CGI script.\n\n\n11\nSCRIPT_NAME\nThe name of the CGI script.\n\n\n12\nSERVER_NAME\nThe server's hostname or IP Address\n\n\n13\nSERVER_SOFTWARE\nThe name and version of the software the server is running.\n\n\nHere is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment\n\n#!/usr/bin/python\n\nimport os\n\nprint \"Content-type: text/html\\r\\n\\r\\n\";\nprint \"<font size=+1>Environment</font><\\br>\";\nfor param in os.environ.keys():\n print \"<b>%20s</b>: %s<\\br>\" % (param, os.environ[param])", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "192024536611520d9d814e91e02c6d96", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9386008ac1651df4c2df0d2bfd0e25a6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows \u2212\n\nhttp://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2\n\nThe GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.\nYou can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "aa34687a7aa8023007775b481686d3f8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple URL, which passes two values to hello_get.py program using GET method.\n/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI\nBelow is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"\n\nThis would generate the following result \u2212\n\n\n\nHello ZARA ALI", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a9c2611b476fe54fe7dbb3741ba94dd3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.\n\n<form action = \"/cgi-bin/hello_get.py\" method = \"get\">\nFirst Name: <input type = \"text\" name = \"first_name\"> <br />\n\nLast Name: <input type = \"text\" name = \"last_name\" />\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nHere is the actual output of the above form, you enter First and Last Name and then click submit button to see the result.\n\nFirst Name: \n\nLast Name:", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "821e96afd34d9d6db64d7519442764ed", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.\nBelow is same hello_get.py script which handles GET as well as POST method.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"\n\nLet us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.\n\n<form action = \"/cgi-bin/hello_get.py\" method = \"post\">\nFirst Name: <input type = \"text\" name = \"first_name\"><br />\nLast Name: <input type = \"text\" name = \"last_name\" />\n\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nHere is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.\n\nFirst Name: \n\nLast Name:", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7efd82f7f95db20c1ddaa0018ef25fa3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Checkboxes are used when more than one option is required to be selected.\nHere is example HTML code for a form with two checkboxes \u2212\n\n<form action = \"/cgi-bin/checkbox.cgi\" method = \"POST\" target = \"_blank\">\n<input type = \"checkbox\" name = \"maths\" value = \"on\" /> Maths\n<input type = \"checkbox\" name = \"physics\" value = \"on\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>\n\nThe result of this code is the following form \u2212\n\n Maths\n Physics\n\n\nBelow is checkbox.cgi script to handle input given by web browser for checkbox button.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('maths'):\n math_flag = \"ON\"\nelse:\n math_flag = \"OFF\"\n\nif form.getvalue('physics'):\n physics_flag = \"ON\"\nelse:\n physics_flag = \"OFF\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Checkbox - Third CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> CheckBox Maths is : %s</h2>\" % math_flag\nprint \"<h2> CheckBox Physics is : %s</h2>\" % physics_flag\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "84385713b56681693bba3e7a977060dc", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Radio Buttons are used when only one option is required to be selected.\nHere is example HTML code for a form with two radio buttons \u2212\n\n<form action = \"/cgi-bin/radiobutton.py\" method = \"post\" target = \"_blank\">\n<input type = \"radio\" name = \"subject\" value = \"maths\" /> Maths\n<input type = \"radio\" name = \"subject\" value = \"physics\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>\n\nThe result of this code is the following form \u2212\n\n Maths\n Physics\n\n\nBelow is radiobutton.py script to handle input given by web browser for radio button \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('subject'):\n subject = form.getvalue('subject')\nelse:\n subject = \"Not set\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Radio - Fourth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "eaf3bc19af2b2fd8c0199f3f928bd302", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program.\nHere is example HTML code for a form with a TEXTAREA box \u2212\n\n<form action = \"/cgi-bin/textarea.py\" method = \"post\" target = \"_blank\">\n<textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\nType your text here...\n</textarea>\n<input type = \"submit\" value = \"Submit\" />\n</form>\n\nThe result of this code is the following form \u2212\n\nType your text here...\n\n\nBelow is textarea.cgi script to handle input given by web browser \u2212\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\";\nprint \"<title>Text Area - Fifth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Entered Text Content is %s</h2>\" % text_content\nprint \"</body>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e7aad215a8e2fdff8586ce3dd80c5843", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Drop Down Box is used when we have many options available but only one or two will be selected.\nHere is example HTML code for a form with one drop down box \u2212\n\n<form action = \"/cgi-bin/dropdown.py\" method = \"post\" target = \"_blank\">\n<select name = \"dropdown\">\n<option value = \"Maths\" selected>Maths</option>\n<option value = \"Physics\">Physics</option>\n</select>\n<input type = \"submit\" value = \"Submit\"/>\n</form>\n\nThe result of this code is the following form \u2212\n\n\nMaths\nPhysics\n\n\n\nBelow is dropdown.py script to handle input given by web browser.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('dropdown'):\n subject = form.getvalue('dropdown')\nelse:\n subject = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Dropdown Box - Sixth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1557e8242f49cd3090332dd82c0610aa", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages?\nIn many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9eaf26e82cd6fdcce78456dd53219fca", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.\nCookies are a plain text data record of 5 variable-length fields \u2212\n\nExpires \u2212 The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.\nDomain \u2212 The domain name of your site.\nPath \u2212 The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.\nSecure \u2212 If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.\nName=Value \u2212 Cookies are set and retrieved in the form of key and value pairs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "708688d15243dd5996b10be4521a5220", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows \u2212\n\n#!/usr/bin/python\n\nprint \"Set-Cookie:UserID = XYZ;\\r\\n\"\nprint \"Set-Cookie:Password = XYZ123;\\r\\n\"\nprint \"Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT\";\\r\\n\"\nprint \"Set-Cookie:Domain = www.tutorialspoint.com;\\r\\n\"\nprint \"Set-Cookie:Path = /perl;\\n\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\n...........Rest of the HTML Content....\n\nFrom this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.\nIt is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2d60945998fecb2a1e7e05742ee1b36b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form \u2212\n\nkey1 = value1;key2 = value2;key3 = value3....\n\nHere is an example of how to retrieve cookies.\n\n#!/usr/bin/python\n\n# Import modules for CGI handling \nfrom os import environ\nimport cgi, cgitb\n\nif environ.has_key('HTTP_COOKIE'):\n for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):\n (key, value ) = split(cookie, '=');\n if key == \"UserID\":\n user_id = value\n\n if key == \"Password\":\n password = value\n\nprint \"User ID = %s\" % user_id\nprint \"Password = %s\" % password\n\nThis produces the following result for the cookies set by above script \u2212\n\nUser ID = XYZ\nPassword = XYZ123", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8b09ad9c1d8447a7ef10e35d7c6d0435", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a \"Browse\" button.\n\n<html>\n<body>\n <form enctype = \"multipart/form-data\" \n action = \"save_file.py\" method = \"post\">\n <p>File: <input type = \"file\" name = \"filename\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n </form>\n</body>\n</html>\n\nThe result of this code is the following form \u2212\n\nFile: \n\n\nAbove example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.\nHere is the script save_file.py to handle file upload \u2212\n\n#!/usr/bin/python\n\nimport cgi, os\nimport cgitb; cgitb.enable()\n\nform = cgi.FieldStorage()\n\n# Get filename here.\nfileitem = form['filename']\n\n# Test if the file was uploaded\nif fileitem.filename:\n # strip leading path from file name to avoid \n # directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('/tmp/' + fn, 'wb').write(fileitem.file.read())\n\n message = 'The file \"' + fn + '\" was uploaded successfully'\n \nelse:\n message = 'No file was uploaded'\n \nprint \"\"\"\\\nContent-Type: text/html\\n\n<html>\n<body>\n <p>%s</p>\n</body>\n</html>\n\"\"\" % (message,)\n\nIf you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.\n\nfn = os.path.basename(fileitem.filename.replace(\"\\\\\", \"/\" ))", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dd44081836128e73dceb8cb82eab2244", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sometimes, it is desired that you want to give option where a user can click a link and it will pop up a \"File Download\" dialogue box to the user instead of displaying actual content. This is very easy and can be achieved through HTTP header. This HTTP header is be different from the header mentioned in previous section.\nFor example, if you want make a FileName file downloadable from a given link, then its syntax is as follows \u2212\n\n#!/usr/bin/python\n\n# HTTP Header\nprint \"Content-Type:application/octet-stream; name = \\\"FileName\\\"\\r\\n\";\nprint \"Content-Disposition: attachment; filename = \\\"FileName\\\"\\r\\n\\n\";\n\n# Actual File Content will go here.\nfo = open(\"foo.txt\", \"rb\")\n\nstr = fo.read();\nprint str\n\n# Close opend file\nfo.close()\n\nHope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a0b8b5e44d2f92788ee0fe8f45e50503", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.\nYou can choose the right database for your application. Python Database API supports a wide range of database servers such as \u2212\n\nGadFly\nmSQL\nMySQL\nPostgreSQL\nMicrosoft SQL Server 2000\nInformix\nInterbase\nOracle\nSybase\n\nHere is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.\nThe DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This API includes the following \u2212\n\nImporting the API module.\nAcquiring a connection with the database.\nIssuing SQL statements and stored procedures.\nClosing the connection\n\nWe would learn all the concepts using MySQL, so let us talk about MySQLdb module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68814a6ba31d4cb4afb7d5424a2b0815", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8f1c80ce75577d0783ddf612662b2945", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\nIf it produces the following result, then it means MySQLdb module is not installed \u2212\n\nTraceback (most recent call last):\n File \"test.py\", line 3, in <module>\n import MySQLdb\nImportError: No module named MySQLdb\n\nTo install MySQLdb module, use the following command \u2212\n\nFor Ubuntu, use the following command -\n$ sudo apt-get install python-pip python-dev libmysqlclient-dev\nFor Fedora, use the following command -\n$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc\nFor Python command prompt, use the following command -\npip install MySQL-python\n\nNote \u2212 Make sure you have root privilege to install above module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f3f329723079afe533b4e5237b0b3b0a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before connecting to a MySQL database, make sure of the followings \u2212\n\nYou have created a database TESTDB.\nYou have created a table EMPLOYEE in TESTDB.\nThis table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.\nUser ID \"testuser\" and password \"test123\" are set to access TESTDB.\nPython module MySQLdb is installed properly on your machine.\nYou have gone through MySQL tutorial to understand MySQL Basics.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4f4d6c35d0c246bbe1320e4d18ab3aa7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example of connecting with MySQL database \"TESTDB\"\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"SELECT VERSION()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nprint \"Database version : %s \" % data\n\n# disconnect from server\ndb.close()\n\nWhile running this script, it is producing the following result in my Linux machine.\n\nDatabase version : 5.0.45\n\nIf a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are released.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "43f20256c1e2a0a3661673d51078e684", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "78c94995adbc53a873d8efb8d381aec1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us create Database table EMPLOYEE \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Drop table if it already exist using execute() method.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n# Create table as per requirement\nsql = \"\"\"CREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, \n SEX CHAR(1),\n INCOME FLOAT )\"\"\"\n\ncursor.execute(sql)\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b4c1dea6530bcdfdd7d3099a38a6bb5e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "It is required when you want to create your records into a database table.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "14738f1b862fa884bda4440d281a928e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following example, executes SQL INSERT statement to create a record into EMPLOYEE table \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n LAST_NAME, AGE, SEX, INCOME)\n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()\n\nAbove example can be written as follows to create SQL queries dynamically \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"INSERT INTO EMPLOYEE(FIRST_NAME, \\\n LAST_NAME, AGE, SEX, INCOME) \\\n VALUES ('%s', '%s', '%d', '%c', '%d' )\" % \\\n ('Mac', 'Mohan', 20, 'M', 2000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "c82d253fddd977a993443450fbec4795", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following code segment is another form of execution where you can pass parameters directly \u2212\n\n..................................\nuser_id = \"test123\"\npassword = \"password\"\n\ncon.execute('insert into Login values(\"%s\", \"%s\")' % \\\n (user_id, password))\n..................................", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "38e19b065a7e0b8d11e2bd461b07fcc8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "READ Operation on any database means to fetch some useful information from the database.\nOnce our database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.\n\nfetchone() \u2212 It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.\nfetchall() \u2212 It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves\nthe remaining rows from the result set.\nrowcount \u2212 This is a read-only attribute and returns the number of rows that were affected by an execute() method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e09208b6d9ca165a38661ed51160a45d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The following procedure queries all the records from EMPLOYEE table having salary more than 1000 \u2212\n\n#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\nsql = \"SELECT * FROM EMPLOYEE \\\n WHERE INCOME > '%d'\" % (1000)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Fetch all the rows in a list of lists.\n results = cursor.fetchall()\n for row in results:\n fname = row[0]\n lname = row[1]\n age = row[2]\n sex = row[3]\n income = row[4]\n # Now print fetched result\n print \"fname=%s,lname=%s,age=%d,sex=%s,income=%d\" % \\\n (fname, lname, age, sex, income )\nexcept:\n print \"Error: unable to fecth data\"\n\n# disconnect from server\ndb.close()\n\nThis will produce the following result \u2212\n\nfname=Mac, lname=Mohan, age=20, sex=M, income=2000", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2cbc6ef3bd5e64c97579d7da3d81812e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "UPDATE Operation on any database means to update one or more records, which are already available in the database.\nThe following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68b593a84c748441a8fee28e79d48f49", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to UPDATE required records\nsql = \"UPDATE EMPLOYEE SET AGE = AGE + 1\n WHERE SEX = '%c'\" % ('M')\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f97ce7eda59b6ec5ca7579d5e4ae4543", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d67336ee226adb0565586ae4ddc4f144", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "4172e64d4f1f72d3a5ffa73a41225ef8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Transactions are a mechanism that ensures data consistency. Transactions have the following four properties \u2212\n\nAtomicity \u2212 Either a transaction completes or nothing happens at all.\nConsistency \u2212 A transaction must start in a consistent state and leave the system in a consistent state.\nIsolation \u2212 Intermediate results of a transaction are not visible outside the current transaction.\nDurability \u2212 Once a transaction was committed, the effects are persistent, even after a system failure.\n\nThe Python DB API 2.0 provides two methods to either commit or rollback a transaction.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "510015a9904ca9f0ff1e984a5033fdfd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You already know how to implement transactions. Here is again similar example \u2212\n\n# Prepare SQL query to DELETE required records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "957dab0f4164be2ea40b90cb29bbc963", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.\nHere is a simple example to call commit method.\n\ndb.commit()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "84a29a296a2099505e6a8185b34d836c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.\nHere is a simple example to call rollback() method.\n\ndb.rollback()", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "fa40dbd3b9aded370d7907b60e9b1a11", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To disconnect Database connection, use close() method.\n\ndb.close()\n\nIf the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "61241339a112be6d399168d490797fd7", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.\nThe DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.\n\n\nSr.No.\nException & Description\n\n\n1\nWarning\nUsed for non-fatal issues. Must subclass StandardError.\n\n\n2\nError\nBase class for errors. Must subclass StandardError.\n\n\n3\nInterfaceError\nUsed for errors in the database module, not the database itself. Must subclass Error.\n\n\n4\nDatabaseError\nUsed for errors in the database. Must subclass Error.\n\n\n5\nDataError\nSubclass of DatabaseError that refers to errors in the data.\n\n\n6\nOperationalError\nSubclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.\n\n\n7\nIntegrityError\nSubclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.\n\n\n8\nInternalError\nSubclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.\n\n\n9\nProgrammingError\nSubclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.\n\n\n10\nNotSupportedError\nSubclass of DatabaseError that refers to trying to call unsupported functionality.\n\n\nYour Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "95f7d45652a65f6fdc2a13a15feed3b1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.\nPython also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.\nThis chapter gives you understanding on most famous concept in Networking - Socket Programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "492a70c10a003d9c782698eee16aea69", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.\nSockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest.\nSockets have their own vocabulary \u2212\n\n\nSr.No.\nTerm & Description\n\n\n1\nDomain\nThe family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.\n\n\n2\ntype\nThe type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.\n\n\n3\nprotocol\nTypically zero, this may be used to identify a variant of a protocol within a domain and type.\n\n\n4\nhostname\nThe identifier of a network interface \u2212\n\nA string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation\nA string \"<broadcast>\", which specifies an INADDR_BROADCAST address.\nA zero-length string, which specifies INADDR_ANY, or\nAn Integer, interpreted as a binary address in host byte order.\n\n\n\n5\nport\nEach server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2d8889540c0a7811bd9eece287d8ae0e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax \u2212\n\ns = socket.socket (socket_family, socket_type, protocol=0)\n\nHere is the description of the parameters \u2212\n\nsocket_family \u2212 This is either AF_UNIX or AF_INET, as explained earlier.\nsocket_type \u2212 This is either SOCK_STREAM or SOCK_DGRAM.\nprotocol \u2212 This is usually left out, defaulting to 0.\n\nOnce you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "077b0fdf5b2554f37661f8966e9e9865", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.bind()\nThis method binds address (hostname, port number pair) to socket.\n\n\n2\ns.listen()\nThis method sets up and start TCP listener.\n\n\n3\ns.accept()\nThis passively accept TCP client connection, waiting until connection arrives (blocking).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d78a0df1d797642bd7e15f9c52b68fbd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.connect()\nThis method actively initiates TCP server connection.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3c64a5975265fc9734711a3dd8f10fde", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Sr.No.\nMethod & Description\n\n\n1\ns.recv()\nThis method receives TCP message\n\n\n2\ns.send()\nThis method transmits TCP message\n\n\n3\ns.recvfrom()\nThis method receives UDP message\n\n\n4\ns.sendto()\nThis method transmits UDP message\n\n\n5\ns.close()\nThis method closes socket\n\n\n6\nsocket.gethostname()\nReturns the hostname.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "12a2e1979c3b0b21ae6cdc1f8fac7f76", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.\nNow call bind(hostname, port) function to specify a port for your service on the given host.\nNext, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.\n\n#!/usr/bin/python # This is server.py file\n\nimport socket # Import socket module\n\ns = socket.socket() # Create a socket object\nhost = socket.gethostname() # Get local machine name\nport = 12345 # Reserve a port for your service.\ns.bind((host, port)) # Bind to the port\n\ns.listen(5) # Now wait for client connection.\nwhile True:\n c, addr = s.accept() # Establish connection with client.\n print 'Got connection from', addr\n c.send('Thank you for connecting')\n c.close() # Close the connection", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8e7299c268a80d1ecb90c3c3ba1a2d08", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python's socket module function.\nThe socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.\nThe following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits \u2212\n\n#!/usr/bin/python # This is client.py file\n\nimport socket # Import socket module\n\ns = socket.socket() # Create a socket object\nhost = socket.gethostname() # Get local machine name\nport = 12345 # Reserve a port for your service.\n\ns.connect((host, port))\nprint s.recv(1024)\ns.close() # Close the socket when done\n\nNow run this server.py in background and then run above client.py to see the result.\n\n# Following would start a server in background.\n$ python server.py & \n\n# Once server is started run client as follows:\n$ python client.py\n\nThis would produce following result \u2212\n\nGot connection from ('127.0.0.1', 48437)\nThank you for connecting", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "dccba84f0cec4813952a595ba73c523d", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A list of some important modules in Python Network/Internet programming.\n\n\nProtocol\nCommon function\nPort No\nPython module\n\n\nHTTP\nWeb pages\n80\nhttplib, urllib, xmlrpclib\n\n\nNNTP\nUsenet news\n119\nnntplib\n\n\nFTP\nFile transfers\n20\nftplib, urllib\n\n\nSMTP\nSending email\n25\nsmtplib\n\n\nPOP3\nFetching email\n110\npoplib\n\n\nIMAP4\nFetching email\n143\nimaplib\n\n\nTelnet\nCommand lines\n23\ntelnetlib\n\n\nGopher\nDocument transfers\n70\ngopherlib, urllib\n\n\nPlease check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "496f4fb42be88c89a018ea94c887af38", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This was a quick start with Socket Programming. It is a vast subject. It is recommended to go through the following link to find more detail \u2212\n\nUnix Socket Programming.\nPython Socket Library and Modules.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0eeb33dcb11a313cde7d1b786e8dc16c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.\nPython provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.\nHere is a simple syntax to create one SMTP object, which can later be used to send an e-mail \u2212\n\nimport smtplib\n\nsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )\n\nHere is the detail of the parameters \u2212\n\nhost \u2212 This is the host running your SMTP server. You can specify IP address of the host or a domain name like tutorialspoint.com. This is optional argument.\nport \u2212 If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25.\nlocal_hostname \u2212 If your SMTP server is running on your local machine, then you can specify just localhost as of this option.\n\nAn SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. It takes three parameters \u2212\n\nThe sender \u2212 A string with the address of the sender.\nThe receivers \u2212 A list of strings, one for each recipient.\nThe message \u2212 A message as a string formatted as specified in the various RFCs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "061863cdb5ef88eacd4edaaac0a871e2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is a simple way to send one e-mail using Python script. Try it once \u2212\n\n#!/usr/bin/python\n\nimport smtplib\n\nsender = '[email protected]'\nreceivers = ['[email protected]']\n\nmessage = \"\"\"From: From Person <[email protected]>\nTo: To Person <[email protected]>\nSubject: SMTP e-mail test\n\nThis is a test e-mail message.\n\"\"\"\n\ntry:\n smtpObj = smtplib.SMTP('localhost')\n smtpObj.sendmail(sender, receivers, message) \n print \"Successfully sent email\"\nexcept SMTPException:\n print \"Error: unable to send email\"\n\nHere, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From, To, and Subject header, separated from the body of the e-mail with a blank line.\nTo send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).\nIf you are not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider must have provided you with outgoing mail server details that you can supply them, as follows \u2212\n\nsmtplib.SMTP('mail.your-domain.com', 25)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "5e66bc9a8ecaf8eb68b5bc14de626dff", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.\nWhile sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "98f7a6fd3236e4ebd7fd17b99c98eccd", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example to send HTML content as an e-mail. Try it once \u2212\n\n#!/usr/bin/python\n\nimport smtplib\n\nmessage = \"\"\"From: From Person <[email protected]>\nTo: To Person <[email protected]>\nMIME-Version: 1.0\nContent-type: text/html\nSubject: SMTP HTML e-mail test\n\nThis is an e-mail message to be sent in HTML format\n\n<b>This is HTML message.</b>\n<h1>This is headline.</h1>\n\"\"\"\n\ntry:\n smtpObj = smtplib.SMTP('localhost')\n smtpObj.sendmail(sender, receivers, message) \n print \"Successfully sent email\"\nexcept SMTPException:\n print \"Error: unable to send email\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b1452ed1b24e043b0da359b53b1e5514", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.\nA boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.\nAttached files should be encoded with the pack(\"m\") function to have base64 encoding before transmission.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "799b82812cf4ca1b11b5355524edd725", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once \u2212\n\n#!/usr/bin/python\n\nimport smtplib\nimport base64\n\nfilename = \"/tmp/test.txt\"\n\n# Read a file and encode it into base64 format\nfo = open(filename, \"rb\")\nfilecontent = fo.read()\nencodedcontent = base64.b64encode(filecontent) # base64\n\nsender = '[email protected]'\nreciever = '[email protected]'\n\nmarker = \"AUNIQUEMARKER\"\n\nbody =\"\"\"\nThis is a test email to send an attachement.\n\"\"\"\n# Define the main headers.\npart1 = \"\"\"From: From Person <[email protected]>\nTo: To Person <[email protected]>\nSubject: Sending Attachement\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=%s\n--%s\n\"\"\" % (marker, marker)\n\n# Define the message action\npart2 = \"\"\"Content-Type: text/plain\nContent-Transfer-Encoding:8bit\n\n%s\n--%s\n\"\"\" % (body,marker)\n\n# Define the attachment section\npart3 = \"\"\"Content-Type: multipart/mixed; name=\\\"%s\\\"\nContent-Transfer-Encoding:base64\nContent-Disposition: attachment; filename=%s\n\n%s\n--%s--\n\"\"\" %(filename, filename, encodedcontent, marker)\nmessage = part1 + part2 + part3\n\ntry:\n smtpObj = smtplib.SMTP('localhost')\n smtpObj.sendmail(sender, reciever, message)\n print \"Successfully sent email\"\nexcept Exception:\n print \"Error: unable to send email\"", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1d7ee69c82e09fad7b8304c36ea11721", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Running several threads is similar to running several different programs concurrently, but with the following benefits \u2212\n\nMultiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.\nThreads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.\n\nA thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running.\n\nIt can be pre-empted (interrupted)\nIt can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d016a371a2dbe5455c9e2854de3bd119", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To spawn another thread, you need to call following method available in thread module \u2212\n\nthread.start_new_thread ( function, args[, kwargs] )\n\nThis method call enables a fast and efficient way to create new threads in both Linux and Windows.\nThe method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.\nHere, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "950aaa9f3c135f133b48106ef8528d24", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport thread\nimport time\n\n# Define a function for the thread\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print \"%s: %s\" % ( threadName, time.ctime(time.time()) )\n\n# Create two threads as follows\ntry:\n thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print \"Error: unable to start thread\"\n\nwhile 1:\n pass\n\nWhen the above code is executed, it produces the following result \u2212\n\nThread-1: Thu Jan 22 15:42:17 2009\nThread-1: Thu Jan 22 15:42:19 2009\nThread-2: Thu Jan 22 15:42:19 2009\nThread-1: Thu Jan 22 15:42:21 2009\nThread-2: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:25 2009\nThread-2: Thu Jan 22 15:42:27 2009\nThread-2: Thu Jan 22 15:42:31 2009\nThread-2: Thu Jan 22 15:42:35 2009\n\nAlthough it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "a5de9f8410c5827f0b63cb55dfc20b35", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.\nThe threading module exposes all the methods of the thread module and provides some additional methods \u2212\n\nthreading.activeCount() \u2212 Returns the number of thread objects that are active.\nthreading.currentThread() \u2212 Returns the number of thread objects in the caller's thread control.\nthreading.enumerate() \u2212 Returns a list of all thread objects that are currently active.\n\nIn addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows \u2212\n\nrun() \u2212 The run() method is the entry point for a thread.\nstart() \u2212 The start() method starts a thread by calling the run method.\n join([time]) \u2212 The join() waits for threads to terminate.\n isAlive() \u2212 The isAlive() method checks whether a thread is still executing.\n getName() \u2212 The getName() method returns the name of a thread.\n setName() \u2212 The setName() method sets the name of a thread.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6b9f8c7c7c1572d48f172d5d49bd7ef0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To implement a new thread using the threading module, you have to do the following \u2212\n\nDefine a new subclass of the Thread class.\nOverride the __init__(self [,args]) method to add additional arguments.\nThen, override the run(self [,args]) method to implement what the thread should do when started.\n\nOnce you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "005f4053f7aa44bb5bf15eced32462f2", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n print_time(self.name, self.counter, 5)\n print \"Exiting \" + self.name\n\ndef print_time(threadName, counter, delay):\n while counter:\n if exitFlag:\n threadName.exit()\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\nprint \"Exiting Main Thread\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nStarting Thread-1\nStarting Thread-2\nExiting Main Thread\nThread-1: Thu Mar 21 09:10:03 2013\nThread-1: Thu Mar 21 09:10:04 2013\nThread-2: Thu Mar 21 09:10:04 2013\nThread-1: Thu Mar 21 09:10:05 2013\nThread-1: Thu Mar 21 09:10:06 2013\nThread-2: Thu Mar 21 09:10:06 2013\nThread-1: Thu Mar 21 09:10:07 2013\nExiting Thread-1\nThread-2: Thu Mar 21 09:10:08 2013\nThread-2: Thu Mar 21 09:10:10 2013\nThread-2: Thu Mar 21 09:10:12 2013\nExiting Thread-2", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f444c9304ec413f962f9f19c53e16e15", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.\nThe acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.\nIf blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.\nThe release() method of the new lock object is used to release the lock when it is no longer required.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cab41c4fa7d5cb6edadddd3fa5623f71", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport threading\nimport time\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n # Get lock to synchronize threads\n threadLock.acquire()\n print_time(self.name, self.counter, 3)\n # Free lock to release next thread\n threadLock.release()\n\ndef print_time(threadName, delay, counter):\n while counter:\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\n\nthreadLock = threading.Lock()\nthreads = []\n\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\n# Start new Threads\nthread1.start()\nthread2.start()\n\n# Add threads to thread list\nthreads.append(thread1)\nthreads.append(thread2)\n\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nStarting Thread-1\nStarting Thread-2\nThread-1: Thu Mar 21 09:11:28 2013\nThread-1: Thu Mar 21 09:11:29 2013\nThread-1: Thu Mar 21 09:11:30 2013\nThread-2: Thu Mar 21 09:11:32 2013\nThread-2: Thu Mar 21 09:11:34 2013\nThread-2: Thu Mar 21 09:11:36 2013\nExiting Main Thread", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b539e12f625186a241eb3c04d838fa68", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue \u2212\n\nget() \u2212 The get() removes and returns an item from the queue.\nput() \u2212 The put adds item to a queue.\nqsize() \u2212 The qsize() returns the number of items that are currently in the queue.\nempty() \u2212 The empty( ) returns True if queue is empty; otherwise, False.\nfull() \u2212 the full() returns True if queue is full; otherwise, False.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "2bae1a926a9580f42b7af3d0d175d156", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport Queue\nimport threading\nimport time\n\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, q):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.q = q\n def run(self):\n print \"Starting \" + self.name\n process_data(self.name, self.q)\n print \"Exiting \" + self.name\n\ndef process_data(threadName, q):\n while not exitFlag:\n queueLock.acquire()\n if not workQueue.empty():\n data = q.get()\n queueLock.release()\n print \"%s processing %s\" % (threadName, data)\n else:\n queueLock.release()\n time.sleep(1)\n\nthreadList = [\"Thread-1\", \"Thread-2\", \"Thread-3\"]\nnameList = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"]\nqueueLock = threading.Lock()\nworkQueue = Queue.Queue(10)\nthreads = []\nthreadID = 1\n\n# Create new threads\nfor tName in threadList:\n thread = myThread(threadID, tName, workQueue)\n thread.start()\n threads.append(thread)\n threadID += 1\n\n# Fill the queue\nqueueLock.acquire()\nfor word in nameList:\n workQueue.put(word)\nqueueLock.release()\n\n# Wait for queue to empty\nwhile not workQueue.empty():\n pass\n\n# Notify threads it's time to exit\nexitFlag = 1\n\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\"\n\nWhen the above code is executed, it produces the following result \u2212\n\nStarting Thread-1\nStarting Thread-2\nStarting Thread-3\nThread-1 processing One\nThread-2 processing Two\nThread-3 processing Three\nThread-1 processing Four\nThread-2 processing Five\nExiting Thread-3\nExiting Thread-1\nExiting Thread-2\nExiting Main Thread", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cab8694f1fd9ed066a98a15d281b7356", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "16ff4007bf6e664dd02247e3b5eff0f6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.\nXML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6ae1e0edb02ca8bedb6d92812f66c3eb", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Python standard library provides a minimal but useful set of interfaces to work with XML.\nThe two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.\n\nSimple API for XML (SAX) \u2212 Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk and the entire file is never stored in memory.\nDocument Object Model (DOM) API \u2212 This is a World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.\n\n\nSAX obviously cannot process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files.\nSAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other, there is no reason why you cannot use them both for large projects.\nFor all our XML code examples, let's use a simple XML file movies.xml as an input \u2212\n\n<collection shelf=\"New Arrivals\">\n<movie title=\"Enemy Behind\">\n <type>War, Thriller</type>\n <format>DVD</format>\n <year>2003</year>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Talk about a US-Japan war</description>\n</movie>\n<movie title=\"Transformers\">\n <type>Anime, Science Fiction</type>\n <format>DVD</format>\n <year>1989</year>\n <rating>R</rating>\n <stars>8</stars>\n <description>A schientific fiction</description>\n</movie>\n <movie title=\"Trigun\">\n <type>Anime, Action</type>\n <format>DVD</format>\n <episodes>4</episodes>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Vash the Stampede!</description>\n</movie>\n<movie title=\"Ishtar\">\n <type>Comedy</type>\n <format>VHS</format>\n <rating>PG</rating>\n <stars>2</stars>\n <description>Viewable boredom</description>\n</movie>\n</collection>", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ddd89a8e481020bc12399915168cb4f1", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.ContentHandler.\nYour ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file.\nThe methods startDocument and endDocument are called at the start and the end of the XML file. The method characters(text) is passed character data of the XML file via the parameter text.\nThe ContentHandler is called at the start and end of each element. If the parser is not in namespace mode, the methods startElement(tag, attributes) and endElement(tag) are called; otherwise, the corresponding methods startElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an Attributes object.\nHere are other important methods to understand before proceeding \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "01d9c4543f6570c70555f9db285d7eb0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following method creates a new parser object and returns it. The parser object created will be of the first parser type the system finds.\n\nxml.sax.make_parser( [parser_list] )\n\nHere is the detail of the parameters \u2212\n\nparser_list \u2212 The optional argument consisting of a list of parsers to use which must all implement the make_parser method.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "7e062a8b549a94d645da26931fa7d9f9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Following method creates a SAX parser and uses it to parse a document.\n\nxml.sax.parse( xmlfile, contenthandler[, errorhandler])\n\nHere is the detail of the parameters \u2212\n\nxmlfile \u2212 This is the name of the XML file to read from.\ncontenthandler \u2212 This must be a ContentHandler object.\nerrorhandler \u2212 If specified, errorhandler must be a SAX ErrorHandler object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "419323cbf56afb7b8d219d4d4ce367ef", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "There is one more method to create a SAX parser and to parse the specified XML string.\n\nxml.sax.parseString(xmlstring, contenthandler[, errorhandler])\n\nHere is the detail of the parameters \u2212\n\nxmlstring \u2212 This is the name of the XML string to read from.\ncontenthandler \u2212 This must be a ContentHandler object.\nerrorhandler \u2212 If specified, errorhandler must be a SAX ErrorHandler object.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e93fc6337b4a83d1a5e162f5b058c417", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport xml.sax\n\nclass MovieHandler( xml.sax.ContentHandler ):\n def __init__(self):\n self.CurrentData = \"\"\n self.type = \"\"\n self.format = \"\"\n self.year = \"\"\n self.rating = \"\"\n self.stars = \"\"\n self.description = \"\"\n\n # Call when an element starts\n def startElement(self, tag, attributes):\n self.CurrentData = tag\n if tag == \"movie\":\n print \"*****Movie*****\"\n title = attributes[\"title\"]\n print \"Title:\", title\n\n # Call when an elements ends\n def endElement(self, tag):\n if self.CurrentData == \"type\":\n print \"Type:\", self.type\n elif self.CurrentData == \"format\":\n print \"Format:\", self.format\n elif self.CurrentData == \"year\":\n print \"Year:\", self.year\n elif self.CurrentData == \"rating\":\n print \"Rating:\", self.rating\n elif self.CurrentData == \"stars\":\n print \"Stars:\", self.stars\n elif self.CurrentData == \"description\":\n print \"Description:\", self.description\n self.CurrentData = \"\"\n\n # Call when a character is read\n def characters(self, content):\n if self.CurrentData == \"type\":\n self.type = content\n elif self.CurrentData == \"format\":\n self.format = content\n elif self.CurrentData == \"year\":\n self.year = content\n elif self.CurrentData == \"rating\":\n self.rating = content\n elif self.CurrentData == \"stars\":\n self.stars = content\n elif self.CurrentData == \"description\":\n self.description = content\n \nif ( __name__ == \"__main__\"):\n \n # create an XMLReader\n parser = xml.sax.make_parser()\n # turn off namepsaces\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n\n # override the default ContextHandler\n Handler = MovieHandler()\n parser.setContentHandler( Handler )\n \n parser.parse(\"movies.xml\")\n\nThis would produce following result \u2212\n\n*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nYear: 2003\nRating: PG\nStars: 10\nDescription: Talk ", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "472dc5b90e490eb34841cbdfa7820b34", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nYear: 1989\nRating: R\nStars: 8\nDescription: A schientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nFormat: DVD\nRating: PG\nStars: 10\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nStars: 2\nDescription: Viewable boredom\n\nFor a complete detail on SAX API documentation, please refer to standard Python SAX APIs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "85293568ea1f808332ec51ae05e7578b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The Document Object Model (\"DOM\") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents.\nThe DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another.\nHere is the easiest way to quickly load an XML document and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file.\nThe sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object.\n\n#!/usr/bin/python\n\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\n\n# Open XML document using minidom parser\nDOMTree = xml.dom.minidom.parse(\"movies.xml\")\ncollection = DOMTree.documentElement\nif collection.hasAttribute(\"shelf\"):\n print \"Root element : %s\" % collection.getAttribute(\"shelf\")\n\n# Get all the movies in the collection\nmovies = collection.getElementsByTagName(\"movie\")\n\n# Print detail of each movie.\nfor movie in movies:\n print \"*****Movie*****\"\n if movie.hasAttribute(\"title\"):\n print \"Title: %s\" % movie.getAttribute(\"title\")\n\n type = movie.getElementsByTagName('type')[0]\n print \"Type: %s\" % type.childNodes[0].data\n format = movie.getElementsByTagName('format')[0]\n print \"Format: %s\" % format.childNodes[0].data\n rating = movie.getElementsByTagName('rating')[0]\n print \"Rating: %s\" % rating.childNodes[0].data\n description = movie.getElementsByTagName('description')[0]\n print \"Description: %s\" % description.childNodes[0].data\n\nThis would produce the following result \u2212\n\nRoot element : New Arrivals\n*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nRating: PG\nDescription: Talk about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nRating: R\nDescription: A schientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nForm", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "75292a6bf8558c269e0006d3cacc6e18", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "at: DVD\nRating: PG\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nDescription: Viewable boredom\n\nFor a complete detail on DOM API documentation, please refer to standard Python DOM APIs.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "838709b7876b17eaf0a85f1ce85481f4", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.\n\nTkinter \u2212 Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter.\nwxPython \u2212 This is an open-source Python interface for wxWindows http://wxpython.org.\nJPython \u2212 JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org.\n\nThere are many other interfaces available, which you can find them on the net.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "3a1d2cd34a6a5a4245ce8d051f36523b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.\nCreating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps \u2212\n\nImport the Tkinter module.\nCreate the GUI application main window.\nAdd one or more of the above-mentioned widgets to the GUI application.\nEnter the main event loop to take action against each event triggered by the user.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "cec9416a8c3e77054ef87ab613945b1b", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\n\nimport Tkinter\ntop = Tkinter.Tk()\n# Code to add widgets will go here...\ntop.mainloop()\n\nThis would create a following window \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ddf206fc609b352ec7f6e0f9f983c0c3", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.\nThere are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table \u2212\n\n\nSr.No.\nOperator & Description\n\n\n1\nButton\nThe Button widget is used to display buttons in your application.\n\n\n2\nCanvas\nThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.\n\n\n3\nCheckbutton\nThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.\n\n\n4\nEntry\nThe Entry widget is used to display a single-line text field for accepting values from a user.\n\n\n5\nFrame\nThe Frame widget is used as a container widget to organize other widgets.\n\n\n6\nLabel\nThe Label widget is used to provide a single-line caption for other widgets. It can also contain images.\n\n\n7\nListbox\nThe Listbox widget is used to provide a list of options to a user.\n\n\n8\nMenubutton\nThe Menubutton widget is used to display menus in your application.\n\n\n9\nMenu\nThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.\n\n\n10\nMessage\nThe Message widget is used to display multiline text fields for accepting values from a user.\n\n\n11\nRadiobutton\nThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.\n\n\n12\nScale\nThe Scale widget is used to provide a slider widget.\n\n\n13\nScrollbar\nThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.\n\n\n14\nText\nThe Text widget is used to display text in multiple lines.\n\n\n15\nToplevel\nThe Toplevel widget is used to provide a separate window container.\n\n\n16\nSpinbox\nThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.\n\n\n17\nPanedWindow\nA PanedWindow is a container widget that may contain any number of panes, ar", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "e04d720bcc544ae5eaf35fb87de5670a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "ranged horizontally or vertically.\n\n\n18\nLabelFrame\nA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.\n\n\n19\ntkMessageBox\nThis module is used to display message boxes in your applications.\n\n\nLet us study these widgets in detail \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "025ae87afaa19e8fadf371035ca80e3e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified.\n\nDimensions\nColors\nFonts\nAnchors\nRelief styles\nBitmaps\nCursors\n\nLet us study them briefly \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "26c894a919c41062542dab1bfaeed08c", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place.\n\nThe pack() Method \u2212 This geometry manager organizes widgets in blocks before placing them in the parent widget.\nThe grid() Method \u2212 This geometry manager organizes widgets in a table-like structure in the parent widget.\nThe place() Method \u2212 This geometry manager organizes widgets by placing them in a specific position in the parent widget.\n\nLet us study the geometry management methods briefly \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "9a193d3e1869d5ac3860b0032f221d15", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an \"extension.\"\nA Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for shared object). On Windows machines, you typically see .dll (for dynamically linked library).", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6db16196724ec36b4175094a19308a7a", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "To start writing your extension, you are going to need the Python header files.\n\nOn Unix machines, this usually requires installing a developer-specific package such as python2.5-dev.\nWindows users get these headers as part of the package when they use the binary Python installer.\n\nAdditionally, it is assumed that you have good knowledge of C or C++ to write any Python Extension using C programming.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "f1fedc221ede5220591fcd3df373a86f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "For your first look at a Python extension module, you need to group your code into four part \u2212\n\nThe header file Python.h.\nThe C functions you want to expose as the interface from your module.\nA table mapping the names of your functions as Python developers see them to C functions inside the extension module.\nAn initialization function.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b7d752d3f1f6875b48267bdf45b7dbd0", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "You need include Python.h header file in your C source file, which gives you access to the internal Python API used to hook your module into the interpreter.\nMake sure to include Python.h before any other headers you might need. You need to follow the includes with the functions you want to call from Python.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "6b48189beb28a13cd5bd8a810077c613", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The signatures of the C implementation of your functions always takes one of the following three forms \u2212\n\nstatic PyObject *MyFunction( PyObject *self, PyObject *args );\n\nstatic PyObject *MyFunctionWithKeywords(PyObject *self,\n PyObject *args,\n PyObject *kw);\n\nstatic PyObject *MyFunctionWithNoArgs( PyObject *self );\n\nEach one of the preceding declarations returns a Python object. There is no such thing as a void function in Python as there is in C. If you do not want your functions to return a value, return the C equivalent of Python's None value. The Python headers define a macro, Py_RETURN_NONE, that does this for us.\nThe names of your C functions can be whatever you like as they are never seen outside of the extension module. They are defined as static function.\nYour C functions usually are named by combining the Python module and function names together, as shown here \u2212\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Do your stuff here. */\n Py_RETURN_NONE;\n}\n\nThis is a Python function called func inside of the module module. You will be putting pointers to your C functions into the method table for the module that usually comes next in your source code.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8fa37dded11120c0d99e8da1a9a35775", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "This method table is a simple array of PyMethodDef structures. That structure looks something like this \u2212\n\nstruct PyMethodDef {\n char *ml_name;\n PyCFunction ml_meth;\n int ml_flags;\n char *ml_doc;\n};\n\nHere is the description of the members of this structure \u2212\n\nml_name \u2212 This is the name of the function as the Python interpreter presents when it is used in Python programs.\nml_meth \u2212 This must be the address to a function that has any one of the signatures described in previous seection.\nml_flags \u2212 This tells the interpreter which of the three signatures ml_meth is using.\n\nThis flag usually has a value of METH_VARARGS.\nThis flag can be bitwise OR'ed with METH_KEYWORDS if you want to allow keyword arguments into your function.\nThis can also have a value of METH_NOARGS that indicates you do not want to accept any arguments.\n\n\nml_doc \u2212 This is the docstring for the function, which could be NULL if you do not feel like writing one.\n\nThis table needs to be terminated with a sentinel that consists of NULL and 0 values for the appropriate members.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "35b81f882c8f4f93e3e18bf59d727b7f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "For the above-defined function, we have following method mapping table \u2212\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { NULL, NULL, 0, NULL }\n};", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "123e670e80dd2e42ff5fd066d927018e", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The last part of your extension module is the initialization function. This function is called by the Python interpreter when the module is loaded. It is required that the function be named initModule, where Module is the name of the module.\nThe initialization function needs to be exported from the library you will be building. The Python headers define PyMODINIT_FUNC to include the appropriate incantations for that to happen for the particular environment in which we're compiling. All you have to do is use it when defining the function.\nYour C initialization function generally has the following overall structure \u2212\n\nPyMODINIT_FUNC initModule() {\n Py_InitModule3(func, module_methods, \"docstring...\");\n}\n\nHere is the description of Py_InitModule3 function \u2212\n\nfunc \u2212 This is the function to be exported.\nmodule_methods \u2212 This is the mapping table name defined above.\ndocstring \u2212 This is the comment you want to give in your extension.\n\nPutting this all together looks like the following \u2212\n\n#include <Python.h>\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Do your stuff here. */\n Py_RETURN_NONE;\n}\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { NULL, NULL, 0, NULL }\n};\n\nPyMODINIT_FUNC initModule() {\n Py_InitModule3(func, module_methods, \"docstring...\");\n}", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d74b8164dacf75030e04f3625e6984f9", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "A simple example that makes use of all the above concepts \u2212\n\n#include <Python.h>\n\nstatic PyObject* helloworld(PyObject* self) {\n return Py_BuildValue(\"s\", \"Hello, Python extensions!!\");\n}\n\nstatic char helloworld_docs[] =\n \"helloworld( ): Any message you want to put here!!\\n\";\n\nstatic PyMethodDef helloworld_funcs[] = {\n {\"helloworld\", (PyCFunction)helloworld, \n METH_NOARGS, helloworld_docs},\n {NULL}\n};\n\nvoid inithelloworld(void) {\n Py_InitModule3(\"helloworld\", helloworld_funcs,\n \"Extension module example!\");\n}\n\nHere the Py_BuildValue function is used to build a Python value. Save above code in hello.c file. We would see how to compile and install this module to be called from Python script.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "8ebf2105114fa3ee10ff6b280c586450", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The distutils package makes it very easy to distribute Python modules, both pure Python and extension modules, in a standard way. Modules are distributed in source form and built and installed via a setup script usually called setup.py as follows.\nFor the above module, you need to prepare following setup.py script \u2212\n\nfrom distutils.core import setup, Extension\nsetup(name='helloworld', version='1.0', \\\n ext_modules=[Extension('helloworld', ['hello.c'])])\n\nNow, use the following command, which would perform all needed compilation and linking steps, with the right compiler and linker commands and flags, and copies the resulting dynamic library into an appropriate directory \u2212\n\n$ python setup.py install\n\nOn Unix-based systems, you'll most likely need to run this command as root in order to have permissions to write to the site-packages directory. This usually is not a problem on Windows.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "afe7e7634f5d2f0a97fb89adcd3770c8", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Once you installed your extension, you would be able to import and call that extension in your Python script as follows \u2212\n\n#!/usr/bin/python\nimport helloworld\n\nprint helloworld.helloworld()\n\nThis would produce the following result \u2212\n\nHello, Python extensions!!", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "76ab8e2e681e3f34b8578aa054bd8fad", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "As you will most likely want to define functions that accept arguments, you can use one of the other signatures for your C functions. For example, following function, that accepts some number of parameters, would be defined like this \u2212\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n /* Parse args and do something interesting here. */\n Py_RETURN_NONE;\n}\n\nThe method table containing an entry for the new function would look like this \u2212\n\nstatic PyMethodDef module_methods[] = {\n { \"func\", (PyCFunction)module_func, METH_NOARGS, NULL },\n { \"func\", module_func, METH_VARARGS, NULL },\n { NULL, NULL, 0, NULL }\n};\n\nYou can use API PyArg_ParseTuple function to extract the arguments from the one PyObject pointer passed into your C function.\nThe first argument to PyArg_ParseTuple is the args argument. This is the object you will be parsing. The second argument is a format string describing the arguments as you expect them to appear. Each argument is represented by one or more characters in the format string as follows.\n\nstatic PyObject *module_func(PyObject *self, PyObject *args) {\n int i;\n double d;\n char *s;\n\n if (!PyArg_ParseTuple(args, \"ids\", &i, &d, &s)) {\n return NULL;\n }\n \n /* Do something interesting here. */\n Py_RETURN_NONE;\n}\n\nCompiling the new version of your module and importing it enables you to invoke the new function with any number of arguments of any type \u2212\n\nmodule.func(1, s=\"three\", d=2.0)\nmodule.func(i=1, d=2.0, s=\"three\")\nmodule.func(s=\"three\", d=2.0, i=1)\n\nYou can probably come up with even more variations.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "71a8b63385544ad8da9530a96ae48899", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Here is the standard signature for PyArg_ParseTuple function \u2212\n\nint PyArg_ParseTuple(PyObject* tuple,char* format,...)\n\nThis function returns 0 for errors, and a value not equal to 0 for success. tuple is the PyObject* that was the C function's second argument. Here format is a C string that describes mandatory and optional arguments.\nHere is a list of format codes for PyArg_ParseTuple function \u2212\n\n\nCode\nC type\nMeaning\n\n\nc\nchar\n A Python string of length 1 becomes a C char.\n\nd\ndouble\nA Python float becomes a C double.\n\nf\nfloat\nA Python float becomes a C float.\n\ni\nint\nA Python int becomes a C int.\n\nl\nlong\nA Python int becomes a C long.\n\nL\nlong long\nA Python int becomes a C long long\n\nO\nPyObject*\nGets non-NULL borrowed reference to Python argument.\n\ns\nchar*\nPython string without embedded nulls to C char*.\n\ns#\nchar*+int\nAny Python string to C address and length.\n\nt#\nchar*+int\nRead-only single-segment buffer to C address and length.\n\nu\nPy_UNICODE*\nPython Unicode without embedded nulls to C.\n\nu#\nPy_UNICODE*+int\nAny Python Unicode C address and length.\n\nw#\nchar*+int\nRead/write single-segment buffer to C address and length.\n\nz\nchar*\nLike s, also accepts None (sets C char* to NULL).\n\nz#\nchar*+int\nLike s#, also accepts None (sets C char* to NULL).\n\n(...)\nas per ...\nA Python sequence is treated as one argument per item.\n\n|\n\u00a0\nThe following arguments are optional.\n\n:\n\u00a0\nFormat end, followed by function name for error messages.\n\n;\n\u00a0\nFormat end, followed by entire error message text.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "d9a7cf540d5ad44591b67802f15cc2ad", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Py_BuildValue takes in a format string much like PyArg_ParseTuple does. Instead of passing in the addresses of the values you are building, you pass in the actual values. Here's an example showing how to implement an add function \u2212\n\nstatic PyObject *foo_add(PyObject *self, PyObject *args) {\n int a;\n int b;\n\n if (!PyArg_ParseTuple(args, \"ii\", &a, &b)) {\n return NULL;\n }\n return Py_BuildValue(\"i\", a + b);\n}\n\nThis is what it would look like if implemented in Python \u2212\n\ndef add(a, b):\n return (a + b)\n\nYou can return two values from your function as follows, this would be cauptured using a list in Python.\n\nstatic PyObject *foo_add_subtract(PyObject *self, PyObject *args) {\n int a;\n int b;\n\n if (!PyArg_ParseTuple(args, \"ii\", &a, &b)) {\n return NULL;\n }\n return Py_BuildValue(\"ii\", a + b, a - b);\n}\n\nThis is what it would look like if implemented in Python \u2212\n\ndef add_subtract(a, b):\n return (a + b, a - b)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "ee99061e009a42f0a6f959753ace95ce", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The standard library comes with a number of modules that can be used both as modules and as command-line utilities.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "68d9242bb0ca89b17dca220cddf5ceb5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The dis module is the Python disassembler. It converts byte codes to a format that is slightly more appropriate for human consumption.\nYou can run the disassembler from the command line. It compiles the given script and prints the disassembled byte codes to the STDOUT. You can also use dis as a module. The dis function takes a class, method, function or code object as its single argument.", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "18ea2f8d6231b8a2c60c61a017986c00", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "#!/usr/bin/python\nimport dis\n\ndef sum():\n vara = 10\n varb = 20\n\n sum = vara + varb\n print \"vara + varb = %d\" % sum\n\n# Call dis function for the function.\n\ndis.dis(sum)\n\nThis would produce the following result \u2212\n\n 6 0 LOAD_CONST 1 (10)\n 3 STORE_FAST 0 (vara)\n\n 7 6 LOAD_CONST 2 (20)\n 9 STORE_FAST 1 (varb)\n\n 9 12 LOAD_FAST 0 (vara)\n 15 LOAD_FAST 1 (varb)\n 18 BINARY_ADD\n 19 STORE_FAST 2 (sum)\n\n 10 22 LOAD_CONST 3 ('vara + varb = %d')\n 25 LOAD_FAST 2 (sum)\n 28 BINARY_MODULO\n 29 PRINT_ITEM\n 30 PRINT_NEWLINE\n 31 LOAD_CONST 0 (None)\n 34 RETURN_VALUE", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "bbaef3a4600870fe74ec0c03f4183d46", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The pdb module is the standard Python debugger. It is based on the bdb debugger framework.\nYou can run the debugger from the command line (type n [or next] to go to the next line and help to get a list of available commands) \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "1640608ddd6ef5f4f7872724c96d66c5", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Before you try to run pdb.py, set your path properly to Python lib directory. So let us try with above example sum.py \u2212\n\n$pdb.py sum.py\n> /test/sum.py(3)<module>()\n-> import dis\n(Pdb) n\n> /test/sum.py(5)<module>()\n-> def sum():\n(Pdb) n\n>/test/sum.py(14)<module>()\n-> dis.dis(sum)\n(Pdb) n\n 6 0 LOAD_CONST 1 (10)\n 3 STORE_FAST 0 (vara)\n\n 7 6 LOAD_CONST 2 (20)\n 9 STORE_FAST 1 (varb)\n\n 9 12 LOAD_FAST 0 (vara)\n 15 LOAD_FAST 1 (varb)\n 18 BINARY_ADD\n 19 STORE_FAST 2 (sum)\n\n 10 22 LOAD_CONST 3 ('vara + varb = %d')\n 25 LOAD_FAST 2 (sum)\n 28 BINARY_MODULO\n 29 PRINT_ITEM\n 30 PRINT_NEWLINE\n 31 LOAD_CONST 0 (None)\n 34 RETURN_VALUE\n--Return--\n> /test/sum.py(14)<module>()->None\n-v dis.dis(sum)\n(Pdb) n\n--Return--\n> <string>(1)<module>()->None\n(Pdb)", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0937d73f042393482015941dadc33f68", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The profile module is the standard Python profiler. You can run the profiler from the command line \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "b126adf06cd69c579632ae4db38fd7a6", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "Let us try to profile the following program \u2212\n\n#!/usr/bin/python\n\nvara = 10\nvarb = 20\n\nsum = vara + varb\nprint \"vara + varb = %d\" % sum\n\nNow, try running cProfile.py over this file sum.py as follows \u2212\n\n$cProfile.py sum.py\nvara + varb = 30\n 4 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\nncalls tottime percall cumtime percall filename:lineno\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 sum.py:3(<module>)\n 1 0.000 0.000 0.000 0.000 {execfile}\n 1 0.000 0.000 0.000 0.000 {method ......}", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}, {"id": "0290ebb0bd1650bb5f565f714478495f", "parent_id": null, "granularity": null, "adjacency": null, "blob": null, "tensor": null, "mime_type": null, "text": "The tabnanny module checks Python source files for ambiguous indentation. If a file mixes tabs and spaces in a way that throws off indentation, no matter what tab size you're using, the nanny complains \u2212", "weight": null, "uri": null, "tags": null, "offset": null, "location": null, "embedding": null, "modality": null, "evaluations": null, "scores": null, "chunks": null, "matches": null}]