{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<small><small><i>\n", "All the IPython Notebooks in **Python Introduction** lecture series by **[Dr. Milaan Parmar](https://www.linkedin.com/in/milaanparmar/)** are available @ **[GitHub](https://github.com/milaan9/01_Python_Introduction)**\n", "</i></small></small>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Literals\n", "\n", "**Literal** is a raw data given in a **variable** or **constant**. In Python, there are various types of literals they are as follows:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Numeric Literals\n", "\n", "Numeric Literals are **immutable (unchangeable)**. Numeric literals can belong to 3 different numerical types **`Integer`**, **`Float`** and **`Complex`**.\n", "\n", "<div>\n", "<img src=\"img/li0.png\" width=\"500\"/>\n", "</div>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Number data types in Python:\n", "\n", "1. Integers: Integer(negative, zero and positive) numbers\n", " - Example:\n", " - ... -3, -2, -1, 0, 1, 2, 3 ...\n", "\n", "\n", "2. Floating Point Numbers(Decimal numbers)\n", " - Example:\n", " - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...\n", "\n", "\n", "3. Complex Numbers\n", " - Example:\n", " - 1 + j, 2 + 3j, 1 - 1j" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:41.965572Z", "start_time": "2021-10-02T07:56:41.949947Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 100 200 300\n", "10 99\n", "10.5 150.0\n", "3.14j 3.14 0.0\n" ] } ], "source": [ "# Example:\n", "\n", "a = 0b1010 #Binary Literals\n", "b = 100 #Decimal Literal\n", "c = 0o310 #Octal Literal\n", "d = 0x12c #Hexadecimal Literal\n", "\n", "# Integer Literal\n", "int_1 = 10\n", "int_2 = 99\n", "\n", "\n", "# Float Literal\n", "float_1 = 10.5\n", "float_2 = 1.5e2\n", "\n", "\n", "# Complex Literal\n", "x = 3.14j\n", "\n", "print(a, b, c, d)\n", "print(int_1, int_2)\n", "print(float_1, float_2)\n", "print(x, x.imag, x.real)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above program\n", "\n", "* We assigned integer literals into different variables. Here, **`a`** is **binary** literal, **`b`** is a **decimal** literal,**`c`** is an **octal** literal and **`d`** is a **hexadecimal** literal.\n", "\n", "* When we print the variables, all the literals are converted into **decimal** values.\n", "\n", "* **`10.5`** and **`1.5e2`** are **floating point** literals. **`1.5e2`** is **expressed** with **exponential** and is **equivalent** to **`1.5 * 10^2`**.\n", "\n", "* We assigned a complex literal i.e **`3.14j`** in variable **`x`**. Then we use **imaginary** literal (x.imag) and **real** literal (x.real) to create imaginary and real part of **complex number**. \n", "\n", "To learn more about Numeric Literals, refer to **[Python Numbers](https://github.com/milaan9/02_Python_Datatypes/blob/main/001_Python_Numbers.ipynb)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Type Conversion of Numbers in Python\n", "\n", "As a programmer, you can convert a variable of any data type to Number data types in Python using the below Python inbuilt functions. Also, using these functions, you can convert a number from one Number data type to another i.e from int to float, float to decimal, decimal to int and so on.\n", "\n", "* **`int ()`** : This function converts any data type to integer data type.\n", "* **`float ()`** : This function converts any data type to float data type.\n", "* **`complex (real, imaginary)`** or **`complex (real)`** : This function converts any data type to complex data type.\n", "\n", "> **Note**: There is no 'long' integer in Python 3, int and long are unified now. This means int behave more like long. Sample program showing type conversion of Numbers in Python" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:41.980222Z", "start_time": "2021-10-02T07:56:41.968501Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "19\n", "3.7\n", "(3.7+0j)\n", "(19.16+0j)\n", "(3.7+19.16j)\n" ] } ], "source": [ "# Example:\n", "\n", "a = 3.7\n", "b = 19.16\n", "c = 3 + 27j\n", "\n", "#converting float to int\n", "print (int(b))\n", "\n", "#converting int to float\n", "print (float(a))\n", "\n", "#converting int to complex\n", "print (complex(a))\n", "\n", "#converting float to complex\n", "print (complex(b))\n", "\n", "#converting to complex\n", "print (complex(a, b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. String literals (unicode character strings)\n", "\n", "A **string** literal is a **sequence of characters** surrounded by **quotes**. We can use both **single**, **double** or **triple** quotes for a string. And, a **character literal** is a single character surrounded by single or double quotes." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:42.487053Z", "start_time": "2021-10-02T07:56:41.990964Z" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'Apple' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m<ipython-input-3-ee80ca1a52c8>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[0md\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m\"Apple\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 10\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 11\u001b[1;33m \u001b[0me\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mApple\u001b[0m \u001b[1;31m# cannot write string with out quotes ('', \" \", \"\"\" \"\"\", ''' ''')\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 12\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNameError\u001b[0m: name 'Apple' is not defined" ] } ], "source": [ "# Example:\n", "\n", "a = '''Apple'''\n", "\n", "b = \"\"\"Apple\"\"\"\n", "\n", "c = 'Apple'\n", "\n", "d = \"Apple\"\n", "\n", "e = Apple # cannot write string with out quotes ('', \" \", \"\"\" \"\"\", ''' ''')\n", "\n", "print(a)\n", "print(b)\n", "print(c)\n", "print(d)\n", "print(e)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:53.085188Z", "start_time": "2021-10-02T07:56:53.065659Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is Python\n", "C\n", "This is a multiline string with more than one line code.\n", "Ünicöde\n", "raw \\n string\n" ] } ], "source": [ "# Example:\n", "\n", "strings = \"This is Python\"\n", "char = \"C\"\n", "multiline_str = \"\"\"This is a multiline string with more than one line code.\"\"\"\n", "unicode = u\"\\u00dcnic\\u00f6de\"\n", "raw_str = r\"raw \\n string\"\n", "\n", "print(strings)\n", "print(char)\n", "print(multiline_str)\n", "print(unicode)\n", "print(raw_str)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above program, \n", "\n", "* **`This is Python`** is a string literal and **`C`** is a **character** literal. \n", "\n", "* The value with **triple-quote \"\"\"** assigned in the **`multiline_str`** is **multi-line** string literal.\n", "\n", "* The **`u\"\\u00dcnic\\u00f6de\"`** is a **unicode literal** which supports characters other than English. In this case, **`\\u00dc`** represents **`Ü`** and **`\\u00f6`** represents **`ö`**.\n", "\n", "* **`r\"raw \\n string\"`** is a raw string literal." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Boolean literals\n", "\n", "A Boolean literal can have any of the two values: **`True`** or **`False`**." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:53.639879Z", "start_time": "2021-10-02T07:56:53.626204Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x is True\n", "y is False\n", "a: 7\n", "b: 90\n" ] } ], "source": [ "# Example:\n", "\n", "#REMEMBER True == 1 False == 0\n", "\n", "x = (1 == True)\n", "y = (1 == False)\n", "a = True + 6\n", "b = False + 90\n", "\n", "print(\"x is\", x)\n", "print(\"y is\", y)\n", "print(\"a:\", a)\n", "print(\"b:\", b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above program, we use boolean literal **`True`** and **`False`**. In Python, **`True`** represents the value as **`1` and `False` as `0`**. The value of `x` is `True` because **`1` is equal to `True`**. And, the value of **`y`** is **`False`** because **`1` is not equal to `False`**.\n", "\n", "Similarly, we can use the **`True`** and **`False`** in numeric expressions as the value. The value of **`a`** is **`6`** because we add **`True`** which has value of **`1` with `6`**. Similarly, **`b`** is **`90`** because we add the **`False`** having value of **`0` with `90`**." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:54.023664Z", "start_time": "2021-10-02T07:56:54.009994Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Triple quotes (also with '''), allow strings to break over multiple lines.\n", "Alternatively \n", " is a newline character (\t for tab, \\ is a single backslash)\n" ] } ], "source": [ "# Example:\n", "\n", "9.0 # a simple floating point number\n", "1e100 # a googol as floating point number\n", "-1234567890 # an integer\n", "True or False # the two possible boolean values\n", "'This is a string'\n", "\"It's another string\"\n", "print(\"\"\"Triple quotes (also with '''), allow strings to break over multiple lines.\n", "Alternatively \\n is a newline character (\\t for tab, \\\\ is a single backslash)\"\"\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python also has complex numbers that can be written as follows. Note that the **`( )`** brackets or parentheses are required." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:54.425520Z", "start_time": "2021-10-02T07:56:54.416732Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1+2j)\n", "(1+2j)\n" ] } ], "source": [ "complex_number1 = complex(1,2)\n", "print(complex_number1)\n", "\n", "complex_number2 = (1.0+2j) # the same number as above\n", "print(complex_number2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Special literals\n", "\n", "Python contains one **special** literal i.e., **`None`**. We use it to specify to that field that is not created." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:54.823957Z", "start_time": "2021-10-02T07:56:54.812240Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available\n", "None\n" ] } ], "source": [ "# Example:\n", "\n", "juice = \"Available\"\n", "soup = None\n", "def menu(x):\n", " if x == juice:\n", " print(juice)\n", " else:\n", " print(soup)\n", "menu(juice)\n", "menu(soup)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above program, we define a **`menu` function**. Inside **`menu`**, when we set parameter as **`drink`** then, it displays **`Available`**. And, when the parameter is **`food`**, it displays **`None`**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Literal Collections\n", "\n", "There are four different literal collections **List literals, Tuple literals, Dict literals**, and **Set literals**." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:55.311263Z", "start_time": "2021-10-02T07:56:55.288834Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('Banana', 'Apple', 'Strawberry')\n", "['Banana', 'Apple', 'Strawberry']\n", "{'Apple', 'Strawberry', 'Banana'}\n", "{'1': 'Banana', '2': 'Apple', '3': 'Strawberry'}\n" ] } ], "source": [ "# Example:\n", "\n", "fruits1 = (\"Banana\", \"Apple\", \"Strawberry\") # tuple ()\n", "fruits2 = [\"Banana\", \"Apple\", \"Strawberry\"] # list []\n", "fruits3 = {\"Banana\", \"Apple\", \"Strawberry\"} # set {}\n", "fruits4 = {\"1\":\"Banana\", \"2\":\"Apple\", \"3\":\"Strawberry\"} # dictionary {\"Key\":\"Value\"}\n", "\n", "print(fruits1)\n", "print(fruits2)\n", "print(fruits3)\n", "print(fruits4)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2021-10-02T07:56:55.723859Z", "start_time": "2021-10-02T07:56:55.715559Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'mango', 'orange']\n", "(1, 2, 3)\n", "{'a': 'apple', 'b': 'ball', 'c': 'cat'}\n", "{'u', 'e', 'o', 'a', 'i'}\n" ] } ], "source": [ "# Example:\n", "\n", "fruits = [\"apple\", \"mango\", \"orange\"] #list\n", "numbers = (1, 2, 3) #tuple\n", "alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary\n", "vowels = {'a', 'e', 'i' , 'o', 'u'} #set\n", "\n", "print(fruits)\n", "print(numbers)\n", "print(alphabets)\n", "print(vowels)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above program, we created a list of **`fruits`, tuple** of **`numbers`, `dictionary` dict** having values with **keys desginated** to each value and **set** of **`vowels`**.\n", "\n", ">**Note**: To learn more about literal collections, refer to **[Python Data Types](https://github.com/milaan9/01_Python_Introduction/blob/main/009_Python_Data_Types.ipynb)**." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.9" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }