{"id":21879353,"url":"https://github.com/animator/learn-python","last_synced_at":"2025-04-04T20:15:24.718Z","repository":{"id":62980141,"uuid":"545792101","full_name":"animator/learn-python","owner":"animator","description":"📖🐍 Free \u0026 Open Source book to master Python 3. Also available: PDF \u0026 Web Interface.","archived":false,"fork":false,"pushed_at":"2024-05-22T21:58:39.000Z","size":3164,"stargazers_count":279,"open_issues_count":177,"forks_count":139,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-05-22T21:59:10.240Z","etag":null,"topics":["gssoc","learn-python","python","python3"],"latest_commit_sha":null,"homepage":"https://animator.github.io/learn-python/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"cc-by-sa-4.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/animator.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-05T01:34:48.000Z","updated_at":"2024-05-31T01:28:54.515Z","dependencies_parsed_at":"2024-05-22T21:56:12.616Z","dependency_job_id":"6812d858-8a88-4770-abab-a6a7e545e9a8","html_url":"https://github.com/animator/learn-python","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/animator%2Flearn-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/animator%2Flearn-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/animator%2Flearn-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/animator%2Flearn-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/animator","download_url":"https://codeload.github.com/animator/learn-python/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247242681,"owners_count":20907134,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gssoc","learn-python","python","python3"],"created_at":"2024-11-28T08:16:03.662Z","updated_at":"2025-04-04T20:15:24.691Z","avatar_url":"https://github.com/animator.png","language":"Python","funding_links":[],"categories":["hacktoberfest"],"sub_categories":[],"readme":"[![Discord Server Invite](https://img.shields.io/badge/DISCORD-JOIN%20SERVER-5663F7?style=for-the-badge\u0026logo=discord\u0026logoColor=white)](https://bit.ly/heyfoss)\n\nContributors should go through the [Contributing Guide](https://github.com/animator/learn-python/blob/main/CONTRIBUTING.md) to learn how you can contribute to the project.\n\n![Learn Python 3 Logo](images/learn-python.png)\n\nLearn Python 3\n=================\nby **Ankit Mahato** [[About](https://animator.github.io)]  \n*Version 2022.10*\n\n# How to read this book?\n\nThis book can be consumed in 3 ways:\n\n- A nice web interface - [Link](https://animator.github.io/learn-python/)\n![Learn Python 3 Website](images/web.png)\n- A Downloadable PDF - [Link](https://github.com/animator/learn-python/raw/main/pdf/learn-python-v2022.10.pdf)\n![Learn Python 3 PDF](images/pdf.png)\n- Directly on GitHub - [Link](https://github.com/animator/learn-python)\n\n\nTable of Contents\n=================\n\n* [Introduction](#introduction)\n   * [Introduction to Programming Languages](#introduction-to-programming-languages)\n   * [Introduction to Python](#introduction-to-python)\n   * [Advantages of Python](#advantages-of-python)\n   * [Installing Python in Windows](#installing-python-in-windows)\n   * [Installing Python in macOS (Apple)](#installing-python-in-macos-apple)\n   * [Execution Modes](#execution-modes)\n   * [Interactive Mode of Execution](#interactive-mode-of-execution)\n   * [Script Mode of Execution](#script-mode-of-execution)\n* [Python Fundamentals](#python-fundamentals)\n   * [Tokens: Introduction](#tokens-introduction)\n   * [Tokens: Keywords](#tokens-keywords)\n   * [Tokens: Identifiers](#tokens-identifiers)\n   * [Tokens: Literals](#tokens-literals)\n   * [Tokens: Operators](#tokens-operators)\n   * [Tokens: Delimiters](#tokens-delimiters)\n   * [Character Set](#character-set)\n   * [Blocks and Indentation](#blocks-and-indentation)\n   * [Comments](#comments)\n* [Variables, Objects \u0026amp; Data Types](#variables-objects--data-types)\n   * [What are Objects \u0026amp; Variables?](#what-are-objects--variables)\n   * [Variables \u0026amp; Assignment Statements](#variables--assignment-statements)\n   * [Built-in Data Types](#built-in-data-types)\n   * [Type Checking](#type-checking)\n   * [Type Casting](#type-casting)\n      * [Implicit Type Casting](#implicit-type-casting)\n      * [Explicit Type Casting](#explicit-type-casting)\n   * [Mutable \u0026amp; Immutable Data Types](#mutable--immutable-data-types)\n      * [Immutable Data Types](#immutable-data-types)\n      * [Mutable Data Types](#mutable-data-types)\n* [Input / Output](#input--output)\n   * [How to Accept User Input](#how-to-accept-user-input)\n   * [Displaying Output](#displaying-output)\n* [Operators \u0026amp; Expressions](#operators--expressions)\n   * [Introduction to Operators](#introduction-to-operators)\n   * [Arithmetic Operators](#arithmetic-operators)\n   * [Relational Operators](#relational-operators)\n   * [Assignment Operators](#assignment-operators)\n   * [Logical Operators](#logical-operators)\n   * [Identity Operators](#identity-operators)\n   * [Membership Operators](#membership-operators)\n   * [Expressions](#expressions)\n   * [Operator Precedence with Examples](#operator-precedence-with-examples)\n* [Errors \u0026amp; Exception Handling](#errors--exception-handling)\n   * [Error Types](#error-types)\n   * [Syntax Error](#syntax-error)\n   * [Runtime Error](#runtime-error)\n   * [Logical Error](#logical-error)\n   * [Exceptions](#exceptions)\n   * [Exception Handling](#exception-handling)\n* [Control Flow](#control-flow)\n   * [Introduction to Control Flow](#introduction-to-control-flow)\n   * [Sequential Flow](#sequential-flow)\n   * [Selection Statements: if .. else](#selection-statements-if--else)\n   * [Iteration: for](#iteration-for)\n   * [Iteration: while](#iteration-while)\n   * [Jump Statements](#jump-statements)\n      * [pass](#pass)\n      * [break](#break)\n      * [continue](#continue)\n   * [Nested Loops](#nested-loops)\n* [Strings](#strings)\n   * [Strings: Introduction \u0026amp; Creation](#strings-introduction--creation)\n   * [Accessing Characters of a String](#accessing-characters-of-a-string)\n   * [String Operations](#string-operations)\n   * [Introduction to String Methods](#introduction-to-string-methods)\n   * [Convert Case of Strings](#convert-case-of-strings)\n   * [Check Characters of a String](#check-characters-of-a-string)\n   * [Split a String](#split-a-string)\n   * [Strip Characters from a String](#strip-characters-from-a-string)\n   * [Check Prefix or Suffix in a String](#check-prefix-or-suffix-in-a-string)\n   * [Find \u0026amp; Replace Characters in a String](#find--replace-characters-in-a-string)\n   * [Traversing a String](#traversing-a-string)\n* [List](#list)\n   * [What is a Python List? How to Create a List?](#what-is-a-python-list-how-to-create-a-list)\n   * [Accessing Items of a List](#accessing-items-of-a-list)\n      * [Negative Indexing](#negative-indexing)\n   * [Modifying a List](#modifying-a-list)\n   * [Removing Item from a List](#removing-item-from-a-list)\n   * [List Operations](#list-operations)\n   * [Traversing a List](#traversing-a-list)\n   * [Built-in Functions that can be used for a List](#built-in-functions-that-can-be-used-for-a-list)\n   * [Introduction to List Methods](#introduction-to-list-methods)\n   * [Adding Items to a List](#adding-items-to-a-list)\n   * [Removing Items from a List](#removing-items-from-a-list)\n   * [Counting or Locating Items in a List](#counting-or-locating-items-in-a-list)\n   * [Reversing Items](#reversing-items)\n   * [Sorting a List](#sorting-a-list)\n   * [Copying a List](#copying-a-list)\n   * [Nested List](#nested-list)\n   * [List Comprehension](#list-comprehension)\n      * [Member-wise Operation](#member-wise-operation)\n      * [Filtering or Subsequence](#filtering-or-subsequence)\n   * [Sample Programs](#sample-programs)\n* [Tuple](#tuple)\n   * [List vs Tuple](#list-vs-tuple)\n   * [How to Create Tuple?](#how-to-create-tuple)\n   * [What is a Singleton?](#what-is-a-singleton)\n   * [Accessing Items of a Tuple](#accessing-items-of-a-tuple)\n   * [Tuples are Immutable](#tuples-are-immutable)\n   * [Tuple Operations](#tuple-operations)\n   * [Traversing a Tuple](#traversing-a-tuple)\n   * [Built-in Functions that can be used for a Tuple](#built-in-functions-that-can-be-used-for-a-tuple)\n   * [Locating Items in a Tuple](#locating-items-in-a-tuple)\n   * [Counting the Occurrence of an Item](#counting-the-occurrence-of-an-item)\n   * [New Tuple with Reversed Items](#new-tuple-with-reversed-items)\n   * [New Tuple with Sorted Items](#new-tuple-with-sorted-items)\n   * [Nested Tuple](#nested-tuple)\n   * [Understanding the Immutable Nature of Tuples](#understanding-the-immutable-nature-of-tuples)\n* [Dictionary](#dictionary)\n   * [What is a Dictionary?](#what-is-a-dictionary)\n   * [How to Create a Dictionary](#how-to-create-a-dictionary)\n      * [Key: Value Pairs](#key-value-pairs)\n      * [Sequence of (key, value) Tuples](#sequence-of-key-value-tuples)\n      * [Keyword/Named Arguments](#keywordnamed-arguments)\n      * [Key and Value Lists](#key-and-value-lists)\n      * [Keys with Default Value](#keys-with-default-value)\n   * [Accessing Items (Key:Value) of a Dictionary](#accessing-items-keyvalue-of-a-dictionary)\n   * [Updating a Dictionary](#updating-a-dictionary)\n   * [Removing an Item (Key:Value) from a Dictionary](#removing-an-item-keyvalue-from-a-dictionary)\n   * [Dictionary Operations](#dictionary-operations)\n   * [Traversing a Dictionary](#traversing-a-dictionary)\n   * [Built-in Functions for a Dictionary](#built-in-functions-for-a-dictionary)\n   * [Creating a Copy of a Dictionary](#creating-a-copy-of-a-dictionary)\n   * [Nested Dictionary](#nested-dictionary)\n   * [Sample Programs](#sample-programs-1)\n* [Python Standard Library](#python-standard-library)\n   * [Built-in Functions](#built-in-functions)\n   * [Mathematical Functions](#mathematical-functions)\n   * [Type Functions](#type-functions)\n      * [Type Checking](#type-checking-1)\n      * [Built-in Type Functions](#built-in-type-functions)\n   * [I/O Functions](#io-functions)\n   * [Base/Unicode Conversion Functions](#baseunicode-conversion-functions)\n   * [What are Built-in Modules?](#what-are-built-in-modules)\n   * [math Module](#math-module)\n      * [Constants](#constants)\n      * [Functions](#functions)\n   * [random Module](#random-module)\n   * [statistics Module](#statistics-module)\n* [File Handling](#file-handling)\n   * [File Handling in Python - Introduction \u0026amp; Overview](#file-handling-in-python---introduction--overview)\n   * [Text Files vs Binary Files - Use Case, File Formats, Examples](#text-files-vs-binary-files---use-case-file-formats-examples)\n   * [File Opening \u0026amp; Closing](#file-opening--closing)\n   * [File Reading](#file-reading)\n      * [Sequential Reading](#sequential-reading)\n      * [Ad-hoc Reading](#ad-hoc-reading)\n   * [Writing a File](#writing-a-file)\n   * [Reading \u0026amp; Writing Binary Files using pickle Module](#reading--writing-binary-files-using-pickle-module)\n      * [Dumping Data](#dumping-data)\n      * [Loading Data](#loading-data)\n      * [Example: Traversing a Binary File](#example-traversing-a-binary-file)\n   * [Reading \u0026amp; Writing a CSV File using csv Module](#reading--writing-a-csv-file-using-csv-module)\n      * [Reading CSV File](#reading-csv-file)\n      * [Writing CSV File](#writing-csv-file)\n* [User Defined Functions, Modules \u0026amp; Packages](#user-defined-functions-modules--packages)\n   * [User Defined Functions](#user-defined-functions)\n   * [Function Structure](#function-structure)\n      * [Function Header](#function-header)\n      * [Function Body](#function-body)\n   * [Parameters and Arguments](#parameters-and-arguments)\n   * [Scope of Variables](#scope-of-variables)\n      * [Local Variables](#local-variables)\n      * [Global Variables](#global-variables)\n   * [Passing Objects of Mutable Type to a Function](#passing-objects-of-mutable-type-to-a-function)\n      * [Passing a List](#passing-a-list)\n      * [Passing a Dictionary](#passing-a-dictionary)\n   * [What is a Module? How to Create a Module?](#what-is-a-module-how-to-create-a-module)\n   * [Executable Scripts / Modules](#executable-scripts--modules)\n   * [What is a Package? Introduction to PyPi. How to Create a Python Package?](#what-is-a-package-introduction-to-pypi-how-to-create-a-python-package)\n\n# Introduction\n\n## Introduction to Programming Languages\n\nIn today's digital era, we depend on computers, smartphones and the internet to perform a plethora of tasks, like:\n\n- A mathematical task, such as finding the square root of a number or solving a set of simultaneous equations.\n- A text-based task such as reading a document and performing search/replace.\n- Streaming and playing multimedia files containing audio and video.\n- Using a search engine to find and visit a website.\n- Playing an online multiplayer game with friends.\n- and many more...\n\nSoftwares play an important role as they translate human activity into corresponding machine instructions which are executed to accomplish these tasks. \n\nA **software** is a collection of programs where each program provides a sequence of instructions specifying how the computer should act. \n\nThese instructions have to be provided in **machine language** or **low level language** (0s and 1s) that is difficult to read or write for a human being. \n\nThis led to the invention of **high-level programming languages** in which programs can be easily written and managed. The human-readable programs written using high-level languages are converted into computer-readable machine code or byte-code using **compilers** or **interpreters**.\n\nThere are many high-level programming languages that are currently in wide use. \n\nSome of the popular languages are Java, C, C++, C#, Go, Swift, JavaScript, PHP, Dart, Kotlin and Python.\n\n## Introduction to Python\n\nGuido van Rossum started the development of Python in December 1989. He released the first version (0.9.0) of Python for general public on February 20, 1991. \n\nThe language evolved over the next few decades and so did its definition, the current version of which is stated below:  \n\n\u003e Python is a high-level, interpreted, object-oriented programming language with dynamic semantics.\n\nLet us break down and analyze the above definition to gain a better understanding of Python:\n\n**High-level**\n\nPython is a **high-level programming language** which can be used to write a program in natural language (english) making it readable, writable, shareable and manageable. \n\nWhile developing a Python program one is not required to handle the various components of computer architecture like registers, memory addresses and call stacks which have to be handled if an assembly language or a low-level language is used for development. \n\nPython includes high-level language features like variables, data structures (lists, dictionaries, etc.), objects, expressions, modules, classes, functions, loops, threads, file handling, string handling, error handling and other computer science abstraction concepts.  \n\n**Interpreted**\n\nIn traditional programming languages like C or C++, codes are compiled into computer-readable machine code before it can be executed. \n\nPython is an **interpreted language** where the Python interpreter reads and executes the program line by line. \n\nThe process is more time consuming compared to compiled code execution, but allows faster development as one does not have to go through the entire compilation step during testing and debugging. Also, the code can run on any platform as long as it has a valid Python installation (which includes interpreter) as there is no generation of platform dependent binaries.\n\n**Object-oriented**\n\nPython does not enforce **Object-oriented programming (OOP)**, but completely supports it. \n\nA programmer can define Classes specifying the data in the form of attributes (or properties) and some programming logic in the form of member functions (or methods). Once a class is defined, the user can create an instance of that class which is known as an object.\n\nIn Python, everything (`int`, `list`, `dict`, etc.) is an object. We will cover more about objects in detail in the later sections.\n\n**Dynamic Semantics**\n\nAs Python is an interpreted language in which the code is executed line-by-line, a python statement or expression is evaluated during run-time. This allows **dynamic typing** (type of a variable can change over its lifetime) and creation of dynamic objects during run-time, which provides more flexibility, usability and fewer lines of code as compared to statically-typed compiled languages like C/C++.\n\n## Advantages of Python\n\nThe key advantages of Python are as follows:  \n\n**1. Easy to Learn**\n\nThe Python programming language is easy to learn with low technical and conceptual overhead. This makes it an ideal language for beginners to learn programming.\n\n**2. Clear Syntax \u0026 Fewer Lines of Code**\n\nPython's simple and easy to learn syntax increases code readability and leads to fewer lines of code. \n\nA typical task which requires an average of twenty lines of code in C and seven in Java can often be done with just one line in Python. \n\nAlso, due to fewer lines of code the chances of making any error is significantly reduced.\n\n**3. Open Source**\n\nPython is an open source programming language, so anyone can view and contribute to its source code.\n\n**4. Portable \u0026 Platform Independent**\n\nThe Python programming language is portable \u0026 platform independent as it can work on any Linux, MacOS or Windows device.\n\n**5. Standard Library \u0026 Python Packages**\n\nPython has a rich and extensive Standard Library, a collection of predefined functions for various tasks. \n\nPython programmers also have at their disposal the vast ecosystem of more than 250,000 community contributed libraries in the Python Package Index (PyPI), where one can find a solution to every conceivable task.\n\n**6. Web Application Development**\n\nSome of the most popular web development frameworks (django, flask, etc.) are written in Python. This coupled with the availability of packages to connect to any database makes Python a great choice for web application development.\n\n## Installing Python in Windows\n\nLet's start with the Python 3 installation process on Windows operating system.\n\n**Step 1: Download Installer**\n\nDownload the latest Windows installer from the [Python Software Foundation website](https://www.python.org/downloads/).\n\n![Step 1: Download Installer](images/0201a.png)\n\n**Step 2: Install Python 3**\n\nOnce the download is complete double-click and run it.\n\n![Step 2: Install Python 3](images/0201b.png)\n\nSelect the checkbox ✅ `Add Python 3.9 to PATH`. This will enable you to install python packages and run python script via command-line.\n\nHit 🛡️ `Install Now` and complete the setup.\n\n**Step 3: Verify Installation**\n\nOnce the setup is complete, click on the `Start` menu and open `Python 3.9 -\u003e IDLE (Python 3.9 64 bit)` to launch the Python interpreter.\n\n![Step 3: Launch Python Interpreter](images/0201c.png)\n\nPython 3.9 is now successfully installed on your computer.\n\n![Step 3: Verify Installation](images/0201d.png)\n\n## Installing Python in macOS (Apple)\n\nLet's start with the Python 3 installation process on macOS operating system.\n\n**Step 1: Download Installer**\n\nDownload the latest macOS installer from the [Python Software Foundation website](https://www.python.org/downloads/).\n\n![Step 1: Download Installer](images/0202a.png)\n\n**Step 2: Install Python 3**\n\nOnce the download is complete double-click and run it.\n\n![Step 2: Install Python 3](images/0202b.png)\n\nHit `Continue` and complete the setup.\n\n**Step 3: Verify Installation**\n\nOnce the setup is complete, click on the `Launchpad -\u003e IDLE` to launch the Python interpreter.\n\n![Step 3: Verify Installation](images/0202c.png)\n\nPython 3.9 is now successfully installed on your computer.\n\n## Execution Modes\n\nAfter installing the latest version of the Python interpreter, we can now write and execute some basic Python codes.\n\nThere are two ways to execute a Python program:\n\n1. **Interactive Mode**: When the IDLE application is launched, the Python interpreter or the Python shell pops up on the screen. User can interact with the Python interpreter and execute statements (single line or multiline code snippets) directly in this Python shell.\n2. **Script Mode**: This is the most commonly used method for executing a Python program. The entire Python program is written and saved in a file (`.py` extension) which can be executed using the IDLE application.\n\n## Interactive Mode of Execution\n\nLet us execute some basic Python statements and interact with the Python shell.\n\n**Launching the Python Shell**\n\nTo launch the IDLE application click `[Windows Start Menu Button] -\u003e [Python 3.9 Folder] -\u003e [IDLE (Python 3.9 64 bit)]`.\n\n![Launch IDLE](images/0201c.png)\n\nThe Python interpreter or the Python shell will pop-up on the screen.\n\n![Python Shell](images/0201d.png)\n\nThe version (`3.9`) of the Python interpreter is displayed at the top of the window followed by the `\u003e\u003e\u003e` symbol which indicates that the interpreter is ready to take instructions.\n\nPython commands or statements can be input on this prompt. The input statements are executed instantaneously and any variable assignments are retained as long as the session is not terminated.\n\n**Basic Arithmetic**\n\nLet us perform some basic arithmetic operations in the interactive mode using an integer number (`2`) and a floating-point number (`3.5`):\n\n``` python\n\u003e\u003e\u003e 2 + 2\n4\n\u003e\u003e\u003e 2 * 3.5\n7.0\n```\n\nIt can be observed that the results of each of the above computations are displayed immediately in the shell.\n\n**Storing Values/Results**\n\nInstead of immediately displaying the results, they can also be stored in variables using the assignment symbol (`=`) as shown below:\n\n``` python\n\u003e\u003e\u003e a = 2 + 2\n\u003e\u003e\u003e b = 2 * 3.5\n```\n\nThe values of `a` and `b` can be accessed later for future calculations as shown below:\n\n``` python\n\u003e\u003e\u003e a\n4\n\u003e\u003e\u003e b\n7.0\n\u003e\u003e\u003e a * 5\n20\n\u003e\u003e\u003e b / 3\n2.3333333333333335\n```\n\n**Basic String Operation**\n\nInteractive mode is not just restricted to basic arithmetic or assignments. Let us join two strings - `\"Hello, \"` and `\"world!\"`.\n\n``` python\n\u003e\u003e\u003e \"Hello, \" + \"world!\"\n'Hello, world!'\n```\n\nThe complete functionality of Python is easily accessible to a user via the **Interactive Mode**. \n\nThis makes it convenient for testing and instant execution of small code snippets (single line or few lines of code), a feature not available in compiled languages like C, C++ and Java. \n\nBut, the statements cannot be saved for future use and have to retyped for re-execution. This disadvantage is overcome by the use of Python in **Script Mode** as described in the next section.\n\n## Script Mode of Execution\n\nTo write reusable codes, script mode is the most preferred mode of code execution.\n\n**File Creation**\n\nTo create a new file using the IDLE application click `[File] -\u003e [New File]`\n\n![Create New File](images/0303a.png)\n\nWrite a simple Python program as shown below  \n\n``` python\na = 2 + 2\na\n```\n\nand save the script as `example.py` (`.py` file extension for all Python scripts) using `[File] -\u003e [Save As...]` \n\n![Save File](images/0303b.png)\n\n**Script Execution**\n\nNow run this script using `[Run] -\u003e [Run Module]`.\n\n![Execute File](images/0303c.png)\n\nIt can be observed that the code has been executed, but no output is displayed on the console (or the standard output) as all outputs have to be explicitly specified when running a code in the script mode. \n\nThis can be done by using the `print()` function which is used in Python scripts to display output on the output stream. Let us quickly add the `print()` function in the above code and execute it.\n\n``` python\na = 2 + 2\nprint(a)\n```\n\nNow, when you run the script you will observe that the value of `a`, that is `4`, is now displayed on the console.\n\n# Python Fundamentals\n\n## Tokens: Introduction\n\nWhen a Python code is executed, the Python interpreter reads each logical line and breaks it into a sequence of lexical units. \n\nThese lexical units are better known as **tokens** - the smallest individual units of a program. They are the building blocks of a Python code and can be classified into one of the following categories:\n\n- **Keywords** : Reserved words that convey special meaning when processed by the Python interpreter.\n- **Identifiers** : Names defined by the programmer to refer to objects that can represent variables, functions, classes, etc.\n- **Literals** : Values specified in the program which belong to exactly one of the Python's built-in data types.\n- **Delimiters** : Symbols that denote grouping, punctuation, and assignment/binding.\n- **Operators** : Symbols that can operate on data and compute results.\n\n## Tokens: Keywords\n\nKeywords are reserved words that have special meaning when processed by the Python interpreter. They are case-sensitive and cannot be used for naming identifiers (class, function, variable or structure names).\n\nThe list of keywords in Python are provided below:\n\n| | | |\n|---|---|---|\n| `True` | `False` | `import` |\n| `from` | `as` | `None` |\n| `and` | `or` | `not` |\n| `in` | `is` | `try` |\n| `except` | `finally` | `raise` |\n| `del` | `global` | `nonlocal` |\n| `lambda` | `def` | `class` |\n| `with` | `if` | `elif` |\n| `else` | `pass` | `for` |\n| `while` | `continue` | `break` |\n| `assert` | `return` | `yield` |\n| `async` | `await` | |\n\n## Tokens: Identifiers\n\nIdentifiers are used for defining the names of Python objects such as variables, functions, classes, modules, etc. The naming convention for identifiers is as follows:\n\n- Must begin with a lowercase character (`a-z`) or an uppercase character (`A-Z`) or underscore sign (`_`).\n- Followed by any number of letters (`a-z`, `A-Z`), digits (`0-9`), or underscores (`_`).\n- Should not be a keyword.\n- No special symbols are allowed like `!`, `@`, `#`, `$`, `%`, etc.\n\nSome points to keep in mind while naming identifiers:\n\n- Identifiers are case-sensitive in nature and any difference in case of any character refers to a different identifier. e.g., `length` and `Length` are different identifiers.\n- Identifiers differing by only underscores are different. e.g., `unitlength` and `unit_length` are different identifiers.\n\nIt is also a good practice (although not compulsory) to follow the following procedure while naming identifiers:\n\n- Identifiers should be named carefully with an emphasis on clarity and readability. For example, in a program that calculates the area of a rectangle, a good choice for identifier names are - `length`, `breadth` and `area`.\n- Class names should start with uppercase character.\n- Identifiers starting with an underscore have special meaning in a program.\n- Variable, function and method names should be in lowercase characters, with underscores separating multiple words like `area_of_square`, `area_of_triangle`, etc.\n\n## Tokens: Literals\n\nLiterals are tokens in the source code which represent fixed or constant values. They are often used in assignment statements for initializing variables or in comparison expressions.\n\nThe various types of literals available in Python are as follows:\n\n### Numeric Literals\n\nNumeric literals are used for representing numeric values in the source code. They can be of three types - integers, float point numbers and imaginary numbers.\n\n#### Integer Literals\n\nInteger literals are numbers without any fractional component. \n\nIn Python, integer literals can be written in four positional (base) numeral systems:\n\n**i. Decimal or base-10 Integer**\n\nA decimal integer literal consists of one or more digits (`0-9`) and cannot have any zeros preceding the first non-zero digit, except when the number is `0`.\n\nExample base-10 integers:\n\n``` python\n34\n3283298\n864\n0\n```\n\n`092` is not a valid decimal integer literal as a zero precedes the first non-zero digit `9`.\n\n**ii. Binary or base-2 Integer**\n\nA binary integer or base-2 integer begins with `0b` or `0B` followed by binary digits `0-1`. \n\nFor example, `27` can be written as a binary integer literal `0b11011`.\n\n**iii. Octal or base-8 Integer**\n\nAn octal integer or base-8 integer begins with `0o` or `0O` followed by octal digits `0-7`. \n\nFor example, `27` can be written as an octal integer literal `0o33`.\n\n**iv. Hexadecimal or base-16 Integer**\n\nA hexadecimal integer or base-16 integer begins with `0x` or `0X` followed by digits `0-9` or letters `A-F` (case insensitive). \n\nFor example, `27` can be written as a hexadecimal integer literal `0x1B` or `0x1b`.\n\nThus, it can be observed that number `27` can be written in the program as `27` (decimal), `0b11011` (binary), `0o33` (octal) or `0x1B` (hexadecimal).\n\n**Underscores in Integer Literals**\n\nAn optional character `_` (underscore) is also allowed in an integer literal to group digits for enhanced readability. \n\nOne underscore can occur between digits, and after base specifiers like `0o`. \n\nThey are ignored while determining the actual numerical value of the literal. \n\nSome valid underscore usages are - `10_00_00_000`, `0b_1110_0101`, `0x23_123`.\n\n#### Floating Point Literals\n\nFloating point literals are real numbers present in the source code. They contain fractional component and/or exponential component.\n\nThe fractional component includes the digits after the decimal point (`.`).\n\nExample floating point literals:\n\n```\n3.4\n.4\n8.\n3.4E2\n3.4e-2\n```\n\nIn the above example, `.4` is equivalent to `0.4` and `8.` is equivalent to `8.0`.\n\nThe exponential component can be identified by the letter `e` or `E` followed by an optional sign (`+` or `-`) and digits (`0-9`). This exponent is equivalent to multiplying the real number with the power of `10`. \n\nFor example, `3.4E2` is equivalent to `3.4 x 10^2` or `340.0`, whereas `3.4e-2` is equivalent to `3.4 x 10^-2` or `.034`.\n\n#### Imaginary Literals\n\nTo specify complex numbers and perform complex number mathematics, Python supports imaginary literals which are given by real or integer number followed by the letter `j` or `J` which represents the unit imaginary number.\n\nExample imaginary literals:\n\n```\n3.5j   \n15.j    \n12j     \n.005j   \n3e100j   \n3.5e-10j\n```\n\n**Points to Note**\n\nIn Python,\n\n- there is no specialized literal such as a complex literal. A complex number is actually represented in the program using an expression comprising a real number (integer/float numeric literal) and an imaginary number (imaginary literal). For example, `1 + 2j` consists of an integer literal (`1`) and a imaginary literal (`2j`).\n- numeric literals do not include the minus sign (`-`). `-` is actually a unary operator it combines with a numeric literal to represent negative numbers. For example, in `-3.14` the numeric literal is `3.14` and `-` is an operator.\n\n### Boolean Literals\n\nThe reserved words `True` and `False` are also boolean literals which can be used to specify the truth value in a program.\n\n### String Literals\n\nString literals are texts which can be specified in a variety of ways in Python:\n\n- Single quotes: `'python'`\n- Double quotes: `\"python\"`\n- Triple quoted: `'''Triple python'''`, `\"\"\"Three python\"\"\"`. \n\nTriple quoted strings can also span multiple lines.\n\nExample:\n\n``` python\ns = \"I am a String\"  \n\ns1 = \"\"\"A\nmultiline\nString\"\"\"\n\ns2 = '''Also a\nmultiline\nString'''\n```\n\nThe backslash (`\\`) character can be used in a string literal to escape characters that otherwise have a special meaning, such as newline, linefeed, or the quote character.\n\n| Escape Sequence | Meaning |\n|--|--|\n| `\\\\` | Backslash (`\\`) |\n| `\\'` | Single quote (`'`) |\n| `\\\"` | Double quote (`\"`) |\n| `\\a` | ASCII Bell (BEL) |\n| `\\b` | ASCII Backspace (BS) |\n| `\\f` | ASCII Form-feed (FF) |\n| `\\n` | ASCII Linefeed (LF) |\n| `\\r` | ASCII Carriage Return (CR) |\n| `\\t` | ASCII Horizontal Tab (TAB) |\n| `\\v` | ASCII Vertical Tab (VT) |\n\nAlthough `\\'` and `\\\"` can be used to specify quote characters, Python allows embedding double quotes inside a single-quoted string (`'My name is \"Python\".'`) and single quotes inside a double-quoted string (`\"Python's World\"`).\n\nString literals also support unicode characters which can be specified using `\\u` escape sequence followed by the 4 letter unicode.\n\n``` python\n\u003e\u003e\u003e print(\"E = mc\\u00B2\")\nE = mc²\n```\n\nIn the above example, `\\u00B2` is the unicode character which represents the 'SUPERSCRIPT TWO'. \n\n### Special Literal\n\n`None` is a special literal which is used to denote the absence of value. \n\nIt should not be confused with `0` as `0` is an integer literal with a defined finite value, whereas `None` implies nothingness.\n\n``` python\n\u003e\u003e\u003e a = None\n\u003e\u003e\u003e a\n\u003e\u003e\u003e\n```\n\nIn the above example, the Python shell does not display any value of `a` as it is assigned as `None` which has no value.\n\n### Collection of Literals\n\nPython has the provision for specifying a collection of literals in the source code using a special syntax known as **\"displays\"**. \n\nOne can create specialized containers like list, set and dictionary using this syntax.\n\nSome example collection of literals (displays) are provided below:\n\n- **List**: `a = ['a', 'b', 'c']`\n- **Set**: `a = {'a', 'b', 'c'}`\n- **Dictionary**: `a = {'a':1, 'b':2, 'c':3}`\n\nList, set and dictionary will be covered in detail in later chapters.\n\n## Tokens: Operators\n\nOperators are tokens which can be combined with values and variables to create expressions which evaluate to a single value. Python supports a rich set of operators:\n\n``` python\n+       -       *       **      \n/       //      %      @        \n\u003c\u003c      \u003e\u003e      \n\u0026       |       ^       ~       \n:=      \u003c       \u003e       \n\u003c=      \u003e=      ==      !=\n```\n\nEach of the above operators are covered in detail in the chapter - Operators.\n\n## Tokens: Delimiters\n\nDelimiters are tokens which are useful for organizing a program and are used in statements, expressions, functions, literal collections, and various other code structures.\n\nThey can be classified based on utility as follows:\n\n### Grouping\n\n`()`, `[]` and `{}` are delimiters used for:\n\n- grouping expressions which can be spread across multiple physical lines.\n- creating collection of literals like list display, dictionary display, set display.\n- creating parenthesized sub-expression having the highest operator precedence (evaluated first) in a complex expression.\n\n**Example**\n\n``` python\ndays = ['Sunday', 'Monday', \n        'Tuesday', 'Wednesday', \n        'Thursday', 'Friday', \n        'Saturday']\n\nsum_6 = (1 + 2 +\n         3 + 4 +\n         5 + 6)\n```\n\nis equivalent to\n\n``` python\ndays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n\nsum_6 = (1 + 2 + 3 + 4 + 5 + 6)\n```\n\n### Punctuation, Decoration and Annotation\n\nTokens in Python which are used for punctuation, decoration and annotation are:\n\n```\n.       ,       :\n;       @       -\u003e\n```  \n\n### Assignment/Binding\n\nThe assignment or binding delimiters are used for binding objects to names via assignment statements. The complete list of tokens are provided below:\n\n```\n=       +=      -=      *=\n/=      //=     %=      **=\n@=      \u0026=      |=      ^=\n\u003c\u003c=     \u003e\u003e=\n```\n\nExcept `=`, the rest of the tokens have an operator followed by `=` character. \n\nThese delimiters are also known as augmented assignment operators as they perform an operation in combination with assignment.\n\n## Character Set\n\nA set of valid characters that a programming language recognizes is known as its **character set**. \n\nPython is a new age programming language which supports Unicode encoding standard. The default encoding for Python source code is UTF-8 (Unicode Transformation Format – 8-bit) which enables developers to use Unicode characters not only as literals, but also as identifiers. \n\nThis makes Python one of the very few programming languages that support multiple languages as shown in the example below:\n\n**Code**\n\n``` python\nmessage = \"हिन्दी में print करे\"\nprint(message)\n\nक = 1  # Devanagari Letter KA\nক = 2  # Bengali Letter KA\nக = 3  # Tamil Letter KA\nક = 4  # Gujarati Letter KA\nprint(क + ক + க + ક)\n```\n\n**Output**\n\n```\nहिन्दी में print करे\n10\n```\n\n## Blocks and Indentation\n\nIn traditional programming languages like C++ or Java, programs are organised in form of code blocks. \n\nEach code block contains one or more statements which are enclosed between braces - `{` and `}` and are executed sequentially. \n\nA sample C++/Java code is provided below which checks for an input `x`.\n\n**C++**\n\n``` c++\nif (x \u003c 10) {\n    cout \u003c\u003c \"x is less than 10\" \u003c\u003c endl;\n    if (x \u003c= 5) {\n        cout \u003c\u003c \"x is less than or equal to 5\" \u003c\u003c endl;\n    }\n    else {\n        cout \u003c\u003c \"x is more than 5 but less than 10\" \u003c\u003c endl;\n    }\n}\nelse {\n    cout \u003c\u003c \"x is not less than 10\" \u003c\u003c endl;\n}\n```\n\n**Java**\n\n``` java\nif (x \u003c 10) {\n    System.out.println(\"x is less than 10\");\n    if (x \u003c= 5) {\n        System.out.println(\"x is less than or equal to 5\");\n    }\n    else {\n        System.out.println(\"x is more than 5 but less than 10\");\n    }  \n}\nelse {\n    System.out.print(\"x is not less than 10\");\n}\n```\n\nIt can be seen how indentations (`tab` at the beginning of line) are added (not required by programming language) to the code to increase readability, which helps in guiding readers through the code.\n\n**Python**\n\nCode blocks in Python are inspired by this idea as it makes it easier to understand a Python code.\n\nA block of code is denoted by line indentation, typically **4 spaces** (preferred) or a **tab**. This indentation is used to determine the logical group of statements, with all statements within a group having the same level of indentation.\n\nThe corresponding Python code for the above C++/java examples is provided below. \n\nNotice how the code blocks are indented according to the logic.\n\n``` python\nif x \u003c 10:\n    print(\"x is less than 10\")\n    if x \u003c= 5:\n        print(\"x is less than or equal to 5\")\n    else:\n        print(\"x is more than 5 but less than 10\")\nelse:\n    print(\"x is not less than 10\")\n```\n\n## Comments\n\nPython supports single-line comments and multi-line comments to enhance code readability via adding documentation.\n\n### Single Line Comments\n\nA single line comment begins with `#`. Everything between `#` and the end of line is ignored by the Python interpreter.\n\n``` python\n# A single line comment.\na = 1 # assign a\n```\n\n### Multiline comments\n\nA multiline comment begins with `'''` or `\"\"\"` and ends with the same.\n\n``` python\n\"\"\"\nI am\na multiline\ncomment.\n\"\"\"\n\n'''\nI am\nalso a multiline\ncomment.\n'''\n```\n\nAs compared to single line comments, multiline comments should begin at the same indentation level corresponding to their code block. \n\nFor example,\n\n``` python\n\"\"\"\nBegin program\nhere\n\"\"\"\nif x \u003c 10:\n    \"\"\"\n    Enter code block when x\n    is less than 10\n    \"\"\"\n    print(\"x is less than 10\")\n    if x \u003c= 5:\n        \"\"\"\n        Enter code block when x\n        is less than or equal to 5\n        \"\"\"\n        print(\"x is less than or equal to 5\")\n    else:\n        \"\"\"\n        Enter code block when x\n        is more than 5 but less than 10\n        \"\"\"\n        print(\"x is more than 5 but less than 10\")\nelse:\n    \"\"\"\n    Enter code block when x\n    is not less than 10\n    \"\"\"\n    print(\"x is not less than 10\")\n```\n\n# Variables, Objects \u0026 Data Types\n\n## What are Objects \u0026 Variables?\n\nA program is a sequence of instructions which often acts on information (data) provided by the user. \n\nThe process of creating, storing and manipulating this data helps in the computation of new data or the end result.\n\n**Variables are the fundamental building blocks of a program** which provide a way to store, access and modify values during the life-cycle of a program. \n\nEach variable has:\n\n- a name (handle), \n- a type or data-type (kind of data), and \n- a value (actual data).\n\nIn traditional programming languages like Java or C++, the type of the variable is pre-defined.\n\nFor example, if you want to use the value `1` inside the program, you can store it in a variable named `a` of type `int`.\n\n```\nint a = 1;\n```\n\nThis `a` is synonymous to a box of fixed dimensions (fixed type) holding something (value `1`) inside it.\n\n![Box 'a'](images/0501a.png)\n\nIn case we want to change the contents of the box, we can replace it with something similar (same type).\n\n```\na = 2;\n```\n\n![Filled box 'a'](images/0501b.png)\n\nThe contents of this box can be replicated and placed in a similar (same type) box:\n\n```\nint b = a;\n```\n\n![Copy box 'a' contents](images/0501c.png)\n\nMultiple boxes can exist, each containing an item having the same value.\n\n```\nint x = 3;\nint y = 3;\nint z = 3;\n```\n\n![Boxes 'x', 'y' \u0026 'z'](images/0501d.png)\n\nAs shown above, the programming languages in which the variables (named boxes) are declared along with their types (size of the boxes) are known as **statically typed** languages. \n\nThe size of these boxes cannot change later in the program until the variable is re-initialized with the same name and different type.\n\n**Python is a dynamically-typed language**, where every value or data item (of any type like numeric, string, etc.) is an object. \n\nThe variable names are just name-tags pointing to the actual object containing data of any type. \n\nAs there is no need of any variable declaration in Python before usage, there is no concept of default value (an empty box or `null`) which exists in other programming languages.\n\nWhenever a new object is created in Python, it is assigned a unique identity (ID) which remains the same throughout the lifetime of that object. This ID is the address of the object in memory and the built-in function `id()` returns the value of this address.\n\n``` python\n\u003e\u003e\u003e a = 1\n\u003e\u003e\u003e id(a)\n140407745943856\n\u003e\u003e\u003e a = 2\n\u003e\u003e\u003e id(a) \n140407745943888\n```\n\nIn the above example, the ID of `a` changes as it points to a new object (`2`).\n\n``` python\n\u003e\u003e\u003e b = a\n\u003e\u003e\u003e id(b)\n140407745943888\n```\n\nAlso, when `a` is assigned to `b`, instead of creating a new copy, `b` points to the same object as `a`.\n\n## Variables \u0026 Assignment Statements\n\nA variable is uniquely identified by a name (identifier) and follows the same naming convention:\n\n- Must begin with a lowercase character (`a-z`) or an uppercase character (`A-Z`) or underscore sign (`_`).\n- Followed by any number of letters (`a-z`, `A-Z`), digits (`0-9`), or underscores (`_`).\n- Should not be a keyword.\n- No special symbols are allowed like `!`, `@`, `#`, `$`, `%`, etc.\n\n### Assignment\n\nVariables can be bound to a reference of an object (of any type) using assignment statements. \n\nYou can create an object (data) and bind it's reference to a variable using equal sign (`=`):\n\n``` python\ncount = 100       # integer\npi    = 3.141     # real number\nname  = \"Python\"  # string\n```\n\nHere, L-value refers to the assignable variables (`count`, `pi`, `name`) on the left side of the assignment and R-value refers to the expression on the right side of the assignment operator that has a value (`100`, `3.141`, `\"Python\"`).\n\nAs variables are just references, you can rebind them to another object of same or different type:\n\n``` python\na = 100       # integer \na = 3.141     # real number\na = \"Python\"  # string\n```\n\n### Deletion\n\nThe `del` statement can be used to unbind the reference to an object.\n\n``` python\n\u003e\u003e\u003e a = 10\n\u003e\u003e\u003e del a\n\u003e\u003e\u003e a\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nNameError: name 'a' is not defined\n```\n\nAccessing `a` results in a `NameError` as the reference (variable) to the object holding value `10` is deleted.\n\nThe object is also automatically cleaned up from the memory if there is no other variable referencing to it (garbage collection).\n\n### Multiple Assignment\n\nIn Python, multiple assignment can be used to condense variables which are set to the same value:\n\n``` python\n\u003e\u003e\u003e x = y = z = 'foo'\n\u003e\u003e\u003e x\n'foo'\n\u003e\u003e\u003e y\n'foo'\n\u003e\u003e\u003e z\n'foo'\n```\n\n### Tuple Swapping\n\nIn Python, a temporary variable is not required to swap values of two variables. Values can be directly swapped (tuple swapping) as shown below:\n\n``` python\n\u003e\u003e\u003e a = 'Hello'\n\u003e\u003e\u003e b = 'World'\n\u003e\u003e\u003e b, a = a, b\n\u003e\u003e\u003e a\n'World'\n\u003e\u003e\u003e b\n'Hello'\n```\n\n## Built-in Data Types\n\nIn Python, the `type` of a data (or value) is not linked to the variable, but to the actual object which contains it. This type is also known as the object's data type and is used for identifying the operations that can be performed on the data.\n\nThe following built-in data types are available in Python:\n\n- **Numeric Types** - `int`, `float`, `complex`, `bool`\n- **Sequence Types** - `list`, `tuple`, `str`\n- **Set Type** - `set`\n- **Mapping Type** - `dict`\n- **Special Type** - `None`\n\nOften sequence, set and mapping types are also collectively known as **iterables** as they are a collection of items on which a user can traverse (iterate).\n\n### Numeric Types - `int`, `float`, `complex`, `bool`\n\nNumeric data types are used for storing the following types of numbers:\n\n**Integer Numbers**\n\nObjects holding integer numbers like `-1, 0, 200` are of `int` data type.\n\n**Real or Floating-point Numbers**\n\nObjects holding real or floating point numbers like `-1.1, 3e2, 20.0` are of `float` data type.\n\n**Complex Numbers**\n\nObjects storing complex numbers like `2 + 1j, -3j, -1 + 2J` are of type `complex`. \n\nEach complex number has two parts, the real part which is a numeric integer or floating point literal, and the imaginary part which is an imaginary literal.\n\n**Boolean**\n\nThe boolean data type (`bool`) is a subtype of `int`. It stores the evaluated value of expressions represented as keywords - `True` (integer value `1`) and `False` (integer value `0`).\n\n### Sequence Types - `str`, `list`, `tuple`\n\nAn ordered collection of items where each item can be accessed using an integer index is known as a sequence. The following three sequence data types are available in Python:\n\n**String**\n\nA string (`str` data type) is a sequence of zero or more unicode characters enclosed within a pair of single (`'`) or double (`\"`) quotes.\n\nSome example strings are - `\"42\", 'hello', \"python\"`.\n\n**List**\n\nA `list` is sequence of items of same or different data types which are enclosed within brackets - `[ ]`.\n\nSome example lists are - `[1, 2, 3]`, `['abc', 23, 3.14]`, `['edpunk', 'python']`.\n\n**Tuple**\n\nA `tuple` is an immutable sequence of items of same or different data types which are enclosed within parentheses - `( )`. \n\nSome example tuples are - `(1, 2, 3)`, `('abc', 23, 3.14)`, `('edpunk', 'python')`.\n\n### Set Type - `set`\n\nA `set` is an unordered collection of unique items of same of different data types which are enclosed in curly braces - `{ }`. \n\nSome example sets are - `{1, 2, 3}`, `{'abc', 23, 3.14}`, `{'edpunk', 'python'}`.\n\n### Mapping Type - `dict`\n\n`dict` is a mapping data type which stores values in the form of key-value pairs. \n\nIt is used for representing data where you can quickly access the value (any data type) corresponding to a key (any data type except `list`, `set` or `dict`), just like a dictionary where you can lookup the meaning of a given word. \n\nKeys and corresponding values are separated by colon (`:`). \n\nThe key-value pairs are separated by comma (`,`) and enclosed within curly braces - `{ }`. \n\nSome example dictionaries are - `{1: \"a\", 2: \"b\", 3: \"c\"}`, `{\"name\": \"edpunk\", \"language\": \"python\"}`.\n\n### Special Type - `None`\n\n`None` is a special data type which is used to denote the absence of value in an object. \n\nIt is neither `0` nor `False` as these are defined finite values, whereas `None` implies nothingness.\n\n## Type Checking\n\nThe built-in `type()` function can be used to fetch the data type of an object.\n\nExamples:\n\n``` python\n\u003e\u003e\u003e count = 100\n\u003e\u003e\u003e type(count)\n\u003cclass 'int'\u003e\n\n\u003e\u003e\u003e pi = 3.141\n\u003e\u003e\u003e type(pi)\n\u003cclass 'float'\u003e\n\n\u003e\u003e\u003e name = \"Python\"\n\u003e\u003e\u003e type(name)\n\u003cclass 'str'\u003e\n```\n\nThis function can be used along with the `is` operator in an expression to test whether the object is of the given type.\n\n``` python\n\u003e\u003e\u003e count = 100\n\u003e\u003e\u003e type(count) is int\nTrue\n```\n\nThe `in` operator can be used along with the `type()` function to test if the data type is one of the mentioned types.\n\n``` python\n# count is of type int or float\n\u003e\u003e\u003e type(count) in (int, float)\nTrue\n```\n\n## Type Casting\n\nThe process of converting the data type of an object from one type to another is known as **Type Casting** or **Type Conversion**. \n\nThe two kinds of type casting supported in Python are:\n\n### Implicit Type Casting\n\nThe Python interpreter automatically converts the data type without the need of user intervention when evaluating expressions to determine the final data type.\n\nIn the below example the final type of `c` is automatically determined as `float` by the Python interpreter.\n\n``` python\n\u003e\u003e\u003e a = 1   # int\n\u003e\u003e\u003e b = 2.0 # float\n\u003e\u003e\u003e c = a + b\n\u003e\u003e\u003e c\n3.0\n\u003e\u003e\u003e type(c)\n\u003cclass 'float'\u003e\n```\n\n### Explicit Type Casting\n\nWhen the type conversion is explicitly specified by the user using the various built-in functions available in Python, it is known as explicit type casting. \n\nThe built-in functions which can be used for explicit type casting are as follows:\n\n**1. `int()`**\n\nCreates an `int` from a `bool`, `float` or `str` containing integer characters (with or without sign).\n\n``` python\n\u003e\u003e\u003e int(True)\n1\n\u003e\u003e\u003e int(2.3)\n2\n\u003e\u003e\u003e int(\"2\")\n2\n```\n\n**2. `float()`**\n\nCreates a `float` from a `bool`, `int` or `str` containing floating point literals (with or without sign).\n\n``` python\n\u003e\u003e\u003e float(True)\n1.0\n\u003e\u003e\u003e float(2)\n2.0\n\u003e\u003e\u003e float(\"2.3\")\n2.3\n```\n\n`float()` also accepts the following string inputs - \n\n- `\"Infinity\"`\n- `\"inf\"`\n- `\"nan\"` (not a number).\n\n``` python\n\u003e\u003e\u003e float(\"Infinity\") \u003e 1\nTrue\n\u003e\u003e\u003e float(\"nan\")  \nnan\n```\n\nFloating point literals can also contain the following characters -\n\n- `.`, which denotes the fractional part of a number.\n- `e` or `E`, which denotes the exponent part of a number.\n\n``` python\n\u003e\u003e\u003e float(\"3.14\")\n3.14\n\u003e\u003e\u003e float(\"10.\")\n10.0\n\u003e\u003e\u003e float(\"1e100\") \n1e+100\n\u003e\u003e\u003e float(\"3.14e-10\")\n3.14e-10\n```\n\n**3. `str()`**\n\nConverts any object into a `str`.\n\n``` python\n\u003e\u003e\u003e str(2)\n'2'\n\u003e\u003e\u003e str([1, 2, 3, 4])\n'[1, 2, 3, 4]'\n```\n\n**4. `tuple()`**\n\nCreates a `tuple` from an iterable of type `str`, `list`, `set` or `range`.\n\n``` python\n\u003e\u003e\u003e tuple('hello')\n('h', 'e', 'l', 'l', 'o')\n\u003e\u003e\u003e tuple([1, 2, 3, 4])\n(1, 2, 3, 4)\n\u003e\u003e\u003e tuple(range(6))\n(0, 1, 2, 3, 4, 5)\n```\n\n**5. `list()`**\n\nCreates a `list` from an iterable of type `str`, `tuple`, `set` or `range`.\n\n``` python\n\u003e\u003e\u003e list('hello')\n['h', 'e', 'l', 'l', 'o']\n\u003e\u003e\u003e list({1, 2, 3, 4})\n[1, 2, 3, 4]\n\u003e\u003e\u003e list(range(6))\n[0, 1, 2, 3, 4, 5]\n```\n\n**6. `set()`**\n\nCreates a `set` from an iterable of type `str`, `tuple`, `list` or `range`.\n\n``` python\n\u003e\u003e\u003e set('hello')\n{'o', 'e', 'l', 'h'}\n\u003e\u003e\u003e set([1, 2, 3, 4])\n{1, 2, 3, 4}\n\u003e\u003e\u003e set(range(6))\n{0, 1, 2, 3, 4, 5}\n```\n\n## Mutable \u0026 Immutable Data Types\n\n### Immutable Data Types\n\nA data type is said to be immutable when the value of an object of that type cannot be modified.\n\nThe following data types are immutable:\n\n- `int`\n- `float`\n- `complex`\n- `bool`\n- `tuple`\n- `str`\n- `None`\n\nYou might be wondering if some of the above types are immutable then how are we able modify the values of variables?\n\nIn case of variable re-assignment, the original objects are not modified, but new objects (with new values) are created in a new memory location and are bound to the variables. The object containing the old value is destroyed if no other variable references it.\n\nLet us take an example,\n\n``` python\n\u003e\u003e\u003e a = 1\n\u003e\u003e\u003e id_a = id(a)\n\u003e\u003e\u003e a = 2\n\u003e\u003e\u003e id_a2 = id(a)\n\u003e\u003e\u003e id_a == id_a2\nFalse\n```\n\nYou can witness in the above example how the object containing the value `1` is different from the object containing the value `2`, and `a` points to the latest object.\n\nSequence data types like strings and tuples are also immutable, i.e., no modifications are permitted to any item once it is created and any attempt to do so raises an error.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e s[1] = \"P\"\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nTypeError: 'str' object does not support item assignment\n\u003e\u003e\u003e t = (1, 2, 3)\n\u003e\u003e\u003e t[1] = 0\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nTypeError: 'tuple' object does not support item assignment\n```\n\nAlthough, similar to numeric types the variables can be re-assigned to new sequences.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e id_s = id(s)\n\u003e\u003e\u003e s = \"Help\"\n\u003e\u003e\u003e id_s2 = id(s)\n\u003e\u003e\u003e id_s == id_s2\nFalse\n\n\u003e\u003e\u003e t = (1, 2, 3)\n\u003e\u003e\u003e id_t = id(t)\n\u003e\u003e\u003e t = (0, 2, 3)\n\u003e\u003e\u003e id_t2 = id(t)\n\u003e\u003e\u003e id_t == id_t2\nFalse\n```\n\n### Mutable Data Types\n\nIn Python, the following data types are mutable, i.e., any modification does not create a new object but modifies the existing object:\n\n- `list`\n- `set`\n- `dict`\n\nLet us take a list and modify its contents.\n\n``` python\n\u003e\u003e\u003e l = [1, 2, 3]\n\u003e\u003e\u003e id_l = id(l)\n\u003e\u003e\u003e l[0] = 0\n\u003e\u003e\u003e l\n[0, 2, 3]\n\u003e\u003e\u003e id_l2 = id(l)\n\u003e\u003e\u003e id_l == id_l2\nTrue\n```\n\nLet us take an example of a dictionary and add a new `key:value` pair.\n\n``` python\n\u003e\u003e\u003e d = {\"a\": \"apple\", \"b\": \"boy\"}\n\u003e\u003e\u003e id_d = id(d)\n\u003e\u003e\u003e d[\"c\"] = \"cat\"\n\u003e\u003e\u003e d\n{'a': 'apple', 'b': 'boy', 'c': 'cat'}\n\u003e\u003e\u003e id_d2 = id(d)\n\u003e\u003e\u003e id_d == id_d2\nTrue\n```\n\nLet us take an example of a set and add new item.\n\n``` python\n\u003e\u003e\u003e s = {\"apple\", \"bat\"}\n\u003e\u003e\u003e id_s = id(s)\n\u003e\u003e\u003e s.add(\"cat\")\n\u003e\u003e\u003e s\n{'cat', 'apple', 'bat'}\n\u003e\u003e\u003e id_s2 = id(s)\n\u003e\u003e\u003e id_s == id_s2\nTrue\n```\n\nIn the above examples, the `id` of the objects (`list`, `dict`, `set`) do not change, which implies that no new objects are created and the original objects are modified.\n\n# Input / Output\n\n## How to Accept User Input\n\n`input()` function is used to accept new input data from the user. \n\nWhen this function is encountered in the code, the python interpreter waits for the user to type a response which is read as a string and assigned to a variable. \n\n``` python\n\u003e\u003e\u003e name = input()\nedpunk\n\u003e\u003e\u003e name\n'edpunk'\n```\n\nThe function also has an optional string argument which is used as a prompt message for the user.\n\n``` python\n\u003e\u003e\u003e name2 = input(\"Enter name: \")\nEnter name: EdPunk\n\u003e\u003e\u003e name2\n'EdPunk'\n```\n\nUser input can be converted into integer or floating point numbers using the type conversion functions `int()` and `float()`.\n\n``` python\n\u003e\u003e\u003e num = int(input(\"Enter n: \"))\nEnter n: 10\n\u003e\u003e\u003e type(num)\n\u003cclass 'int'\u003e\n\u003e\u003e\u003e num\n10\n\n\u003e\u003e\u003e pi = float(input(\"Enter pi: \"))\nEnter pi: 3.14\n\u003e\u003e\u003e type(pi)\n\u003cclass 'float'\u003e\n\u003e\u003e\u003e pi\n3.14\n```\n\n## Displaying Output\n\nThe built-in `print()` function is used to display an output (value of variables, expressions, etc.) on the standard output.\n\nLet us go through a program which computes the area of a rectangle and displays it:\n\n**Code**\n\n``` python\nlength = 10\nbreadth = 5\narea = length * breadth\nprint(\"Area:\", area)\n```\n\n**Output**\n\n```\nArea: 50\n```\n\n`print()` function can also be used to output the value of multiple objects when they are provided as arguments to the function.\n\n**Code**\n\n``` python\na = 2 + 2\nb = 2 * 3.5\nprint(a, b)\n```\n\n**Output**\n\n```\n4 7.0\n```\n\nIn the above code, the values of `a` and `b` are separated by a blank space (the default value of `sep`). \n\nThis property can be modified by providing any user defined separator using the `sep` option. \n\nLet us modify the code and provide `\",\"` as the separator.\n\n**Code**\n\n``` python\na = 2 + 2\nb = 2 * 3.5\nprint(a, b, sep=\",\")\n```\n\n**Output**\n\n```\n4,7.0\n```\n\nWhen expressions are provided as arguments to the `print()` function, output is the evaluated value of those expressions. \n\nFor example,\n\n**Code**\n\n``` python\nprint(2 + 2)\nprint(2 * 3.5)\nprint(\"Hello, \" + \"world!\")\n```\n\n**Output**\n\n```\n4\n7.0\nHello, world!\n```\n\nIn the above code snippet, each `print()` function invocation creates a new line of output. This is because `end` parameter has the newline character (`'\\n'`) as the default value in the `print()` function.\n\nThis can be modified by the user as shown below:\n\n**Code**\n\n``` python\nprint(2 + 2, end=\",\")\nprint(2 * 3.5, end=\";\")\nprint(\"Hello, \" + \"world!\")\n```\n\n**Output**\n\n```\n4,7.0;Hello, world!\n```\n\n***Note***\n\nAll non-keyword arguments or expressions are converted to strings and written to the output stream by the `print()` function. They are separated by `sep` and followed by `end`. An empty `print()` invocation writes `end` parameter (an empty line as `end` defaults to the newline character `'\\n'`).\n\n# Operators \u0026 Expressions\n\n## Introduction to Operators\n\nOperators are symbols that perform a single simple task or operation on one or more values resulting in a single evaluated value. \n\nThe values on which these operators are applied are called **operands**.\n\n### Unary Operators\n\nUnary operators are applied on a single operand positioned on right side of the operator. \n\nFollowing are some unary operators available in Python:\n\n- `+` (plus): The unary `+` operator does not change the value of the operand.\n- `-` (minus): The unary `-` operator changes the sign of the operand.\n- `~` (bitwise `NOT`): The unary `~` results in the bit-wise inversion of the integer operand. The bit-wise inversion of `x` is defined as `-(x+1)`.\n\n``` python\n\u003e\u003e\u003e x = 5\n\u003e\u003e\u003e -x\n-5\n\u003e\u003e\u003e +x\n5\n\u003e\u003e\u003e ~x\n-6\n```\n\n### Binary Operators\n\nBinary operators are applied on two operands. \n\nFor example, arithmetic operators (`+`, `–`, `*`, `/`) evaluate the result of mathematical computation of two values.\n\n### Operators in Python\n\nA rich set of operators are available in Python which can be categorized as follows:\n\n- Arithmetic Operators - `+`, `–`, `*`, `/`, `%`, `**`, `//`\n- Relational Operators - `==`, `!=`, `\u003e`, `\u003e=`, `\u003c`, `\u003c=`\n- Assignment Operators - `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `//=`\n- Logical Operators - `not`, `or`, `and`\n- Identity Operators - `is`, `is not`\n- Membership Operators - `in`, `not in`\n- Bitwise and Shift Operators - `\u0026`, `|`, `^`, `~`, `\u003c\u003c`, `\u003e\u003e`\n\n## Arithmetic Operators\n\nArithmetic operations can be performed in Python using the following arithmetic operators:\n\n**Addition**\n\nThe `+` operator adds the values of numeric operands.\n\n``` python\n\u003e\u003e\u003e 2 + 3 \n5\n\u003e\u003e\u003e 2 + 3.0\n5.0 \n```\n\nIn case the operands are of type `str`, `list` or `tuple`, the `+` operator concatenates these two sequences or strings.\n\n``` python\n\u003e\u003e\u003e 'edpunk' + 'python' \n'edpunkpython'\n\u003e\u003e\u003e [\"ed\", \"punk\"] + [\"python\", ]\n['ed', 'punk', 'python'] \n```\n\n**Subtraction**\n\nThe `-` operator subtracts the value of operand on right from the value of operand on left.\n\n``` python\n\u003e\u003e\u003e 2 - 3 \n-1\n```\n\n**Multiplication**\n\nThe `*` operator multiplies the values of numeric operands.\n\n``` python\n\u003e\u003e\u003e 2 * 3 \n6\n```\n\nIn case the operands are of type `str`, `list` or `tuple`, the `*` operator returns a sequence or string self-concatenated the specified number of times.\n\n``` python\n\u003e\u003e\u003e \"python\" * 3 \n'pythonpythonpython'\n\u003e\u003e\u003e ['ed', 'py'] * 3\n['ed', 'py', 'ed', 'py', 'ed', 'py']\n```\n\n**Division**\n\nThe `/` operator divides the value of operand on left by the value of operand on right and returns the real number quotient.\n\n``` python\n\u003e\u003e\u003e 6 / 2\n3.0\n\u003e\u003e\u003e 5 / 2\n2.5  \n```\n\n**Floor Division**\n\nThe `//` operator divides the value of operand on left by the value of operand on right and returns the integer quotient.\n\n``` python\n\u003e\u003e\u003e 5 // 2 \n2\n```\n\n**Modulus**\n\nThe `%` operator divides the value of operand on left by the value of operand on right and returns the remainder.\n\n``` python\n\u003e\u003e\u003e 5 % 2\n1\n```\n\n**Exponent**\n\nThe `**` operator raises the left operand to the power of the right operand.\n\n``` python\n\u003e\u003e\u003e 5 ** 2\n25  \n```\n\n## Relational Operators\n\nRelational operators are useful for comparing the values of the operands to determine their relationship. Following relational operators are available in Python:\n\n**Equals to**\n\nThe `==` operator returns `True` if the value of operand on left is same as the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 2 == 2\nTrue\n\u003e\u003e\u003e 2 == 3\nFalse\n```\n\nIn case of sequence operands like `str`, `list` or `tuple`, the result is `True` if both the sequences are exactly the same.\n\n``` python\n\u003e\u003e\u003e \"python\" == \"python\"\nTrue\n\u003e\u003e\u003e \"pypi\" == \"python\"\nFalse\n\u003e\u003e\u003e [1, 2, 3] == [1, 2, 3]\nTrue\n```\n\nAs a sequence is an ordered collection of items, so the order in which the items are positioned is very important.\n\n``` python\n\u003e\u003e\u003e [2, 1, 3] == [1, 2, 3]\nFalse\n```\n\n**Not equal to**\n\nThe `!=` operator returns `True` if the value of operand on left is not equal to the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 2 != 2\nFalse\n\u003e\u003e\u003e 2 != 3\nTrue\n\u003e\u003e\u003e 'py' != 'oy'\nTrue\n\u003e\u003e\u003e [2, 1, 3] != [1, 2, 3]\nTrue\n\u003e\u003e\u003e [1, 2, 3] != [1, 2, 3]\nFalse\n```\n\n**Greater than**\n\nThe `\u003e` operator returns `True` if the value of operand on left is greater than the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 3 \u003e 2\nTrue\n\u003e\u003e\u003e 2 \u003e 2\nFalse\n```\n\nIn case of strings operands, `\u003e` operator perform comparison according to the Unicode code point (integer) of each character one-by-one. \n\nThe Unicode code point of a character can be obtained using the `ord()` function in Python. \n\nThe code point of first character of both operands are compared. In case they are equal, the code point of next character of both operands are compared and the process continues. \n\nFor example,\n\n``` python\n\u003e\u003e\u003e \"python\" \u003e \"Python\"\nTrue\n```\n\nThe code point of `\"p\"` (`112`) is greater than the code point of `\"P\"` (`80`). As `112` is greater than `80` the expression evaluates to `True`.\n\nLet us take another example:\n\n``` python\n\u003e\u003e\u003e \"pYthon\" \u003e \"python\"\nFalse\n```\n\nThe code point of first character is same (`112`), so the next set of characters are compared. The code point of `\"Y\"` (`89`) is not greater than the code point of `\"y\"` (`121`) so the expression evaluates to `False`.\n\nIf two string operands `p` and `q` are of unequal lengths (`len(p) \u003c len(q)`) and `p` is a substring of `q` such that `q = pt` where t is any string of length greater than `0`, then `q \u003e p` returns `True`.\n\n``` python\n\u003e\u003e\u003e \"python\" \u003e \"py\"\nTrue\n```\n\nIn case of sequence operands like `list` or `tuple`, the items are compared one-by-one starting from index `0`.\n\n``` python\n\u003e\u003e\u003e [\"p\",\"py\",\"PY\"] \u003e [\"p\",\"Py\",\"PY\"]\nTrue\n\u003e\u003e\u003e [1, 3] \u003e [1, 2]\nTrue\n\u003e\u003e\u003e [1, 3, 4] \u003e [1, 2]\nTrue\n```\n\nIn the above examples, `\"py\"` is greater than `\"Py\"` and `3` is greater than `2` respectively.\n\nIf two sequences are of unequal lengths and the smaller sequence is the starting subsequence of the larger one, then the larger sequence is considered greater than the smaller one.\n\n``` python\n\u003e\u003e\u003e [1, 2, 4] \u003e [1, 2]\nTrue\n```\n\n**Greater than or equal to**\n\nThe `\u003e=` operator returns `True` if the value of operand on left is greater than or equal to the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 3 \u003e= 3\nTrue\n\u003e\u003e\u003e 2 \u003e= 3\nFalse\n```\n\nIn case of sequence operands (`str`, `list`, `tuple`), the comparison operation performed is along the same lines as the `\u003e` operator discussed above.\n\n``` python\n\u003e\u003e\u003e \"python\" \u003e= \"Python\"\nTrue\n\u003e\u003e\u003e \"python\" \u003e= \"python\"\nTrue\n\u003e\u003e\u003e [\"py\", \"py\", \"PY\"] \u003e= [\"py\", \"Py\", \"PY\"]\nTrue\n\u003e\u003e\u003e [1, 2] \u003e= [1, 2]\nTrue\n\u003e\u003e\u003e [1, 2, 4] \u003e= [1, 2]\nTrue\n```\n\n**Less than**\n\nThe `\u003c` operator returns `True` if the value of operand on left is less than the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 2 \u003c 3\nTrue\n\u003e\u003e\u003e 3 \u003c 3\nFalse\n```\n\nIn case of sequence operands (`str`, `list`, `tuple`), the comparison operation performed is along the same lines as the `\u003e` operator discussed above.\n\n``` python\n\u003e\u003e\u003e \"file\" \u003c \"Pile\"\nFalse\n# f(102) is \u003e P(80)\n\u003e\u003e\u003e \"py\" \u003c \"python\"\nTrue\n\u003e\u003e\u003e [\"Py\", \"PY\"] \u003c [\"py\", \"PY\"]\nTrue\n\u003e\u003e\u003e ['a', 2] \u003c ['a', 3]\nTrue\n\u003e\u003e\u003e [1, 2] \u003c [1, 2, 4]\nTrue\n```\n\n**Less than or equal to**\n\nThe `\u003c=` operator returns `True` if the value of operand on left is lesser than or equal to the value of operand on right.\n\n``` python\n\u003e\u003e\u003e 2 \u003c= 3\nTrue\n\u003e\u003e\u003e 3 \u003c= 3\nTrue\n```\n\nIn case of sequence operands (`str`, `list`, `tuple`), the comparison operation performed is along the same lines as the `\u003e` operator discussed above.\n\n``` python\n\u003e\u003e\u003e \"file\" \u003c= \"Pile\"\nFalse\n# f(102) is \u003e P(80)\n\u003e\u003e\u003e \"py\" \u003c= \"python\"\nTrue\n\u003e\u003e\u003e [\"Py\", \"PY\"] \u003c= [\"py\", \"PY\"]\nTrue\n\u003e\u003e\u003e ['a', 3] \u003c= ['b', 2]\nTrue\n\u003e\u003e\u003e [1, 2] \u003c= [1, 2, 4]\nTrue\n```\n\n## Assignment Operators\n\nThe assignment symbol (`=`) serves as a delimiter between the name and value in an assignment statement. \n\nIt binds (or rebinds) a value (data, variable, expression) on the right to the target variable on the left.\n\n``` python\n\u003e\u003e\u003e x = 1\n\u003e\u003e\u003e x\n1\n\u003e\u003e\u003e y = x\n\u003e\u003e\u003e y\n1\n\u003e\u003e\u003e y = \"python\"\n\u003e\u003e\u003e y\n'python'\n```\n\nBinary operators can be combined with the assignment symbol to create **Augmented Assignment Operators**. \n\nThese operators perform the binary operation on the two operands and assign the result to the original target (left operand). \n\nIf `\u003cop\u003e` is a binary operator, then the expression `a \u003cop\u003e= b` containing the augmented assignment operator is equivalent to `a = a \u003cop\u003e b`.\n\n**`+=`**\n\nThe `+=` operator adds a value (right operand) to the variable (left operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 2\n\u003e\u003e\u003e a += 3\n\u003e\u003e\u003e a\n5\n\u003e\u003e\u003e x = \"hello\"\n\u003e\u003e\u003e y = \"world\"\n\u003e\u003e\u003e x += y\n\u003e\u003e\u003e x\n'helloworld'\n```\n\n**`-=`**\n\nThe `-=` operator subtracts a value (right operand) from the variable (left operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 3\n\u003e\u003e\u003e a -= 2\n\u003e\u003e\u003e a\n1\n```\n\n**`*=`**\n\nThe `*=` operator multiplies a value (right operand) to the variable (left operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 3\n\u003e\u003e\u003e a *= 2\n\u003e\u003e\u003e a\n6\n\u003e\u003e\u003e x = \"hi\"\n\u003e\u003e\u003e x *= 3\n\u003e\u003e\u003e x\n'hihihi'\n```\n\n**`/=`**\n\nThe `/=` operator divides the variable (left operand) by a value (right operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 4\n\u003e\u003e\u003e a /= 2\n\u003e\u003e\u003e a\n2.0\n```\n\n**`//=`**\n\nThe `//=` operator floor divides the variable (left operand) by a value (right operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 5\n\u003e\u003e\u003e a //= 2\n\u003e\u003e\u003e a\n2\n```\n\n**`**=`**\n\nThe `**=` operator raises the variable (left operand) to a power (right operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 4\n\u003e\u003e\u003e a **= 2\n\u003e\u003e\u003e a\n16\n```\n\n**`%=`**\n\nThe `%=` operator computes modulus of the variable (left operand) and a value (right operand) and assigns the result to that variable.\n\n``` python\n\u003e\u003e\u003e a = 4\n\u003e\u003e\u003e a %= 3\n\u003e\u003e\u003e a\n1\n```\n\n## Logical Operators\n\nExpressions using logical operators evaluate to a boolean value (`True` or `False`) based on the logical state of the operands. \n\n### Logical State of Operands\n\nIn Python, all values except `0`, `None`, `False`, `\"\"`, `''`, `()`, `[]`, `{}` have their logical state as `True`.\n\n`bool()` built-in function can be used to determine the logical state of literals, variables or expressions.\n\nThe logical state of the following literals is `False`.\n\n``` python\n\u003e\u003e\u003e bool(False)\nFalse\n\u003e\u003e\u003e bool(0)\nFalse\n\u003e\u003e\u003e bool([])\nFalse\n\u003e\u003e\u003e bool(None)\nFalse\n\u003e\u003e\u003e bool(\"\")\nFalse\n\u003e\u003e\u003e bool([])\nFalse\n\u003e\u003e\u003e bool(())\nFalse\n\u003e\u003e\u003e bool({})\nFalse\n```\n\nSome example literals having boolean state as `True` are provided below.\n\n``` python\n\u003e\u003e\u003e bool(True)\nTrue\n\u003e\u003e\u003e bool(1)\nTrue\n\u003e\u003e\u003e bool(2.0)\nTrue\n\u003e\u003e\u003e bool(100)\nTrue\n\u003e\u003e\u003e bool(\"python\")\nTrue\n\u003e\u003e\u003e bool([\"py\", \"thon\"])\nTrue\n```\n\n**`not`**\n\nThe logical state of an operand can be reversed (`False` to `True`, and vice versa) using the logical `not` operator.\n\n``` python\n\u003e\u003e\u003e n = 5\n\u003e\u003e\u003e bool(n)\nTrue\n\u003e\u003e\u003e bool(not n)\nFalse\n```\n\n**`or`**\n\nThe logical `or` operator returns `True` if the logical state of any of the two operands is `True`.\n\n``` python\n\u003e\u003e\u003e True or False\nTrue\n\u003e\u003e\u003e bool(1 or 0)\nTrue\n\u003e\u003e\u003e False or False\nFalse\n```\n\n**`and`**\n\nThe logical `and` operator returns `True` if the logical state of both the operands is `True`.\n\n``` python\n\u003e\u003e\u003e True and True\nTrue\n\u003e\u003e\u003e True and False\nFalse\n\u003e\u003e\u003e bool(10 and 20)\nTrue\n\u003e\u003e\u003e bool(1 and 0)\nFalse\n```\n\n## Identity Operators\n\nWe have already witnessed how Python treats every value or data item as an object. \n\nThe relational operator `==` can be used to test whether the operands contain the same value. \n\n``` python\n\u003e\u003e\u003e n = 1\n\u003e\u003e\u003e n2 = 1\n\u003e\u003e\u003e n == n2\nTrue\n```\n\nThis operator however does not check if both the operands are referring to the same object or different objects. \n\nThe identity operators `is` and `is not` are used to test whether two objects have the same or different identity (pointing to the same location in memory) respectively.  \n\n`a is b` is equivalent to `id(a) == id(b)`, where `id()` is the built-in function which returns the identity of an object.\n\n``` python\n\u003e\u003e\u003e n = 1\n\u003e\u003e\u003e n2 = 1\n\u003e\u003e\u003e n is n2\nTrue\n```\n\nIn the above example, both variables `n` and `n2` point to that same memory location (same object).\n\n``` python\n\u003e\u003e\u003e l = [1, 2, 3]\n\u003e\u003e\u003e l2 = [1, 2, 3]\n\u003e\u003e\u003e l == l2\nTrue\n\u003e\u003e\u003e l is l2\nFalse\n```\n\nIn the above example, both lists `l` and `l2` although contain items with same values, are actually two different objects occupying different memory locations.\n\n## Membership Operators\n\nThe operators `in` and `not in` test whether a value is present or not present in an iterable (string, list, tuple, set, dictionary).\n\n``` python\n\u003e\u003e\u003e 1 in [1, 2, 3]\nTrue\n\u003e\u003e\u003e \"ed\" in [\"ed\", \"py\", \"hi\"]\nTrue\n\u003e\u003e\u003e \"ed\" in (\"ed\", \"py\", \"hi\")\nTrue\n\u003e\u003e\u003e 'ed' in {'ed': 1, 'py': 2}\nTrue\n\n\u003e\u003e\u003e \"pen\" not in [\"pencil\", \"ink\"]\nTrue\n\u003e\u003e\u003e \"pen\" not in [\"pen\", \"ink\"]\nFalse\n```\n\n## Expressions\n\nLiterals (constants), identifiers (variables) and operators can be combined to form an expression which always evaluates to a single value. \n\nFor example, `40 + marks` is an expression containing a literal (`40`), a variable (`marks`) and an operator (`+`).\n\nSome valid expressions are provided below:\n\n- `10`\n- `a`\n- `-a`\n- `a - 10`\n- `a + b`\n- `4.0 * 3.5`\n- `a == b`\n- `c in d`  \n- `a is T`\n- `\"Hello\" + \"World\"`\n- `15 - a*4`\n- `3*num + 9/4 - 10%count**2`\n\nAs shown above, standalone literals (like `10`) and variables (like `a`) are considered as expressions, but standalone operators are not expressions.\n\n### Chained Expression\n\nComparison operators can be chained together in Python. \n\nFor example, `lower \u003c= age \u003c= upper` is a valid chained expression which is equivalent to the expression - \n\n`lower \u003c= age and age \u003c= upper`. \n\nIf `a`, `b`, `c`, …, `y`, `z` are expressions and `op1`, `op2`, …, `opN` are comparison operators, then the chained expression `a op1 b op2 c ... y opN z` is equivalent to `a op1 b and b op2 c and ... y opN z`.\n\n### Conditional Expression\n\nPython does not have ternary operators (`?:`) like other programming languages. Hence, the keywords `if` and `else` are used to create conditional expressions which evaluates to a value based on the given condition.\n\nFor example,\n\n``` python\nvar = t_val if cond else f_val\n```\n\nIf the above condition `cond` evaluates to `True`, then the variable `var` is assigned `t_val`, else it is assigned `f_val`.\n\n``` python\n\u003e\u003e\u003e value = 1 if 2 \u003e 3 else -1\n\u003e\u003e\u003e value\n-1\n```\n\n## Operator Precedence with Examples\n\nWhile studying mathematics in middle school, we came across the **BODMAS** (Bracket, Of, Division, Multiplication, Addition, and Subtraction) rule which helps us in understanding how mathematical expressions are computed in the presence of multiple operators (`of`, `x`, `/`, `+`, `-`).\n\nIn Python, we have a large number of operators and a similar rule to determine the order of evaluation of an expression. This is known as **operator precedence** where the operator with higher precedence is evaluated before the operator with lower precedence in an expression.\n\nThe table below presents the precedence of operators in Python from highest to lowest. Operators in the same row have the same precedence, so in such cases the expression is evaluated from left to right.\n\n| Operator | Description |\n|--|--|\n| `(expressions...)` | Parenthesized expression (Group) |\n| `**` | Exponentiation |\n| `+x`, `-x`, `~x` | Unary positive, Unary negative, Bitwise `NOT` |\n| `*`, `@`, `/`, `//`, `%` | Multiplication, Matrix multiplication, Division, Floor division, Remainder |\n| `+`, `-` | Addition, Subtraction |\n| `\u003c\u003c`, `\u003e\u003e` | Shifts |\n| `\u0026` | Bitwise `AND` |\n| `^` | Bitwise `XOR` |\n| `\\|` | Bitwise `OR` |\n| `in`, `not in`, `is`, `is not`, `\u003c`, `\u003c=`, `\u003e`, `\u003e=`, `!=`, `==` | Membership, Identity \u0026 Comparisons |\n| `not x` | Boolean `NOT` |\n| `and` | Boolean `AND` |\n| `or` | Boolean `OR` |\n| `:=` | Assignment expression |\n\n### Exercises\n\n**Example 1**\n\nEvaluate the expression \n\n`15 - 2 * 4`\n\n**Solution**\n\nStep: `*` has higher precedence over `-`  \n`15 - 2 * 4`  \n= `15 - 8`  \n= `7`\n\n**Example 2**\n\nEvaluate the expression \n\n`15 - 2 + 4`  \n\n**Solution**\n\nStep: `-` and `+` have the same order of precedence so the expression is evaluated left to right  \n`15 - 2 + 4`  \n= `13 + 4`  \n= `17`\n\n**Example 3**\n\nEvaluate the expression \n\n`15 - (2 + 4)`\n\n**Solution**\n\nParenthesized expression `(...)` has the highest precedence so `+` is evaluated first  \n`15 - (2 + 4)`  \n= `15 - 6`  \n= `9`\n\n**Example 4**\n\nEvaluate the expression \n\n`3 * 2 + 9 / 4 - 10 % 2 ** 2`\n\n**Step 1**\n\n`**` takes precedence  \n`3 * 2 + 9 / 4 - 10 % 2 ** 2`  \n= `3 * 2 + 9 / 4 - 10 % 4`\n\n**Step 2**\n\n`*`, `/` and `%` have the same precedence so they are evaluated left to right.  \n`3 * 2 + 9 / 4 - 10 % 4`  \n= `6 + 2.25 - 2`\n\n**Step 3**\n\n`+` and `-` evaluation  \n`6 + 2.25 - 2`  \n= `6.25`\n\n**Example 5**\n\nEvaluate the expression \n\n`20 / 4 // 2 * 2 - 4 + 20`\n\n**Step 1**\n\n`*`, `/`, `//` and `%` have the same precedence so they are evaluated left to right.  \n`20 / 4 // 2 * 2 - 4 + 20`  \n= `5 // 2 * 2 - 4 + 20`  \n= `2 * 2 - 4 + 20`  \n= `4 - 4 + 20`\n\n**Step 2**\n\n`+` and `-` evaluation  \n`4 - 4 + 20`  \n= `20`\n\n**Example 6**\n\nEvaluate the expression \n\n`not 6 \u003c= 4 and 3 ** 3 \u003e 12 / 3`\n\n**Step 1**\n\n`**` takes precedence  \n`not 6 \u003c= 4 and 3 ** 3 \u003e 12 / 3`  \n= `not 6 \u003c= 4 and 27 \u003e 12 / 3`\n\n**Step 2**\n\n`/` is next in line of precedence  \n`not 6 \u003c= 4 and 27 \u003e 12 / 3`  \n= `not 6 \u003c= 4 and 27 \u003e 4`\n\n**Step 3**\n\nComparison operators are next in line of precedence  \n`not 6 \u003c= 4 and 27 \u003e 4`  \n= `not False and True`\n\n**Step 4**\n\nBoolean `NOT` is evaluated  \n`not False and True`  \n= `True and True`\n\n**Step 5**\n\nBoolean `AND` is evaluated  \n`True and True`  \n= `True`\n\n# Errors \u0026 Exception Handling\n\n## Error Types\n\nA program contains **\"bug(s)\"** when it is unable to execute or produces an output which is different from what is expected. These bugs are generally introduced by a programmer unknowingly. \n\nThe process of identifying and eliminating these bugs or errors is known as **debugging**.\n\nThe three major types of errors are:\n\n- Syntax Error\n- Runtime Error\n- Logical Error\n\n## Syntax Error\n\nSyntax error occurs when the program contains any statement that does not follow the prescribed Python rules or syntax which makes it difficult for the Python interpreter to parse (understand) and execute it.\n\nSome common syntax errors are:\n\n- Missing/Misspelled keyword\n- Missing colon or brackets\n- Empty block\n- Incorrect position of keyword\n- Incorrect block indentation\n\n### Script Mode\n\nWhen a code containing syntactically incorrect statement is executed using script mode via IDLE, an error dialog box is displayed.\n\n![Syntax Error Dialog](images/0702a.png)\n\nOn closing the dialog box, the incorrect part of the code, the potential cause of error, is highlighted in red.\n\n![Syntax Error Highlighted](images/0702b.png)\n\nThis error has to be rectified to execute the program correctly.\n\n### Interactive Mode\n\nWhen a syntactically incorrect statement is executed in the Python console (interactive mode), the Python interpreter displays it and also adds a little arrow (`^`) pointing at the entry point or token where the error was detected.\n\n**Example**\n\n``` python\n\u003e\u003e\u003e while True print('Hi!')\n  File \"\u003cstdin\u003e\", line 1\n    while True print('Hi!')\n               ^\nSyntaxError: invalid syntax\n```\n\nIn the above example there is a syntax error with `^` pointing to `print` function which the parser is unable to understand as there is a missing `:` (colon) after `True`.\n\n## Runtime Error\n\nA runtime error occurs when the program is terminated prematurely by the Python interpreter as it is unable to execute a statement although it is correct syntactically.\n\nSome runtime error examples are:\n\n- **ImportError**: Raised when the `import` statement has trouble loading a module or any definition from a module.\n- **IOError**: Raised when the interpreter is not able to open the file specified in the program.\n- **ZeroDivisionError**: Raised when a number is divided or mod by zero.\n- **NameError**: Raised when an identifier is encountered which has not been defined.\n- **ValueError**: Raised when an argument or operand is of required data type, but has undesired value.\n- **IndexError**: Raised when the provided index in a sequence (string, list, tuple, etc.) is out of range.\n- **KeyError**: Raised when a dictionary key is not found in the set of existing keys.\n- **TypeError**: Raised while performing an operation on incompatible types.\n- **IndentationError**: Raised when the indentation of a statement or code block is incorrect.\n\n### Runtime Error Examples\n\n**ZeroDivisionError**\n\n``` python\nn = 100\nd = 0\nprint(n/d)\n```\n\n``` python\nTraceback (most recent call last):\n  File \"/Users/name/Desktop/test.py\", line 3, in \u003cmodule\u003e\n    print(n/d)\nZeroDivisionError: division by zero\n```\n\n**NameError**\n\n``` python\nn = 100\nprint(d)\n```\n\n``` python\nTraceback (most recent call last):\n  File \"/Users/name/Desktop/test.py\", line 2, in \u003cmodule\u003e\n    print(d)\nNameError: name 'd' is not defined\n```\n\n**KeyError**\n\n``` python\nd = {1: \"1st\", 2: \"2nd\"}\nprint(d[3])\n```\n\n``` python\nTraceback (most recent call last):\n  File \"/Users/name/Desktop/test.py\", line 2, in \u003cmodule\u003e\n    print(d[3])\nKeyError: 3\n```\n\n**TypeError**\n\n``` python\nn =1\ns = \"a\"\ntot = n + s\n```\n\n``` python\nTraceback (most recent call last):\n  File \"/Users/name/Desktop/test.py\", line 3, in \u003cmodule\u003e\n    tot = n + s\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n```\n\n## Logical Error\n\nLogical error or Semantic error is caused when the issue lies in the underlying meaning of the code which leads to an incorrect output. \n\nAs compared to syntax or runtime error there is no termination of the program. \n\nDebugging a logical error requires inspection of the entire code as no guiding error message is displayed.\n\n### Example\n\nLet us write a program to calculate the average of two numbers\n\n``` python\nn = 10\nm = 20\navg = n + m / 2\nprint(\"Average:\", avg)\n```\n\nOn executing the script the result is \n\n```\nAverage: 20.0\n```\n\nThis is incorrect as there is a logical error in the code. \n\nSince `/` has a higher precedence over `+`, `m / 2` is being computed first. \n\nWe can modify the code to get rid of the logical error.\n\n``` python\nn = 10\nm = 20\navg = (n + m) / 2\nprint(\"Average:\", avg)\n```\n\nOn executing the script, we now obtain the correct result \n\n```\nAverage: 15.0\n```\n\n## Exceptions\n\nWe have witnessed that even if a program is syntactically correct, its execution may lead to a run-time error. \n\nThis error detected during execution is known as an **exception** which is an object created by the Python interpreter containing information regarding the error like type of error, file name and the location of the error (line number, token) in the program.\n\nSome of the built-in exceptions that are raised by the Python interpreter are - `ImportError`, `ZeroDivisionError`, `NameError`, `ValueError`, `IndexError`, `KeyError`, `TypeError` and `IndentationError`.\n\nApart from the Python interpreter, a programmer can also trigger and raise an exception (along with a custom message) in the code using `raise` or `assert` statement.\n\n### raise\n\nThe `raise` statement can be used to throw an exception in a program. The exception may or may not contain the custom error message (recommended).\n\nLet us consider a program which accepts two numbers (`a` and `b`) from the user and prints the result `a/b`.\n\n**Code**\n\n``` python\na = int(input(\"Enter a: \"))\nb = int(input(\"Enter b: \"))\nprint(\"a/b =\", a/b)\n```\n\n**Output**\n\n```\nEnter a: 10\nEnter b: 0\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 3, in \u003cmodule\u003e\n    print(\"a/b =\", a/b)\nZeroDivisionError: division by zero\n```\n\nIt can be observed that the Python interpreter raises a `ZeroDivisionError` when the value of `b` is entered as `0`.\n\nNow we can modify the above code to raise an exception for such scenarios.\n\n**Code**\n\n``` python\na = int(input(\"Enter a: \"))\nb = int(input(\"Enter b: \"))\nif b==0:\n    raise Exception()\nprint(\"a/b =\", a/b)\n```\n\n**Output**\n\n```\nEnter a: 10\nEnter b: 0\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 4, in \u003cmodule\u003e\n    raise Exception()\nException\n```\n\nAn exception is raised, but it is not helpful. \n\nLet us add some custom error message.\n\n**Code**\n\n``` python\na = int(input(\"Enter a: \"))\nb = int(input(\"Enter b: \"))\nif b==0:\n    raise Exception(\"b is zero\")\nprint(\"a/b =\", a/b)\n```\n\n**Output**\n\n```\nEnter a: 10\nEnter b: 0\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 4, in \u003cmodule\u003e\n    raise Exception(\"b is zero\")\nException: b is zero\n```\n\nWe can also raise any specific type of error as per the program logic as shown below:\n\n**Code**\n\n``` python\na = int(input(\"Enter a: \"))\nb = int(input(\"Enter b: \"))\nif b==0:\n    raise ValueError(\"The value of b cannot be zero\")\nprint(\"a/b =\", a/b)\n```\n\n**Output**\n\n```\nEnter a: 10\nEnter b: 0\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 4, in \u003cmodule\u003e\n    raise ValueError(\"The value of b cannot be zero\")\nValueError: The value of b cannot be zero\n```\n\n### assert\n\nAn `assert` statement is often used during code development to act like a safety valve which notifies the programmer in case the test expression is evaluated as `False`. \n\nIf the test expression’s value is `True`, the code execution continues normally. \n\nAn `AssertionError` is raised if the value is `False`.\n\n**Code**\n\n``` python\na = 3\nb = 4\nassert a == b\nc = 5\n```\n\n**Output**\n\n```\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 3, in \u003cmodule\u003e\n    assert a == b\nAssertionError\n```\n\nThe statement also allows for a message to be attached to the `AssertionError`.\n\n**Code**\n\n``` python\na = 3\nb = 4\nassert a == b, \"a is not equal to b\"\nc = 5\n```\n\nOutput:\n\n```\nTraceback (most recent call last):\n  File \"/Users/name/test.py\",\n   line 3, in \u003cmodule\u003e\n    assert a == b, \"a is not equal to b\"\nAssertionError: a is not equal to b\n```\n\n## Exception Handling\n\nException handling is the process of properly handling an exception which can potentially crash a program during execution.\n\nWhen an error occurs, the program throws an exception. \n\nThe runtime system attempts to find an **exception handler**, a block of code that can handle a particular type of error. Once located, the suitable exception handler **catches the exception** and executes the code block which can attempt to recover from the error. In case the error is unrecoverable, the handler provides a way to gently exit the program.\n\nThe `try` statement in Python specifies the exception handlers and/or cleanup code for a code block. \n\nThe various parts of a try statement are:\n\n- `try` block: The block of statements within which an exception might be thrown.\n- `except` clause(s): One or more exception handlers. Each `except` clause handles a particular type of exception. In case an exception of a particular type occurs in the `try` block, the corresponding `except` clause code block is executed.\n- `else` clause: An optional `else` clause can also be included after the last `except` block. In case no exception is raised, none of the `except` blocks are executed. In this case, the `else` code block is executed.\n- `finally` clause: An optional `finally` clause can be added at the end of the try statement which includes a block of statements that are executed regardless of whether or not any error occurred inside the try block. This block is usually setup for code cleanup and closing all open file objects.\n\nHere's the general form of these statements:\n\n``` python\ntry:\n    [code block]\nexcept [exception1 [as identifier1]]:\n    [exception code block 1]\nexcept [exception2 [as identifier2]]:\n    [exception code block 2]\n...\n...\nelse:\n    [code block executes if no error]\nfinally:\n    [code block always executed]\n```\n\n# Control Flow\n\n## Introduction to Control Flow\n\nA simple Python program can be treated as a block of code where each statement is executed by the Python interpreter in a sequential order from top to bottom. \n\nBut, in real world we would like to have some control over the execution of code such as:\n\n- skip or execute a block (set of statements) based on certain conditions\n- execute a block repeatedly\n- redirect execution to another set of statements  \n- breaking up the execution\n\nThis control over the flow of execution is provided by **Control Flow Statements**. \n\nThey can be categorized as:\n\n- Sequential\n- Selection\n- Iteration/Repetition\n- Jump\n- Procedural Abstraction - A sequence of statements are referenced as a single function or method call\n- Recursion - Calling a method/function in the same method/function\n- Exception Handling\n\n## Sequential Flow\n\nBy default the code statements in Python are executed in Sequential order.\n\nThe below flow chart demonstrates how 3 statements are executed in a sequential order.\n\n![Sequential Flow](images/0802a.png)\n\nFor example, \n\n``` python\na = 2\nb = 3\nc = a*b\nprint(c)\n```\n\nThe above code will be executed in the following sequential order:\n\n![Sequential Flow of Code](images/0802b.png)\n\n## Selection Statements: if .. else\n\nSelection statements, also known as Decision making statements, control the flow of a program based on the outcome of one or many test expression(s). If the condition is satisfied (`True`) then the code block is executed. There is also a provision to execute another code block if the condition is not satisfied.\n\nThis process can be demonstrated using the below flowchart:\n\n![Selection Flow](images/0803a.png)\n\nPython supports `if` compound statement which provides this control. The `if` statement comprises:\n\n- `if` keyword followed by the test expression, a colon `:` and an indented block of code which gets executed if the condition is satisfied\n- (optional) one or many `elif` clause followed by their test conditions and their corresponding code blocks\n- (optional) `else` clause and the corresponding code block which gets executed if none of the above conditions (`if`, `elif`) are satisfied\n\nAn example `if` statement is provided below:\n\n``` python\n'''\nage - age of loan applicant\nemp - is employed (bool)\ncscore - credit scrore of applicant\n'''\nresult = None\nif age \u003c 26 and not emp:\n    result = \"Loan rejected\"\nelif age \u003e 35 and cscore \u003c 600:\n    result = \"Loan rejected\"\nelse:\n    result = \"Loan approved\"\nprint(result)\n```\n\nThe control flow view of the above code is:\n\n![Selection in Flow of Code](images/0803b.png)\n\n### Examples\n\nLet us go through some programming problems which utilize selection statements.\n\n**1. Absolute Value**\n\nWrite a program to output the magnitude of difference between two numbers using conditional statement.\n\n**Code**\n\n``` python\nn1 = int(input(\"Enter 1st number: \"))\nn2 = int(input(\"Enter 2nd number: \"))\n\nif n1 \u003e n2:\n    diff = n1 - n2\nelse:\n    diff = n2 - n1\n\nprint(\"The difference of\", n1, \"and\", n2, \"is\", diff)\n```\n\n**Output**\n\n```\nEnter 1st number: 12\nEnter 2nd number: 15\nThe difference of 12 and 15 is 3\n```\n\n**2. Sorting 3 Numbers**\n\nWrite a program to accept 3 numbers from the user and print them in ascending order of value.\n\n**Code**\n\n``` python\na = int(input(\"Enter 1st number: \"))\nb = int(input(\"Enter 2nd number: \"))\nc = int(input(\"Enter 3rd number: \"))\n\nif b \u003c a: \n    # Swapping the values of a and b\n    a, b = b, a \n          \nif c \u003c b: \n    b, c = c, b \n    if b \u003c a: \n        a, b = b, a\n\nprint(\"The numbers in sorted order:\", a, \",\", b, \",\", c)\n```\n\n**Output**\n\n```\nEnter 1st number: 9\nEnter 2nd number: 2\nEnter 3rd number: 6\nThe numbers in sorted order: 2 , 6 , 9\n```\n\n**3. Divisibility**\n\nWrite a program to accept two numbers and test if the first number is divisible by the second number.\n\n**Code**\n\n``` python\na = int(input(\"Enter 1st number: \"))\nb = int(input(\"Enter 2nd number: \"))\n\nif a % b == 0: \n    print(a, \"is divisible by\", b)\nelse:\n    print(a, \"is not divisible by\", b)\n```\n\n**Output**\n\n```\nEnter 1st number: 9\nEnter 2nd number: 2\n9 is not divisible by 2\n\nEnter 1st number: 9\nEnter 2nd number: 3\n9 is divisible by 3\n```\n\n## Iteration: for\n\nIteration statements, also known as Looping statements, allow repeated execution of a code block. \n\nPython provides `for` and `while` statements to perform iteration.\n\nThe `for` statement can be used to iterate over the items of a sequence (`list`, `string`, `tuple`, `range`). It can also be used to iterate over unordered sequences like `set` and `dict`.\n\nThis process can be demonstrated using the below flowchart:\n\n![Iteration in Flow of Code Python](images/0804a.png)\n\nLet us go through some code examples to demonstrate how `for` statement can be used to iterate over sequences.\n\n### List Iteration\n\n**Code**\n\n``` python\ncars = [\"Hyundai\", \"Honda\", \n        \"Ford\", \"Toyota\", \n        \"BMW\", \"Volkswagen\"]\nfor make in cars:\n    print(make)\n```\n\n**Output**\n\n```\nHyundai\nHonda\nFord\nToyota\nBMW\nVolkswagen\n```\n\n### Tuple Iteration\n\n**Code**\n\n``` python\ncars = (\"Hyundai\", \"Honda\", \n        \"Ford\", \"Toyota\", \n        \"BMW\", \"Volkswagen\")\nfor make in cars:\n    print(make)\n```\n\n**Output**\n\n```\nHyundai\nHonda\nFord\nToyota\nBMW\nVolkswagen\n```\n\n### String Iteration\n\n**Code**\n\n``` python\nname = \"python\"\nfor char in name:\n    print(char)\n```\n\n**Output**\n\n```\np\ny\nt\nh\no\nn\n```\n\n### Range Iteration\n\nThe `range` type represents an immutable sequence of numbers that is usually used in for loops for looping a certain number of times. `range` object always take the same (small) amount of memory, no matter the size of the range it represents, which is an advantage over a regular `list` or `tuple`.\n\n**Syntax**: `range(stop)` or  \n`range(start, stop[, step])`\n\n``` python\n\u003e\u003e\u003e range(10)\nrange(0, 10)\n\u003e\u003e\u003e list(range(10))\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\u003e\u003e\u003e list(range(1, 10, 2))\n[1, 3, 5, 7, 9]\n```\n\n`range()` function is widely used in a `for` statement to control the number of iterations and provide the index value (`i`) of each iteration.\n\n**Example #1**\n\nPrint multiples of 5 starting from 0 to 20.\n\n**Code**\n\n``` python\nfor i in range(5):\n    print(i*5)\n```\n\n**Output**\n\n```\n0\n5\n10\n15\n20\n```\n\n**Example #2**\n\nPrint all integers from 2 to 5 including the boundary values.\n\n**Code**\n\n``` python\nfor i in range(2, 6):\n    print(i)\n```\n\n**Output**\n\n```\n2\n3\n4\n5\n```\n\n**Example #3**\n\nPrint all odd numbers between 2 and 10.\n\n**Code**\n\n``` python\nfor i in range(3, 10, 2):\n    print(i)\n```\n\nor\n\n``` python\nfor i in range(2, 10):\n    if i % 2 != 0:\n        print(i)\n```\n\n**Output**\n\n```\n3\n5\n7\n9\n```\n\n**Example #4**\n\nPrint the index of all occurrences of `o` in `python programming`.\n\n**Code**\n\n``` python\ns = \"python programming\"\nfor i in range(len(s)):\n    if s[i] == \"o\":\n        print(i)\n```\n\n**Output**\n\n```\n4\n9\n```\n\n### Exercises\n\nLet us go through some programming problems which utilize the `for` iteration statement.\n\n**1. Compound Interest**\n\nWrite a program to calculate the total compound interest payable for given principal, interest rate (compounded annually) and total time (in years).\n\n**Code**\n\n``` python\nprin = float(input(\"Enter the principal amount: \"))\nrate = float(input(\"Enter the annual interest rate: \"))\ntime = int(input(\"Enter the loan duration (in years): \"))\n\namt = prin\nfor n in range(time):\n    amt += rate*amt/100\n\nprint(\"Total interest payable:\", amt - prin)\n```\n\n**Output**\n\n```\nEnter the principal amount: 500000\nEnter the annual interest rate: 5\nEnter the loan duration (in years): 3\nTotal interest payable: 78812.5\n```\n\n**2. Factorial**\n\nThe factorial of a positive integer `n`, denoted by `n!`, is the product of all positive integers less than or equal to `n`.  \n`n! = n×(n-1)×(n-2)...3×2×1`  \nWrite a program to calculate `n!` for a given `n` (assume `n` is greater than `0`).\n\n**Code**\n\n``` python\nn = int(input(\"Enter n: \"))\n\nfactorial = 1\nfor i in range(1, n+1):\n    factorial *= i\n\nprint(\"n! :\", factorial)\n```\n\n**Output**\n\n```\nEnter n: 6\nn! : 720\n```\n\n## Iteration: while\n\n`while` statement repeatedly executes a code block as long as the test condition is satisfied. \n\nUsually there is a statement at the end of the code block which updates the value of the variable being used in the test expression, so the the loop does not execute infinitely. \n\nA flowchart of the process is provided below:\n\n![while loop Iteration in Flow of Code](images/0805a.png)\n\nFor example, let us traverse a list and print the position(index) and value of each element until we reach the end of the list.\n\n**Code**\n\n``` python\ncars = [\"Hyundai\", \"Honda\", \n        \"Ford\", \"Toyota\", \n        \"BMW\", \"Volkswagen\"]\ni = 0  \nwhile i\u003clen(cars):    \n    print(i, cars[i])\n    i+=1\n```\n\n**Output**\n\n```\n0 Hyundai\n1 Honda\n2 Ford\n3 Toyota\n4 BMW\n5 Volkswagen\n```\n\nIn the above example, the test condition is `i\u003clen(cars)` and the update statement is `i+=1`.\n\n### Exercises\n\nLet us go through some programming problems which utilize the `while` iteration statement.\n\n**1. Compound Interest**\n\nWrite a program to calculate the total compound interest payable for given principal, interest rate (compounded annually) and total time (in years).\n\n**Code**\n\n``` python\nprin = float(input(\"Enter the principal amount: \"))\nrate = float(input(\"Enter the annual interest rate: \"))\ntime = int(input(\"Enter the loan duration (in years): \"))\n\namt = prin\nwhile time \u003e 0:\n    amt += rate*amt/100\n    time = time - 1\n\nprint(\"Total interest payable:\", amt - prin)\n```\n\n**Output**\n\n```\nEnter the principal amount: 500000\nEnter the annual interest rate: 5\nEnter the loan duration (in years): 3\nTotal interest payable: 78812.5\n```\n\n**2. Factorial**\n\nThe factorial of a positive integer `n`, denoted by `n!`, is the product of all positive integers less than or equal to `n`.  \n`n! = n×(n-1)×(n-2)...3×2×1`   \nWrite a program to calculate `n!` for a given `n` (assume `n` is greater than `0`).\n\n**Code**\n\n``` python\nn = int(input(\"Enter n: \"))\n\nfactorial = 1\nwhile n \u003e 0:\n    factorial *= n\n    n = n - 1\n\nprint(\"n! :\", factorial)\n```\n\n**Output**\n\n```\nEnter n: 6\nn! : 720\n```\n\n## Jump Statements\n\nJump statements are used to (abruptly) alter the flow of execution. \n\nSome of the jump statements available in Python are:\n\n### pass\n\nA `pass` statement acts as a placeholder and performs null (no) operation.\n\nVarious reasons for using the keyword `pass` are provided below:\n\n**1. Syntactical Requirement**\n\nUsing `pass` becomes a syntactical requirement for cases where the Python interpreter can raise a `SyntaxError` due to missing statements.  \n\nThe below code will execute successfully without any operation in the loop\n\n``` python\nfor i in range(6):\n    pass  \n```\n\nwhereas without `pass`\n\n``` python\nfor i in range(6):\n```\n\nwill throw the following `SyntaxError`\n\n```\nFile \"\u003cipython-input-18-f2ba5099d499\u003e\", line 1\n    for i in range(6):\n                    ^\nSyntaxError: unexpected EOF while parsing\n```\n\nSimilarly, inside an `if`\n\n``` python\nif 2 \u003c 3:\n    pass  \n```\n\nwhereas without `pass`\n\n``` python\nif 2 \u003c 3:\n```\n\nwill throw the following `SyntaxError`\n\n```\nFile \"\u003cipython-input-20-068861cce0a8\u003e\", line 1\n    if 2 \u003c 3:\n            ^\nSyntaxError: unexpected EOF while parsing\n```\n\n**2. Skipping Code Execution**\n\n`pass` can be used to skip code execution for certain cases. \n\nFor example,\n\n**Code**\n\n``` python\nl = [2, 3, 4, 5, 6]\nfor i in l:\n    if i%3 == 0:\n        pass\n    else:\n        print(i, \"is not divisible by 3\")\n```\n\n**Output**\n\n```\n2 is not divisible by 3\n4 is not divisible by 3\n5 is not divisible by 3\n```\n\n**3. Placeholders**\n\n`pass` can be used to create valid empty functions and classes as placeholders which can be modified in the future versions of code.\n\n``` python\ndef emptyFunction():\n    pass\n\nclass EmptyClass:\n    pass\n```\n\n### break\n\nThe `break` statement is used to terminate the execution of immediately enclosing `for` or `while` statement.\n\nThe below code will terminate the `for` loop when `i` is equal to `4`\n\n``` python\nfor i in range(10):\n    print(i)\n    if i == 4:\n        break\n```\n\n```\n0\n1\n2\n3\n4\n```\n\nIn a while statement,\n\n``` python\ni =0\nwhile i \u003c10:\n    print(i)\n    if i == 4:\n        break\n    i+=1\n```\n\n`break` will terminate the `while` loop when `i` is equal to `4`\n\n```\n0\n1\n2\n3\n4\n```\n\n### continue\n\n`continue` statement is used to skip the execution of successive statements and start the next iteration.\n\nThe below code will skip all candidates for an interview who have less than 4 years of work experience.\n\n``` python\npeople =  [{\"name\": \"ABC\", \"experience\": 6},\n           {\"name\": \"EFG\", \"experience\": 2},\n           {\"name\": \"JKL\", \"experience\": 5},\n           {\"name\": \"XYZ\", \"experience\": 3},]\nfor candidate in people:\n    if candidate[\"experience\"]\u003c4:\n        continue  \n    print(candidate[\"name\"], \"is selected for interview\")\n```\n\nOutput:\n\n```\nABC is selected for interview\nJKL is selected for interview\n```\n\n## Nested Loops\n\nWhen a loop is present inside another loop, it is known as a nested loop. \n\nFor each iteration of the outer loop, the inner loop undergoes complete iteration. Thus, if the outer loop has to undergo `n` iterations and the inner loop has to undergo `m` iterations, the code block inside the inner loop executes `n x m` times.  \n\nLet us go through a nested loop example:\n\n### Factorial\n\nWrite a program to print the factorial of all numbers in the range `1` to `10` (inclusive).\n\n**Code**\n\n``` python\nfor n in range(1, 11):\n    factorial = 1\n    for i in range(1, n+1):\n        factorial *= i\n    print(n,\"! =\", factorial)\n```\n\n**Output**\n\n```\n1 ! = 1\n2 ! = 2\n3 ! = 6\n4 ! = 24\n5 ! = 120\n6 ! = 720\n7 ! = 5040\n8 ! = 40320\n9 ! = 362880\n10 ! = 3628800\n```\n\n### Nested Loop - break\n\nA `break` statement inside the inner loop terminates only the inner loop whereas the outer loop is not affected.\n\nTo develop a better understanding, let us write a program to find all prime numbers between 2 and 40.\n\n**Code**\n\n``` python\nfor n in range(2, 40):\n    i = 2\n    while i \u003c n/2:\n        if n%i == 0:\n            break\n        i+=1\n    if i\u003en/2:\n        print(n,\"is prime\")\n```\n\n**Output**\n\n```\n2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n```\n\n# Strings\n\n## Strings: Introduction \u0026 Creation\n\nA String (`str`) is an **immutable** sequence of Unicode characters which is used to handle textual data in Python.\n\nThey can be specified by enclosing within:\n\n- Single quotes: `'embedded \"double\" quotes are allowed'`\n- Double quotes: `\"embedded 'single' quotes are allowed\"`\n- Triple quotes: `'''Three single quotes'''`, `\"\"\"Three double quotes\"\"\"`. \n\nTriple quoted strings can also span multiple lines.\n\nSome examples are provided below:\n\n``` python\ns = \"I am a String\"  \n\ns1 = \"\"\"A\nmultiline\nString\"\"\"\n\ns2 = '''Also a\nmultiline\nString'''\n```\n\n### Escape Characters\n\nThe backslash (`\\`) character can be used in a string to escape characters that otherwise have a special meaning, such as newline, linefeed, or the quote character.\n\n| Escape Sequence | Meaning |\n|--|--|\n| `\\\\` | Backslash (`\\`) |\n| `\\'` | Single quote (`'`) |\n| `\\\"` | Double quote (`\"`) |\n| `\\a` | ASCII Bell (BEL) |\n| `\\b` | ASCII Backspace (BS) |\n| `\\f` | ASCII Form-feed (FF) |\n| `\\n` | ASCII Linefeed (LF) |\n| `\\r` | ASCII Carriage Return (CR) |\n| `\\t` | ASCII Horizontal Tab (TAB) |\n| `\\v` | ASCII Vertical Tab (VT) |\n\nAlthough `\\'` and `\\\"` can be used to specify quote characters, Python allows embedding double quotes inside a single-quoted string (`'My name is \"Python\".'`) and single quotes inside a double-quoted string (`\"Python's World\"`).\n\n### Unicode Support\n\nPython string objects support Unicode characters. \n\nA unicode character can be specified as `\\u` followed by the 4 letter unicode (`\\uXXXX`).\n\n``` python\n\u003e\u003e\u003e print(\"E = mc\\u00B2\")\nE = mc²\n```\n\nIn the above example, `\\u00B2` is the unicode character which represents the 'SUPERSCRIPT TWO'. \n\n### Other Types to String\n\nIn case you want to create a string object from other data types, just use the built-in `str()` function as follows:\n\n``` python\n\u003e\u003e\u003e str(9)\n'9'\n\n\u003e\u003e\u003e str(10.0)\n'10.0'\n```\n\n## Accessing Characters of a String\n\nPython strings are \"immutable\", i.e., the state (value) of the objects cannot be modified after they are created. \n\nUsing the standard `[ ]` syntax and zero-based indexing, characters can be accessed in a string.\n\nIf `s = \"hello\"`,\n\n- `s[0]` will result in `h`\n- `s[2]` will result in `l`\n- `s[5]` will result in `IndexError: string index out of range` as the length of string is `5` (index `0` to `4`)\n- `s[2] = 'p'` will result in `TypeError: 'str' object does not support item assignment` as `s` is immutable\n\nPython also supports negative indexing, i.e., you can access the values of a string from right to left. \n\nIndex of `-1` denotes the last character of the string, `-2` is the second last character and so forth.\n\nIf `s = \"hello\"`,\n\n- `s[-1]` will result in `o`\n- `s[-4]` will result in `e`\n- `s[-6]` will result in `IndexError: string index out of range` as the length of string is `5` (negative index `-1` to `-5`)\n\n### Length of String\n\nThe built-in function `len()` returns the length of a string which is useful during string traversal or other string operations.\n\n``` python\n\u003e\u003e\u003e len(\"hello\")\n5\n\n\u003e\u003e\u003e s = \"sample text\"\n\u003e\u003e\u003e len(s)\n11\n\n\u003e\u003e\u003e p = \"python\"\n\u003e\u003e\u003e l = len(p)\n\u003e\u003e\u003e p[l-1]\n'n'\n```\n\n## String Operations\n\nWe can perform various operations on a string (sequence of characters) such as slicing, membership, concatenation and repetition.\n\n### Slicing\n\nIn Python, a character in a string can be easily accessed using its index.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e s[1]\n'e' \n```\n\nPython also provides a way to access a substring from a string. This substring is known as a **slice** and it can be obtained using the slice operator `[n:m]` which returns the part of the string from the start index (`n`) to the end index (`m`), including the first but excluding the last.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e s[1:3]\n'el' \n```\n\nIf the start index (`n`) is omitted, the default value of `n` is set as `0` which denotes the beginning of the string. If the end index (`m`) is omitted, the substring ends at the last character of the string.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e s[:3]\n'Hel'\n\u003e\u003e\u003e s[3:]\n'lo'\n\u003e\u003e\u003e s[:]\n'Hello'\n```\n\nNegative indexing is also supported in the slice operator.\n\n``` python\n\u003e\u003e\u003e s = \"Hello\"\n\u003e\u003e\u003e s[-4:-2]\n'el'\n```\n\nIn the above example, `-4` is","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanimator%2Flearn-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanimator%2Flearn-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanimator%2Flearn-python/lists"}