| Start |
|---|
| Getting Started Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. Python features a dynamic type system and automatic memory management and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library. Two major versions of Python are currently in active use:
You can download and install either version of Python here (opens new window). See Python 3 vs. Python 2 (opens new window) for a comparison between them. In addition, some third-parties offer re-packaged versions of Python that add commonly used libraries and other features to ease setup for common use cases, such as math, data analysis or scientific use. See the list at the official site (opens new window). Verify if Python is installedTo confirm that Python was installed correctly, you can verify that by running the following command in your favorite terminal (If you are using Windows OS, you need to add path of python to the environment variable before using it in command prompt): If you have Python 3 installed, and it is your default version (see Troubleshooting (opens new window) for more details) you should see something like this: If you have Python 2 installed, and it is your default version (see Troubleshooting (opens new window) for more details) you should see something like this: If you have installed Python 3, but Hello, World in Python using IDLEIDLE (opens new window) is a simple editor for Python, that comes bundled with Python. How to create Hello, World program in IDLE
In the shell, there is a prompt of three right angle brackets: Now write the following code in the prompt: Hit Enter. Hello World Python fileCreate a new file You can use the Python 3 Python 2 has a number of functionalities that can be optionally imported from Python 3 using the If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not recommended because it reduces cross-version code compatibility. In your terminal, navigate to the directory containing the file Type You should see You can also substitute Launch an interactive Python shellBy executing (running) the If you want to run Python 3 from your terminal, execute the command Alternatively, start the interactive prompt and load file with In command line, run: There are multiple ways to close the Python shell: or Alternatively, CTRL + D will close the shell and put you back on your terminal's command line. If you want to cancel a command you're in the middle of typing and get back to a clean command prompt, while staying inside the Interpreter shell, use CTRL + C. Try an interactive Python shell online (opens new window). Other Online ShellsVarious websites provide online access to Python shells. Online shells may be useful for the following purposes: Examples: Disclaimer: documentation author(s) are not affiliated with any resources listed below. Run commands as a stringPython can be passed arbitrary code as a string in the shell: This can be useful when concatenating the results of scripts together in the shell. Shells and BeyondPackage Management - The PyPA recommended tool for installing Python packages is PIP (opens new window). To install, on your command line execute Shells - So far, we have discussed different ways to run code using Python's native interactive shell. Shells use Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE (opens new window) - a pre-bundled GUI, IPython (opens new window) - known for extending the interactive experience, etc. Programs - For long-term storage you can save content to .py files and edit/execute them as scripts or programs with external tools e.g. shell, IDEs (opens new window) (such as PyCharm (opens new window)), Jupyter notebooks (opens new window), etc. Intermediate users may use these tools; however, the methods discussed here are sufficient for getting started. Python tutor (opens new window) allows you to step through Python code so you can visualize how the program will flow, and helps you to understand where your program went wrong. PEP8 (opens new window) defines guidelines for formatting Python code. Formatting code well is important so you can quickly read what the code does. |
| Creating variables and assigning values To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it. Python uses Variable assignment works from left to right. So the following will give you an syntax error. You can not use python's keywords as a valid variable name. You can see the list of keyword by: Rules for variable naming:
Even though there's no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in type (opens new window) for it: Now you know the basics of assignment, let's get this subtlety about assignment in python out of the way. When you use That is: So, from many assignment examples above, if we pick You can assign multiple values to multiple variables in one line. Note that there must be the same number of arguments on the right and left sides of the The error in last example can be obviated by assigning remaining values to equal number of arbitrary variables. This dummy variable can have any name, but it is conventional to use the underscore ( Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack error' is thrown as above: You can also assign a single value to several variables simultaneously. When using such cascading assignment, it is important to note that all three variables The above is also true for mutable types (like So far so good. Things are a bit different when it comes to modifying the object (in contrast to assigning the name to a different object, which we did above) when the cascading assignment is used for mutable types. Take a look below, and you will see it first hand: Nested lists are also valid in python. This means that a list can contain another list as an element. Lastly, variables in Python do not have to stay the same type as which they were first defined -- you can simply use If this bothers you, think about the fact that what's on the left of |
| Block Indentation Python uses indentation to define control and loop constructs. This contributes to Python's readability, however, it requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration could result in code that behaves in unexpected ways. Python uses the colon symbol ( For example: or Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style: Attempting to do this with more than a single statement will not work: An empty block causes an Spaces vs. TabsIn short: always use 4 spaces for indentation. Using tabs exclusively is possible but PEP 8 (opens new window), the style guide for Python code, states that spaces are preferred. Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated: Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces (opens new window). Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs. Citing PEP 8 (opens new window): When invoking the Python 2 command line interpreter with the Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the Tab key.
Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8 (opens new window). (A less powerful alternative comes with most Python installations: reindent.py (opens new window)) |
Datatypes Built-in TypesBooleans
In Python 2.x and in Python 3.x, a boolean is also an If boolean values are used in arithmetic operations, their integer values ( NumbersIntegers in Python are of arbitrary sizes.
Note: in older versions of Python, a float: Floating point number; precision depends on the implementation and system architecture, for CPython the float datatype corresponds to a C double. The Strings
Sequences and collectionsPython differentiates between ordered sequences and unordered collections (such as Supports indexing; immutable; hashable if all its members are hashable list: An ordered collection of n values (n >= 0) Not hashable; mutable. set: An unordered collection of unique values. Items must be hashable (opens new window). An object is hashable if it has a hash value which never changes during its lifetime (it needs a Built-in constantsIn conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:
Testing the type of variablesIn python, we can check the datatype of an object using the built-in function In conditional statements it is possible to test the datatype with For information on the differences between To test if something is of Converting between datatypesYou can perform explicit datatype conversion. For example, '123' is of Converting from a float string such as '123.456' can be done using You can also convert sequence or collection types Explicit string type at definition of literalsWith one letter labels just in front of the quotes you can tell what type of string you want to define.
Mutable and Immutable Data TypesAn object is called mutable if it can be changed. For example, when you pass a list to some function, the list can be changed: An object is called immutable if it cannot be changed in any way. For example, integers are immutable, since there's no way to change them: Note that variables themselves are mutable, so we can reassign the variable Data types whose instances are mutable are called mutable data types, and similarly for immutable objects and datatypes. Examples of immutable Data Types:
Examples of mutable Data Types:
|
| Collection Types There are a number of collection types in Python. While types such as Lists The A list can be empty: The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language: A list can contain another list as its element: The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on: Indices can also be negative which means counting from the end of the list ( Lists are mutable, so you can change the values in a list: Besides, it is possible to add and/or remove elements from a list: Append object to end of list with Add a new element to list at a specific index. Remove the first occurrence of a value with Get the index in the list of the first item whose value is x. It will show an error if there is no such item. Count length of list count occurrence of any item in list Reverse the list Remove and return item at index (defaults to the last item) with You can iterate over the list elements like below: Tuples A The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid Python valid. A tuple with only one member must be defined (note the comma) this way: or or just using Dictionaries A To get a value, refer to it by its key: You can also get all of the keys in a dictionary and then iterate over them: Dictionaries strongly resemble JSON syntax. The native set A Defining a Or you can build a Check membership of the You can iterate over a defaultdict A A For example, consider the following dictionary If we try to access a non-existent key, python returns us an error as follows Let us try with a What we did here is to set a default value (Boston) in case the give key does not exist. Now populate the dict as before: If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston and returns the created values for existing key just like a normal |
| IDLE - Python GUI IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the command line. As the name may imply, IDLE is very useful for developing new code or learning python. On Windows this comes with the Python interpreter, but in other operating systems you may need to install it through your package manager. The main purposes of IDLE are:
In IDLE, hit Note that there are lots of alternatives, see for example this discussion (opens new window) or this list (opens new window). Troubleshooting |
| User Input Interactive input To get input from the user, use the Security Remark Do not use The remainder of this example will be using Python 3 syntax. The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a prompt, waiting for the user to input. If the user types "Bob" and hits enter, the variable Note that the NB: It's recommended to use |
| Built in Modules and Functions A module is a file containing Python definitions and statements. Function is a piece of code which execute some logic. To check the built in function in python we can use To know the functionality of any function, we can use built in function Built in modules contains extra functionalities.For example to get square root of a number we need to include To know all the functions in a module we can assign the functions list to a variable, and then print the variable. it seems In addition to functions, documentation can also be provided in modules. So, if you have a file named You can access its docstrings like this: Any data type can be simply converted to string using a builtin function called |
| Creating a module A module is an importable file containing definitions and statements. A module can be created by creating a Functions in a module can be used by importing the module. For modules that you have made, they will need to be in the same directory as the file that you are importing them into. (However, you can also put them into the Python lib directory with the pre-included modules, but should be avoided if possible.) Modules can be imported by other modules. Specific functions of a module can be imported. Modules can be aliased. A module can be stand-alone runnable script. Run it! If the module is inside a directory and needs to be detected by python, the directory should contain a file named |
| Installation of Python 2.7.x and 3.x Note: Following instructions are written for Python 2.7 (unless specified): instructions for Python 3.x are similar. WINDOWS First, download the latest version of Python 2.7 from the official Website (https://www.python.org/downloads/) (opens new window)). Version is provided as an MSI package. To install it manually, just double-click the file. By default, Python installs to a directory: Warning: installation does not automatically modify the PATH environment variable. Assuming that your Python installation is in C:\Python27, add this to your PATH: Now to check if Python installation is valid write in cmd: Python 2.x and 3.x Side-By-Side To install and use both Python 2.x and 3.x side-by-side on a Windows machine:
Python 3 will install the Python launcher which can be used to launch Python 2.x and Python 3.x interchangeably from the command-line: To use the corresponding version of LINUX The latest versions of CentOS, Fedora, Redhat Enterprise (RHEL) and Ubuntu come with Python 2.7. To install Python 2.7 on linux manually, just do the following in terminal: Also add the path of new python in PATH environment variable. If new python is in Now to check if Python installation is valid write in terminal: Ubuntu (From Source) If you need Python 3.6 you can install it from source as shown below (Ubuntu 16.10 and 17.04 have 3.6 version in the universal repository). Below steps have to be followed for Ubuntu 16.04 and lower versions: macOS As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly modified from the regular Python. The version of Python that ships with OS X is great for learning but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. ([source](http://docs.python-guide.org/en/latest/starting/install/osx/)) Install Homebrew (opens new window): Install Python 2.7: For Python 3.x, use the command |
| String function - str() and repr() There are two functions that can be used to obtain a readable representation of an object.
repr()For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to str()For strings, this returns the string itself. The difference between this and Example 1: Example 2: When writing a class, you can override these methods to do whatever you want: Using the above class we can see the results: |
| Installing external modules using pip
On instances with both Python 2 and Python 3 installed, Finding / installing a packageSearching for a package is as simple as typing Installing a package is as simple as typing (in a terminal / command-prompt, not in the Python interpreter) where When your server is behind proxy, you can install package by using below command: Upgrading installed packagesWhen new versions of installed packages appear they are not automatically installed to your system. To get an overview of which of your installed packages have become outdated, run: To upgrade a specific package use Updating all outdated packages is not a standard functionality of Upgrading pipYou can upgrade your existing pip installation by using the following commands You may need to use or For more information regarding pip do read here (opens new window). |
| Help Utility Python has several functions built into the interpreter. If you want to get information of keywords, built-in functions, modules or topics open a Python console and enter: You will receive information by entering keywords directly: or within the utility: which will show an explanation: You can also request subclasses of modules: You can use help to access the docstrings of the different modules you have imported, e.g., try the following: and you'll get an error And now you will get a list of the available methods in the module, but only AFTER you have imported it. Close the helper with Remarks
Its design principles are outlined in The Zen of Python (opens new window). Currently, there are two major release branches of Python which have some significant differences. Python 2.x is the legacy version though it still sees widespread use. Python 3.x makes a set of backwards-incompatible changes which aim to reduce feature duplication. For help deciding which version is best for you, see this article (opens new window). The official Python documentation (opens new window) is also a comprehensive and useful resource, containing documentation for all versions of Python as well as tutorials to help get you started. There is one official implementation of the language supplied by Python.org, generally referred to as CPython, and several alternative implementations of the language on other runtime platforms. These include IronPython (opens new window) (running Python on the .NET platform), Jython (opens new window) (on the Java runtime) and PyPy (opens new window) (implementing Python in a subset of itself). |
Read Article
https://develop.horje.com/learn/1434/reference