What are Python Literals? Python literals or constants are the notation for representing a fixed value in source code. In contrast to variables, literals (123, 4.3, “Hello”) are static values or you can say constants which do not change throughout the operation of the program or application. For example, in the following assignment statement. Here 10 is a literal as numeric value representing 10, which is directly stored in memory. However, Here, even if the expression evaluates to 20, it is not literally included in source code. You can also declare an int object with built-in int() function. However, this is also an indirect way of instantiation and not with literal. Different Types of Python Literals Python provides following literals which will be explained this tutorial: Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Integer Literal Any representation involving only the digit symbols (0 to 9) creates an object of int type. The object so declared may be referred by a variable using an assignment operator. Integer literals consist three different types of different literal values decimal, octal, and hexadecimal literals. 1. Decimal Literal Decimal literals represent the signed or unsigned numbers. Digitals from 0 to 9 are used to create a decimal literal value. Look at the below statement assigning decimal literal to the variable − 2. Octal Literal Python allows an integer to be represented as an octal number or a hexadecimal number. A numeric representation with only eight digit symbols (0 to 7) but prefixed by 0o or 0O is an octal number in Python. Look at the below statement assigning octal literal to the variable − 3. Hexadecimal Literal Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or 0X represents an integer in Hexedecimal form in Python. Look at the below statement assigning hexadecimal literal to the variable − However, it may be noted that, even if you use octal or hexadecimal literal notation, Python internally treats them as of int type. Example Open Compiler When you run this code, it will produce the following output − Python Float Literal A floating point number consists of an integral part and a fractional part. Conventionally, a decimal point symbol (.) separates these two parts in a literal representation of a float. For example, Example of Float Literal For a floating point number which is too large or too small, where number of digits before or after decimal point is more, a scientific notation is used for a compact literal representation. The symbol E or e followed by positive or negative integer, follows after the integer part. Example of Float Scientific Notation Literal For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2 is equivalent to 0.0123 Open Compiler Here, you will get the following output − Python Complex Literal A complex number comprises of a real and imaginary component. The imaginary component is any number (integer or floating point) multiplied by square root of “-1” (√ −1). In literal representation (−1−−−√−1) is representation by “j” or “J”. Hence, a literal representation of a complex number takes a form x+yj. Example of Complex Type Literal Open Compiler This code will produce the following output − Python String Literal A string object is one of the sequence data types in Python. It is an immutable sequence of Unicode code points. Code point is a number corresponding to a character according to Unicode standard. Strings are objects of Python’s built-in class ‘str’. String literals are written by enclosing a sequence of characters in single quotes (‘hello’), double quotes (“hello”) or triple quotes (”’hello”’ or “””hello”””). Example of String Literal Open Compiler Here, you will get the following output − Example of String Literal With Double Quoted Inside String If it is required to embed double quotes as a part of string, the string itself should be put in single quotes. On the other hand, if single quoted text is to be embedded, string should be written in double quotes. Open Compiler It will produce the following output − Python List Literal List object in Python is a collection of objects of other data type. List is an ordered collection of items not necessarily of same type. Individual object in the collection is accessed by index starting with zero. Literal representation of a list object is done with one or more items which are separated by comma and enclosed in square brackets []. Example of List Type Literal Open Compiler It will produce the following output − Python Tuple Literal Tuple object in Python is a collection of objects of other data type. Tuple is an ordered collection of items not necessarily of same type. Individual object in the collection is accessed by index starting with zero. Literal representation of a tuple object is done with one or more items which are separated by comma and enclosed in parentheses (). Example of Tuple Type Literal Open Compiler It will produce the following output − Example of Tuple Type Literal Without Parenthesis Default delimiter for Python sequence is parentheses, which means a comma separated sequence without parentheses also amounts to declaration of a tuple. Open Compiler Here too, you will get the same output − Python Dictionary Literal Like list or tuple, dictionary is also a collection data type. However, it is not a sequence. It is an unordered collection of items, each of which is a key-value pair. Value is bound to key by the “:” symbol. One or more key:value pairs separated by comma are put inside curly brackets to form a dictionary object. Example of Dictionary Type Literal Open Compiler Key should be an immutable object. Number, string or tuple can be used as key. Key cannot appear more than once in one collection. If a key appears more than once, only the last one will be retained. Values can be of any data type. One value can be assigned to more than one keys. For example,
Unicode System
What is Unicode System? Software applications often require to display messages output in a variety in different languages such as in English, French, Japanese, Hebrew, or Hindi. Python’s string type uses the Unicode Standard for representing characters. It makes the program possible to work with all these different possible characters. A character is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. A unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes. Character Encoding A sequence of code points is represented in memory as a set of code units, mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a character encoding. Three types of encodings are present, UTF-8, UTF-16 and UTF-32. UTF stands for Unicode Transformation Format. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python’s Unicode Support Python 3.0 onwards has built-in support for Unicode. The str type contains Unicode characters, hence any string created using single, double or the triple-quoted string syntax is stored as Unicode. The default encoding for Python source code is UTF-8. Hence, string may contain literal representation of a Unicode character (3/4) or its Unicode value (\u00BE). Example Open Compiler This above code will produce the following output − Example In the following example, a string ’10’ is stored using the Unicode values of 1 and 0 which are \u0031 and u0030 respectively. Open Compiler It will produce the following output − Strings display the text in a human-readable format, and bytes store the characters as binary data. Encoding converts data from a character string to a series of bytes. Decoding translates the bytes back to human-readable characters and symbols. It is important not to confuse these two methods. encode is a string method, while decode is a method of the Python byte object. Example In the following example, we have a string variable that consists of ASCII characters. ASCII is a subset of Unicode character set. The encode() method is used to convert it into a bytes object. Open Compiler The decode() method converts byte object back to the str object. The encodeing method used is utf-8. Example In the following example, the Rupee symbol (₹) is stored in the variable using its Unicode value. We convert the string to bytes and back to str. Open Compiler When you execute the above code, it will produce the following output −
Type Casting
Python Type Casting From a programming point of view, a type casting refers to converting an object of one type into another. Here, we shall learn about type casting in Python Programming. Python Type Casting is a process in which we convert a literal of one data type to another data type. Python supports two types of casting − implicit and explicit. In Python there are different data types, such as numbers, sequences, mappings etc. There may be a situation where, you have the available data of one type but you want to use it in another form. For example, the user has input a string but you want to use it as a number. Python’s type casting mechanism let you do that. Python Implicit Casting When any language compiler/interpreter automatically converts object of one type into other, it is called automatic or implicit casting. Python is a strongly typed language. It doesn’t allow automatic type conversion between unrelated data types. For example, a string cannot be converted to any number type. However, an integer can be cast into a float. Other languages such as JavaScript is a weakly typed language, where an integer is coerced into a string for concatenation. Note that memory requirement of each data type is different. For example, an integer object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because of its fractional part. Hence, Python interpreter doesn’t automatically convert a float to int, because it will result in loss of data. On the other hand, int can be easily converted into float by setting its fractional part to 0. Implicit int to float casting takes place when any arithmetic operation on int and float operands is done. Consider we have an ,int and one float variable To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but equivalent to its earlier numeric value. Now we can perform addition of two floats. In implicit type casting, a Python object with lesser byte size is upgraded to match the bigger byte size of other object in the operation. For example, a Boolean object is first upgraded to int and then to float, before the addition with a floating point object. In the following example, we try to add a Boolean object in a float, pleae note that True is equal to 1, and False is equal to 0. Open Compiler This will produce the following result: Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Explicit Casting Although automatic or implicit casting is limited to int to float conversion, you can use Python’s built-in functions int(), float() and str() to perform the explicit conversions such as string to integer. Python int() Function Python’s built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer literal representation. Using int() with an int object as argument is equivalent to declaring an int object directly. is same as − If the argument to int() function is a float object or floating point expression, it returns an int object. For example − The int() function also returns integer 1 if a Boolean object is given as argument. String to Integer The int() function returns an integer from a string object, only if it contains a valid integer representation. However, if the string contains a non-integer representation, Python raises ValueError. The int() function also returns integer from binary, octal and hexa-decimal string. For this, the function needs a base parameter which must be 2, 8 or 16 respectively. The string should have a valid binary/octal/Hexa-decimal representation. Binary String to Integer The string should be made up of 1 and 0 only, and the base should be 2. The Decimal equivalent of binary number 110011 is 51. Octal String to Integer The string should only contain 0 to 7 digits, and the base should be 8. The Decimal equivalent of octal 20 is 16. Hexa-Decimal String to Integer The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F. Base should be 16. Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions with calculator app in Windows, Ubuntu or Smartphones. Following is an example to convert number, float and string into integer data type: Open Compiler This produce the following result − Python float() Function The float() is a built-in function in Python. It returns a float object if the argument is a float literal, integer or a string with valid floating point representation. Using float() with an float object as argument is equivalent to declaring a float object directly is same as − If the argument to float() function is an integer, the returned value is a floating point with fractional part set to 0. The float() function returns float object from a string, if the string contains a valid floating point number, otherwise ValueError is raised. The reason of ValueError here is the presence of comma in the string. For the purpose of string to float conversion, the sceientific notation of floating point is also considered valid. Following is an example to convert number, float and string into float data type: Open Compiler This produce the following result − Python str() Function We saw how a Python obtains integer or float number from corresponding string representation. The str() function works the opposite. It surrounds an integer or a float object with quotes (‘) to return a str object. The str() function returns the string representation of any Python object. In this section, we shall see different examples of str() function in Python. The str() function has three parameters. First required parameter (or argument) is the object whose string representation we want. Other two operators, encoding and errors, are optional. We shall execute str() function in Python console to easily verify that the returned object is a string, with the enclosing quotation marks (‘). Integer to string You can convert any integer number into a string as follows: Float to String str() function converts floating point objects with both the notations of floating point, standard notation with a decimal point separating integer and fractional part,
Data Types
Python Data Types Python data types are actually classes, and the defined variables are their instances or objects. Since Python is dynamically typed, the data type of a variable is determined at runtime based on the assigned value. In general, the data types are used to define the type of a variable. It represents the type of data we are going to store in a variable and determines what operations can be done on it. Each programming language has its own classification of data items. With these datatypes, we can store different types of data values. Types of Data Types in Python Python supports the following built-in data types − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 1. Python Numeric Data Types Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example − Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively − A complex number is made up of two parts – real and imaginary. They are separated by ‘+’ or ‘-‘ signs. The imaginary part is suffixed by ‘j’ which is the imaginary number. The square root of -1 (−1−−−√−1), is defined as imaginary number. Complex number in Python is represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a complex number. Here are some examples of numbers − int float complex 10 0.0 3.14j 0O777 15.20 45.j -786 -21.9 9.322e-36j 080 32.3+e18 .876j 0x17 -90. -.6545+0J -0x260 -32.54e100 3e+26J 0x69 70.2-E12 4.53e-7j Example of Numeric Data Types Following is an example to show the usage of Integer, Float and Complex numbers: Open Compiler 2. Python String Data Type Python string is a sequence of one or more Unicode characters, enclosed in single, double or triple quotation marks (also called inverted commas). Python strings are immutable which means when you perform an operation on strings, you always produce a new string object of the same type, rather than mutating an existing string. As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent. A string in Python is an object of str class. It can be verified with type() function. A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it. However, operations such as slicing and concatenation can be done. Python’s str class defines a number of useful methods for string processing. 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. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python. Example of String Data Type Open Compiler This will produce the following result − 3. Python Sequence Data Types Sequence is a collection data type. It is an ordered collection of items. Items in the sequence have a positional index starting with 0. It is conceptually similar to an array in C or C++. There are following three sequence data types defined in Python. Python sequences are bounded and iterable – Whenever we say an iterable in Python, it means a sequence data type (for example, a list). (a) Python List Data Type Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type. A list in Python is an object of list class. We can check it with type() function. As mentioned, an item in the list may be of any data type. It means that a list object can also be an item in another list. In that case, it becomes a nested list. A list can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined class also. The values stored in a Python 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. Example of List Data Type Open Compiler This produce the following result − (b) Python Tuple Data Type Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses (…). A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the collection. The index starts from 0. In Python, a tuple is an object of tuple class. We can check it with the type() function. As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python class. To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing symbols are treated as a tuple by default. Example of Tuple data Type Open Compiler This produce the following result − The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed i.e. lists are mutable, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as read-only lists. The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists − Open Compiler (c) Python Range Data Type A Python range is
Variables
Python Variables Python variables are the reserved memory locations used to store values with in a Python Program. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable, Python interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to Python variables, you can store integers, decimals or characters in these variables. Memory Addresses Data items belonging to different data types are stored in computer’s memory. Computer’s memory locations are having a number or address, internally represented in binary form. Data is also stored in binary form as the computer works on the principle of binary representation. In the following diagram, a string May and a number 18 is shown as stored in memory locations. If you know the assembly language, you will covert these data items and the memory address, and give a machine language instruction. However, it is not easy for everybody. Language translator such as Python interpreter performs this type of conversion. It stores the object in a randomly chosen memory location. Python’s built-in id() function returns the address where the object is stored. Once the data is stored in the memory, it should be accessed repeatedly for performing a certain process. Obviously, fetching the data from its ID is cumbersome. High level languages like Python make it possible to give a suitable alias or a label to refer to the memory location. In the above example, let us label the location of May as month, and location in which 18 is stored as age. Python uses the assignment operator (=) to bind an object with the label. The data object (May) and its name (month) have the same id(). The id() of 18 and age are also same. The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name that is a reference or pointer to an object. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Creating Python Variables Python variables do not need explicit declaration to reserve memory space or you can say to create a variable. A Python variable is created automatically when you assign a value to it. The equal sign (=) is used to assign values to variables. The 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 − Example to Create Python Variables This example creates different types (an integer, a float, and a string) of variables. Printing Python Variables Once we create a Python variable and assign a value to it, we can print it using print() function. Following is the extension of previous example and shows how to print different variables in Python: Example to Print Python Variables This example prints variables. Open Compiler Here, 100, 1000.0 and “Zara Ali” are the values assigned to counter, miles, and name variables, respectively. When running the above Python program, this produces the following result − Deleting Python Variables You can delete the reference to a number object by using the del statement. The syntax of the del statement is − You can delete a single object or multiple objects by using the del statement. For example − Example Following examples shows how we can delete a variable and if we try to use a deleted variable then Python interpreter will throw an error: Open Compiler counter =100print(counter)del counter print(counter) This will produce the following result: Getting Type of a Variable You can get the data type of a Python variable using the python built-in function type() as follows. Example: Printing Variables Type Open Compiler This will produce the following result: Casting Python Variables You can specify the data type of a variable with the help of casting as follows: Example This example demonstrates case sensitivity of variables. Open Compiler This will produce the following result: Case-Sensitivity of Python Variables Python variables are case sensitive which means Age and age are two different variables: Open Compiler This will produce the following result: Python Variables – Multiple Assignment Python allows to initialize more than one variables in a single statement. In the following case, three variables have same value. Instead of separate assignments, you can do it in a single assignment statement as follows − In the following case, we have three variables with different values. These separate assignment statements can be combined in one. You need to give comma separated variable names on left, and comma separated values on the right of = operator. Let’s try few examples in script mode: − Open Compiler This produces the following result: Here, 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 − Open Compiler This produces the following result: Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value “Zara Ali” is assigned to the variable c. Python Variables – Naming Convention Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. There are certain rules which should be taken care while naming a Python variable: If the name of variable contains multiple words, we should use these naming patterns − Example Following are valid Python variable names: Open Compiler This will produce the following result: Example Following are invalid Python variable names: Open Compiler This will produce the following result: Example Once you use a variable to identify a data object, it can be used repeatedly without its id() value. Here, we have a variables height and width of a rectangle. We can compute the area and perimeter with these variables. Use of variables is especially advantageous when writing scripts or programs. Following script also uses the above variables.
Syntax
Python – Syntax The Python syntax defines a set of rules that are used to create a Python Program. The Python Programming Language Syntax has many similarities to Perl, C, and Java Programming Languages. However, there are some definite differences between the languages. First Python Program Let us execute a Python program to print “Hello, World!” in two different modes of Python Programming. (a) Interactive Mode Programming (b) Script Mode Programming. Python – Interactive Mode Programming We can invoke a Python interpreter from command line by typing python at the command prompt as following − Here >>> denotes a Python Command Prompt where you can type your commands. Let’s type the following text at the Python prompt and press the Enter − If you are running older version of Python, like Python 2.4.x, then you would need to use print statement without parenthesis as in print “Hello, World!”. However in Python version 3.x, this produces the following result − Python – Script Mode Programming We can invoke the Python interpreter with a script parameter which begins the execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Python program in a script which is simple text file. Python files have extension .py. Type the following source code in a test.py file − Open Compiler We assume that you have Python interpreter path set in PATH variable. Now, let’s try to run this program as follows − This produces the following result − Let us try another way to execute a Python script. Here is the modified test.py file − Open Compiler We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows − This produces the following result − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Identifiers 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). Python 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. Here are naming conventions for Python identifiers − Python Reserved Words 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. and as assert break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield Python Lines and Indentation Python programming 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. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example − However, the following block generates an error − Open Compiler Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks − 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. Python Multi-Line Statements 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 − Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example following statement works well in Python − Quotations in Python 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. The triple quotes are used to span the string across multiple lines. For example, all the following are legal − Comments in Python A comment is a programmer-readable explanation or annotation in the Python source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Python interpreter Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. Python comments are very much similar to the comments available in PHP, BASH and Perl Programming languages. 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. Open Compiler This produces the following result − You can type a comment on the same line after a statement or expression − name =”Madisetti”# This is again comment You can comment multiple lines as follows − Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments: Using Blank Lines in Python Programs A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement. Waiting for the User The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action − Here, “\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. Multiple Statements on a Single Line 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 − Open Compiler Multiple
Virtual Environment
Python Virtual Environment Python virtual environments create a virtual installation of Python inside a project directory. Users can then install and manage Python packages for each project. This allows users to be able to install packages and modify their Python environment without fear of breaking packages installed in other environments. What is Virtual Environment in Python? A Python virtual environment is: When you install Python software on your computer, it is available for use from anywhere in the filesystem. This is a system-wide installation. While developing an application in Python, one or more libraries may be required to be installed using the pip utility (e.g., pip3 install somelib). Moreover, an application (let us say App1) may require a particular version of the library − say somelib 1.0. At the same time another Python application (for example App2) may require newer version of same library say somelib 2.0. Hence by installing a new version, the functionality of App1 may be compromised because of conflict between two different versions of same library. This conflict can be avoided by providing two isolated environments of Python in the same machine. These are called virtual environment. A virtual environment is a separate directory structure containing isolated installation having a local copy of Python interpreter, standard library and other modules. The following figure shows the purpose of advantage of using virtual environment. Using the global Python installation, more than one virtual environments are created, each having different version of the same library, so that conflict is avoided. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Creation of Virtual Environments in Python using venv This functionality is supported by venv module in standard Python distribution. Use following commands to create a new virtual environment. Here, myvenv is the folder in which a new Python virtual environment will be created showing following directory structure − The utilities for activating and deactivating the virtual environment as well as the local copy of Python interpreter will be placed in the scripts folder. Activating Virtual Environment To enable this new virtual environment, execute activate.bat in Scripts folder. Note the name of the virtual environment in the parentheses. The Scripts folder contains a local copy of Python interpreter. You can start a Python session in this virtual environment. Checking If Python is Running Inside a Virtual Environment? To confirm whether this Python session is in virtual environment check the sys.path. The scripts folder of this virtual environment also contains pip utilities. If you install a package from PyPI, that package will be active only in current virtual environment. Deactivating Virtual Environment To deactivate this environment, run deactivate.bat.
Environment Setup
First step in the journey of learning Python is to install it on your machine. Today most computer machines, especially having Linux OS, have Python pre-installed. However, it may not be the latest version. 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. Python has also been ported to the Java and .NET virtual machines Local Environment Setup Open a terminal window and type “python” to find out if it is already installed and which version is installed. If Python is already installed then you will get a message something like as follows: Downloading Python 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/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Installing Python 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. If 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. Here is a quick overview of installing Python on various platforms − Install Python on Ubuntu Linux To check whether Python is already installed, open the Linux terminal and enter the following command − In Ubuntu Linux, the easiest way to install Python is to use apt – Advanced Packaging Tool. It is always recommended to update the list of packages in all the configured repositories. Even after the update, the latest version of Python may not be available for install, depending upon the version of Ubuntu you are using. To overcome this, add the deadsnakes repository. Update the package list again. To install the latest Python 3.11 version, enter the following command in the terminal − Check whether it has been properly installed. Install Python on other Linux Here are the simple steps to install Python on Unix/Linux machine. Now issue the following commands: This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python. Using Yum Command Red Hat Enterprise Linux (RHEL 8) does not install Python 3 by default. We usually use yum command on CentOS and other related variants. The procedure for installing Python-3 on RHEL 8 is as follows: $ sudo yum install python3 Install Python on Windows It should be noted that Python’s version 3.10 onwards cannot be installed on Windows 7 or earlier operating systems. The recommended way to install Python is to use the official installer. A link to the latest stable version is given on the home page itself. It is also found at https://www.python.org/downloads/windows/. You can find embeddable packages and installers for 32 as well as 64-bit architecture. Let us download 64-bit Windows installer − (https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe) Double click on the file where it has been downloaded to start the installation. Although you can straight away proceed by clicking the Install Now button, it is advised to choose the installation folder with a relatively shorter path, and tick the second check box to update the PATH variable. Accept defaults for rest of the steps in this installation wizard to complete the installation. Open the Window Command Prompt terminal and run Python to check the success of installation. C:\Users\Acer>python Python 3.11.2(tags/v3.11.2:878ead1, Feb 72023,16:38:35)[MSC v.193464 bit (AMD64)] on win32 Type “help”,”copyright”,”credits”or”license”for more information.>>> Python’s standard library has an executable module called IDLE – short for Integrated Development and Learning Environment. Find it from Window start menu and launch. IDLE contains Python shell (interactive interpreter) and a customizable multi-window text editor with features such as syntax highlighting, smart indent, auto completion etc. It is cross-platform so works the same on Windows, MacOS and Linux. It also has a debugger with provision to set breakpoints, stepping, and viewing of global and local namespaces. Here are the steps to install Python on Windows machine. Macintosh Installation 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. Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation. Setting up PATH 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. The 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. The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). In 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. Setting path at Unix/Linux To add the Python directory to the path for a particular session in Unix − Setting path at Windows To add the Python directory to the path for a particular session in Windows − At the command prompt − type path %path%;C:\Python and press Enter. Note − C:\Python is the path of the Python directory Python Environment Variables Here are important environment variables, which can be recognized by Python − Sr.No. Variable & Description 1 PYTHONPATHIt 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. 2 PYTHONSTARTUPIt contains the path of an initialization file
Python Interpreter and Its Modes
Python is an interpreter-based language. In a Linux system, Python’s executable is installed in /usr/bin/ directory. For Windows, the executable (python.exe) is found in the installation folder (for example C:\python311). This tutorial will teach you How Python Interpreter Works in interactive and scripted mode. Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism: Python interpreter has an interactive mode and a scripted mode. Python Interpreter – Interactive Mode When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the principle of REPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows. To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press Enter to return to the OS prompt. The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreter software such as IPython and bpython to have additional functionalities. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python Interpreter – Scripting Mode Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has .py extension, and use the name as the command line parameter for Python command. Save the following lines as prog.py, with the use of any text editor such as vim on Linux or Notepad on Windows. Open Compiler When we execute above program on a Windows machine, it will produce following result: Note that even though Python executes the entire script in one go, but internally it is still executed in line by line fashion. In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until first occurrence of error is encountered. Let us introduce an error purposefully in the above code. Open Compiler Note the misspelt variable prive instead of price. Try to execute the script again as before − Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in interpreted manner. Python Interpreter – Using Shebang #! In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add a shebang line on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with #! And followed by the path to Python executable. Modify the prog.py script as follows − Open Compiler To mark the script as self-executable, use the chmod command You can now execute the script directly, without using it as a command-line argument. Interactive Python – IPython IPython (stands for Interactive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001. IPython has the following important features − Install IPython with PIP installer utility. Launch IPython from command-line Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below − Tab completion is one of the most useful enhancements provided by IPython. IPython pops up appropriate list of methods as you press tab key after dot in front of object. IPython provides information (introspection) of any object by putting ? in front of it. It includes docstring, function definitions and constructor details of class. For example to explore the string object var defined above, in the input prompt enter var?. IPython’s magic functions are extremely powerful. Line magics let you run DOS commands inside IPython. Let us run the dir command from within IPython console Jupyter notebook is a web-based interface to programming environments of Python, Julia, R and many others. For Python, it uses IPython as its main kernel. Print Page
Application Areas
Python is a general-purpose programming language. It is suitable for the development of a wide range of software applications. Over the last few years Python has been the preferred language of choice for developers in the following application areas − Let’s look into these application areas in more detail: Data Science Python’s recent meteoric rise in the popularity charts is largely due to its Data science libraries. Python has become an essential skill for data scientists. Today, real time web applications, mobile applications and other devices generate huge amount of data. Python’s data science libraries help companies generate business insights from this data. Libraries like NumPy, Pandas, and Matplotlib are extensively used to apply mathematical algorithms to the data and generate visualizations. Commercial and community Python distributions like Anaconda and ActiveState bundle all the essential libraries required for data science. Machine Learning Python libraries such as Scikit-learn and TensorFlow help in building models for prediction of trends like customer satisfaction, projected values of stocks etc. based upon the past data. Machine learning applications include (but not restricted to) medical diagnosis, statistical arbitrage, basket analysis, sales prediction etc. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Web Development Python’s web frameworks facilitate rapid web application development. Django, Pyramid, Flask are very popular among the web developer community. etc. make it very easy to develop and deploy simple as well as complex web applications. Latest versions of Python provide asynchronous programming support. Modern web frameworks leverage this feature to develop fast and high performance web apps and APIs. Computer Vision and Image processing OpenCV is a widely popular library for capturing and processing images. Image processing algorithms extract information from images, reconstruct image and video data. Computer Vision uses image processing for face detection and pattern recognition. OpenCV is a C++ library. Its Python port is extensively used because of its rapid development feature. Some of the application areas of computer vision are robotics, industrial surveillance, automation, and biometrics etc. Embedded Systems and IoT Micropython (https://micropython.org/), a lightweight version especially for microcontrollers like Arduino. Many automation products, robotics, IoT, and kiosk applications are built around Arduino and programmed with Micropython. Raspberry Pi is also very popular alow cost single board computer used for these type of applications. Job Scheduling and Automation Python found one of its first applications in automating CRON (Command Run ON) jobs. Certain tasks like periodic data backups, can be written in Python scripts scheduled to be invoked automatically by operating system scheduler. Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros). Desktop GUI Applications Python is a great option for building ergonomic, attractive, and user-friendly desktop GUI applications. Several graphics libraries, though built in C/C++, have been ported to Python. The popular Qt graphics toolkit is available as a PyQt package in Python. Similarly, WxWidgets has been ported to Python as WxPython. Python’s built-in GUI package, TKinter is a Python interface to the Tk Graphics toolkit. Here is a select list of Python GUI libraries: Console-based Applications Python is often employed to build CLI (command-line interface) applications. Such scripts can be used to run scheduled CRON jobs such as taking database backups etc. There are many Python libraries that parse the command line arguments. The argparse library comes bundled with Python’s standard library. You can use Click (part of Flask framework) and Typer (included in FastAPI framework) to build console interfaces to the web-based applications built by the respective frameworks. Textual is a rapid development framework to build apps that run inside a terminal as well as browsers. CAD Applications CAD engineers can take advantage of Python’s versatility to automate repetitive tasks such as drawing shapes and generating reports. Autodesk Fusion 360 is a popular CAD software, which has a Python API that allows users to automate tasks and create custom tools. Similarly, SolidWorks has a built-in Python shell that allows users to run Python scripts inside the software. CATIA is another very popular CAD software. Along with a VBScript, certain third-party Python libraries that can be used to control CATIA. Game Development Some popular gaming apps have been built with Python. Examples include BattleField2, The Sims 4, World of Tanks, Pirates of the Caribbean, and more. These apps are built with one of the following Python libraries. Pygame is one of the most popular Python libraries used to build engaging computer games. Pygame is an open-source Python library for making multimedia applications like games built on top of the excellent SDL library. It is a cross-platform library, which means you can build a game that can run on any operating system platform. Another library Kivy is also widely used to build desktop as well as mobile-based games. Kivy has a multi-touch interface. It is an open-source and cross-platform Python library for rapid development of game applications. Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi. PyKyra library is based on both SDL (Software and Documentation Localisation) and the Kyra engine. It is one of the fastest game development frameworks. PyKyra supports MPEG , MP3, Ogg Vorbis, Wav, etc., multimedia formats.