{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Introduction to Python Programming\n",
"\n",
" \n",
"\n",
"### Sachin Joshi\n",
"### Research Computing"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Basics of Python Programming\n",
"\n",
"\n",
"- Brief Introduction\n",
"- Variables\n",
"- Data Types\n",
" - Strings\n",
" - Lists\n",
" - Dictionaries\n",
" - Tuples\n",
"- Operators and Operands\n",
" - Arithmetic \n",
" - Comparison\n",
" - Logical\n",
"- Conditonal Execution\n",
"- Looping Statements\n",
" - for\n",
" - while\n",
"- Control Statements\n",
" - break\n",
" - continue\n",
" - pass\n",
"- Functions\n",
"- File Handling\n",
"- Numpy Arrays"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Python - The new generation Language\n",
"\n",
" - A general-purpose programming language (1980) by Guido van Rossum\n",
" - Emphasis on code readability, shorter codes, ease of writing\n",
" - Dynamically typed - No need to declare anything\n",
" - Automatic memory management\n",
" - Interpreted - There are no separate compilation and execution steps like C and C++.\n",
" - Free (developed under an OSI-approved open-source license) and portable"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Python - Fastest Growing Programming Language\n",
"\n",
" \n",
"\n",
"- Presence of third-party modules\n",
"- Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) and frameworks\n",
"- Open source and supportive community development\n",
"- Easy to learn and User-friendly data structures\n",
"- Widely used in Big Data and Machine Learning\n",
"- Web Development(Full stack framworks - Django, Pyramid, TurboGears, etc)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Why Python Best-Suited for Machine Learning?\n",
"\n",
" \n",
"\n",
"- According to Forbes, Machine learning patents grew at a 34% rate between 2013 and 2017 \n",
"- And Python is the primary programming language used for much of the research and development in Machine Learning\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"\n",
"\n",
"\n",
"- Python has multiple Libraries and Frameworks\n",
" * **Keras** is an open-source library that is particularly focused on experimentation with deep neural networks.\n",
" * **TensorFlow** is a free software library that is used for many machine learning applications like neural networks.\n",
" * **Scikit-learn** is a free software library for Machine Learning that various classification, regression and clustering algorithms."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Python vs Other language\n",
"\n",
"| Python | Java |\n",
"|:------:|:--------------:|\n",
"| Interpreted Language | Compiled Language |\n",
"| Slower, type of data is determined at runtime | Faster, less time to execute the code |\n",
"| Concise | Verbose |\n",
"| Uses Identation for structuring code | Uses braces for code structuring |\n",
"| Best for AI, ML IoT | Embedded and cross-platform applications |\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Installing Python\n",
"\n",
"\n",
" - Many PCs and Macs will have python already installed.\n",
" - To check if you have python installed:\n",
" - Open Command Line (cmd.exe) on Windows\n",
" - Open Terminal on Linux or Mac\n",
" - and run the following command\n",
" - python --version
\n",
" \n",
"- If you find that you do not have python installed on your computer, then you can download it for free from the following website: https://www.python.org/ "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Anaconda Python Distribution\n",
"\n",
" - [Anaconda Python distribution](https://www.anaconda.com/distribution/) is the most popular platform for Python\n",
" - It provides \n",
" - a convenient install procedure for over 1400 Data Science libraries for Python and R\n",
" - conda to manage your packages, dependencies, and environments\n",
" - anaconda navigator: a desktop portal to install and launch applications and editors including Jupyter, RStudio, Visual Studio Code, and Spyder\n",
" \n",
" - Visit https://go.lehigh.edu/linux to use Anaconda (and other Linux software) installed and maintained by the Research Computing group on your local Linux laptop or workstation\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Variables and Types\n",
"\n",
"- A **variable** is a name that refers to a value.\n",
"- An **assignment statement** creates new variables and gives them values"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"message = 'And now for something completely different'\n",
"n = 17\n",
"pi = 3.1415926535897931"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- The first assigns a string to a new variable named message\n",
"- the second gives the integer 17 to n\n",
"- the third assigns the (approximate) value of $\\pi$ to pi\n",
"\n",
"- To display the value of a variable, you can use a ***print*** function"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Printing to screen\n",
"\n",
"- Python has a built-in function, ***print*** to write output to standard output or screen"
]
},
{
"cell_type": "code",
"execution_count": 127,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World!\n",
"And now for something completely different\n"
]
}
],
"source": [
"print(\"Hello World!\")\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- The type of a variable is the type of the value it refers to."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(message)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"int"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(n)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"float"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(pi)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Reading from screen\n",
"\n",
"- Python has a built-in function, ***input*** to read input from standard input or screen"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What is your name: Sachin Joshi\n"
]
},
{
"data": {
"text/plain": [
"'Sachin Joshi'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"input('What is your name: ')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## Variable names\n",
"\n",
"- Variable names can be arbitrarily long. They can contain both letters and numbers, **but they have to begin with a letter**.\n",
"- The underscore character (\\_) can appear in a name. \n",
" * It is often used in names with multiple words, such as *my_name*\n",
"- If you give a variable an illegal name, you get a syntax error"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (, line 1)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m 76trombones = 'big parade'\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"76trombones = 'big parade'"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (, line 1)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m class = 'Advanced Theoretical Zymurgy'\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"class = 'Advanced Theoretical Zymurgy'"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## Reserved Words\n",
"\n",
"- Python has 31 keywords or reserved words that cannot be used for variable names."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"and | \n",
"del | \n",
"for | \n",
"is | \n",
"raise | \n",
"
\n",
"\n",
"as | \n",
"elif | \n",
"from | \n",
"lambda | \n",
"return | \n",
"
\n",
"\n",
"assert | \n",
"else | \n",
"global | \n",
"not | \n",
"try | \n",
"
\n",
"\n",
"break | \n",
"except | \n",
"if | \n",
"or | \n",
"while | \n",
"
\n",
"\n",
"class | \n",
"exec | \n",
"import | \n",
"pass | \n",
"with | \n",
"
\n",
"\n",
"continue | \n",
"finally | \n",
"in | \n",
"print | \n",
"yield | \n",
"
\n",
"\n",
"def | \n",
"
\n",
"\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Use an editor that has syntax highlighting, wherein python functions have a different color \n",
" - See previous slides, variable names are in the normal color i.e. black while reserved keywords, for e.g. ***class***, are in green"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Python Data Types\n",
"\n",
"- Data types are the classification or categorization of data items. \n",
"- It represents the kind of value that tells what operations can be performed on a particular data. \n",
"- Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- Following are the standard or built-in data type of python:\n",
"\n",
" - **Numeric**\n",
" - **Sequence Type**\n",
" - **Boolean**\n",
" - **Set**\n",
" - **Dictionary**\n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Strings\n",
"\n",
"- In Python, Strings are arrays of bytes representing Unicode characters. \n",
"- A string is a collection of one or more characters put in a single quote, double-quote or triple quote. \n",
"- In python there is no character data type, a character is a string of length one. \n",
"- It is represented by ***str*** class."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String with the use of Single Quotes: \n",
"Welcome to the Geeks World\n"
]
}
],
"source": [
"# Creating a String with single Quotes \n",
"\n",
"String1 = 'Welcome to the Geeks World'\n",
"print(\"String with the use of Single Quotes: \") \n",
"print(String1) "
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String with the use of Double Quotes: \n",
"I'm a Geek\n",
"\n"
]
}
],
"source": [
"# Creating a String with double Quotes \n",
"\n",
"String1 = \"I'm a Geek\"\n",
"print(\"String with the use of Double Quotes: \") \n",
"print(String1) \n",
"print(type(String1)) "
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Creating a multiline String: \n",
"Geeks \n",
" For \n",
" Life\n"
]
}
],
"source": [
"# Creating String with triple Quotes \n",
"# allows multiple lines \n",
"\n",
"String1 = '''Geeks \n",
" For \n",
" Life'''\n",
"print(\"Creating a multiline String: \") \n",
"print(String1) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. \n",
" - If a string is to contain a single quote, delimit it with double quotes and vice versa"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This string contains a single quote (') character.\n",
"This string contains a double quote (\") character.\n"
]
}
],
"source": [
"print(\"This string contains a single quote (') character.\")\n",
"print('This string contains a double quote (\") character.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Alternatively, escape the quote character using a backslash"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Escape Sequencing in Python\n",
"\n",
"- While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. \n",
"- Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings.\n",
"- Escape sequences start with a backslash and can be interpreted differently. \n",
"- If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and same is done for Double Quotes.\n",
"\n",
"\n",
"\n",
"| Escape Sequence | Escaped Interpretation |\n",
"|-----------------|------------------------|\n",
"| \\' | Literal single quote (') character |\n",
"| \\\" | Literal double quote (\") character |\n",
"| \\newline | Newline is ignored |\n",
"| \\\\\\ | Literal backslash (\\) character |\n",
"| \\n | ASCII Linefeed (LF) character |\n",
"| \\r | ASCII Carriage Return (CR) character |\n",
"| \\t | ASCII Horizontal Tab (TAB) character |\n",
"| \\v | ASCII Vertical Tab (VT) character |\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This string contains a single quote (') character.\n",
"This string contains a double quote (\") character.\n"
]
}
],
"source": [
"print('This string contains a single quote (\\') character.')\n",
"print(\"This string contains a double quote (\\\") character.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### String Operations\n",
"\n",
"- Python strings are immutable i.e. elements of a String cannot be changed once it has been assigned. \n",
"- Only new strings can be reassigned to the same name.\n",
"- Every element of a string can be referenced by their index (first index is 0)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1495599709240 1495599709240\n"
]
}
],
"source": [
"str1=\"Hello\"\n",
"str2=\"Hello\"\n",
"print(id(str1),id(str2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- ***str1*** and ***str2*** both refer to the same memory location\n",
"- If you modify ***str1***, it creates a new object at a different memory location"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Welcome to LTS Seminars \n",
" 1495599788080 \n",
" 1495599709240\n"
]
}
],
"source": [
"str1+=\", Welcome to LTS Seminars\"\n",
"print(str1, \"\\n\", id(str1), \"\\n\", id(str2))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"First character of String is: \n",
"H\n"
]
}
],
"source": [
"# Printing First character \n",
"\n",
"print(\"\\nFirst character of String is: \") \n",
"print(str1[0]) "
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Last character of String is: \n",
"s\n"
]
}
],
"source": [
"# Printing Last character \n",
"\n",
"print(\"\\nLast character of String is: \") \n",
"print(str1[-1]) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- **+** operator is used to concatenate string and * operator is a repetition operator for string."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? \n"
]
}
],
"source": [
"s = \"So, you want to learn Python? \" * 4\n",
"print(s)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- You can take subset of string from original string by using **[ ]** operator, also known as slicing operator.\n",
"- s[start:end]
will return part of the string starting from index start
to index end - 1
"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"' you want to'"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[3:15]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- start
index and end
index are optional. \n",
"- default value of start
index is 0 \n",
"- default value of end
is the last index of the string"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'So,'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[:3]"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"' learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[15:]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s[:]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### String functions\n",
"\n",
"- ***ord()***: returns the ASCII code of the character.\n",
"- ***chr()***: function returns character represented by a ASCII number.\n",
"- ***len()***: returns length of the string\n",
"- ***max()***: returns character having highest ASCII value\n",
"- ***min()***: returns character having lowest ASCII value"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"120"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(s)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Lists\n",
"\n",
"- Lists are just like the arrays, declared in other languages. \n",
"- Lists need not be homogeneous always which makes it the most powerful tool in Python. \n",
"- A single list may contain DataTypes like Integers, Strings, as well as Objects. \n",
"- Lists are mutable, and hence, they can be altered even after their creation. \n",
"- List in Python are ordered and have a definite count. \n",
"- Indexing of a list is done with 0 being the first index. \n",
"- Allows duplicating of elements in the list.\n",
"- It is represented by ***list*** class.\n",
"- Lists in Python can be created by just placing the sequence inside the square brackets **[ ]**"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Intial blank List: \n",
"[]\n"
]
}
],
"source": [
"# Creating a List \n",
"List = [] \n",
"print(\"Intial blank List: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List containing multiple values: \n",
"[10, 20, 30, 40]\n",
"Fist Element 10\n",
"Third Element 30\n"
]
}
],
"source": [
"# Creating a List with the use of multiple values \n",
"List = [10, 20, 30, 40] \n",
"print(\"List containing multiple values: \")\n",
"print(List)\n",
"print(\"Fist Element\", List[0]) \n",
"print(\"Third Element\", List[2]) "
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Multi-Dimensional List: \n",
"['spam', 2.0, 5, [10, 20]]\n"
]
}
],
"source": [
"# Creating a Multi-Dimensional List \n",
"# (By Nesting a list inside a List) \n",
"List = ['spam', 2.0, 5, [10, 20]] \n",
"print(\"Multi-Dimensional List: \") \n",
"print(List) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### List Operations\n",
"\n",
"### Adding Elements to a List\n",
"\n",
"- Elements can be added to the List by using built-in **append()** function. \n",
"- Only one element at a time can be added to the list by using **append()** method. \n",
"- **insert()**: this method is used for addition of element at the desired position. \n",
"- **extend()**: this method is used to add multiple elements at the same time at the end of the list."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Initial List: \n",
"[5, 10, 15]\n"
]
}
],
"source": [
"List = [5, 10, 15] \n",
"print(\"Initial List: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after Addition of Three elements: \n",
"[5, 10, 15, 20, 25, 15]\n"
]
}
],
"source": [
"# Addition of Elements in the List \n",
"List.append(20) \n",
"List.append(25) \n",
"List.append(15) \n",
"print(\"List after Addition of Three elements: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after performing Insert Operation: \n",
"['Geeks', 5, 10, 15, 12, 20, 25, 15]\n"
]
}
],
"source": [
"# Addition of Element at specific Position (using Insert Method) \n",
"List.insert(3, 12) \n",
"List.insert(0, 'Geeks') \n",
"print(\"List after performing Insert Operation: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after performing Extend Operation: \n",
"['Geeks', 5, 10, 15, 12, 20, 25, 15, 8, 'Geeks', 'Always']\n"
]
}
],
"source": [
"# Addition of multiple elements to the List at the end (using Extend Method) \n",
"List.extend([8, 'Geeks', 'Always']) \n",
"print(\"List after performing Extend Operation: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[15, 12, 20, 25]"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# You can reference a section of the list using a slice operator\n",
"List[3:7]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Removing Elements from the List\n",
"\n",
"- Elements can be removed from the List by using built-in **remove()** function but an Error arises if element doesn’t exist in the set. \n",
"- **Pop()** function can also be used to remove and return an element from the set, but by default it removes only the last element of the set, to remove element from a specific position of the List, index of the element is passed as an argument to the **pop()** method."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Intial List: \n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n"
]
}
],
"source": [
"List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] \n",
"print(\"Intial List: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after Removal of two elements: \n",
"[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]\n"
]
}
],
"source": [
"# Removing elements from List using Remove() method \n",
"List.remove(5) \n",
"List.remove(6) \n",
"print(\"List after Removal of two elements: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after popping an element: \n",
"[1, 2, 3, 4, 7, 8, 9, 10, 11]\n"
]
}
],
"source": [
"x = List.pop() \n",
"print(\"List after popping an element: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12\n"
]
}
],
"source": [
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after popping a specific element: \n",
"[1, 2, 4, 7, 8, 9, 10, 11]\n"
]
}
],
"source": [
"# Removing element at a specific location from the Set using the pop() method \n",
"y = List.pop(2) \n",
"print(\"List after popping a specific element: \") \n",
"print(List) "
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"print(y)"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 4, 7, 8, 9, 10, 11]\n"
]
}
],
"source": [
"# Use del if you do not need the removed value\n",
"del List[1]\n",
"print(List)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List after deleting more than 1 element:\n",
"[1, 9, 10, 11]\n"
]
}
],
"source": [
"# To remove more than one element, you can use del with a slice index\n",
"del List[1:4]\n",
"print(\"List after deleting more than 1 element:\")\n",
"print(List)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Lists and Strings\n",
"\n",
"- A string is a sequence of characters and a list is a sequence of values\n",
"- list of characters is not the same as a string. \n",
"- To convert from a string to a list of characters, you can use ***list***"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['s', 'p', 'a', 'm']\n"
]
}
],
"source": [
"s = 'spam'\n",
"t = list(s)\n",
"print(t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- The ***list*** function breaks a string into individual letters. \n",
"- If you want to break a string into words, you can use the ***split*** method"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['pining', 'for', 'the', 'fjords']\n"
]
}
],
"source": [
"s = 'pining for the fjords'\n",
"t = s.split()\n",
"print(t)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"data": {
"text/plain": [
"['spam', 'spam', 'spam']"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# An optional argument called a delimiter specifies which characters to use as word boundaries\n",
"\n",
"s = 'spam-spam-spam'\n",
"delimiter = '-'\n",
"s.split(delimiter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- ***join*** is the inverse of ***split***. \n",
"- It takes a list of strings and concatenates the elements. \n",
"- ***join*** is a string method, so you have to invoke it on the delimiter and pass the list as a parameter"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'pining:for:the:fjords'"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t = ['pining', 'for', 'the', 'fjords']\n",
"delimiter = ':'\n",
"delimiter.join(t)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Dictionaries\n",
"\n",
"- Dictionary in Python is an unordered collection of data values, used to store data values like a map.\n",
"- Dictionary holds ***key:value*** pair. \n",
"- **Key-value** is provided in the dictionary to make it more optimized. \n",
"- Each **key-value** pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.\n",
"- Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.\n",
"- Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.\n",
"\n",
"\n",
"- Dictionary can also be created by the built-in function ***dict()***.\n",
"- In Python, a Dictionary can be created by placing a sequence of elements within curly **{ }** braces, separated by ‘comma’.\n"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Empty Dictionary: \n",
"{}\n"
]
}
],
"source": [
"# Creating an empty Dictionary \n",
"Dict = {} \n",
"print(\"Empty Dictionary: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary with the use of Integer Keys: \n",
"{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n"
]
}
],
"source": [
"# Creating a Dictionary with Integer Keys \n",
"Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} \n",
"print(\"Dictionary with the use of Integer Keys: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary with the use of dict(): \n",
"{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n"
]
}
],
"source": [
"# Creating a Dictionary with dict() method \n",
"Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) \n",
"print(\"Dictionary with the use of dict(): \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary with each item as a pair: \n",
"{1: 'Geeks', 2: 'For'}\n"
]
}
],
"source": [
"# Creating a Dictionary with each item as a Pair \n",
"Dict = dict([(1, 'Geeks'), (2, 'For')]) \n",
"print(\"Dictionary with each item as a pair: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary with the use of Mixed Keys: \n",
"{'Name': 'Geeks', 1: [1, 2, 3, 4]}\n"
]
}
],
"source": [
"# Creating a Dictionary with Mixed keys \n",
"Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} \n",
"print(\"Dictionary with the use of Mixed Keys: \") \n",
"print(Dict) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Dictionary Operations\n",
"\n",
"### Adding Elements to a Dictionary\n",
"\n",
"- One value at a time can be added to a Dictionary by defining value along with the key e.g. **Dict[Key] = ‘Value’**. \n",
"- Updating an existing value in a Dictionary can be done by using the built-in **update()** method.\n",
"- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary."
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Empty Dictionary: \n",
"{}\n"
]
}
],
"source": [
"# Creating an empty Dictionary \n",
"Dict = {} \n",
"print(\"Empty Dictionary: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary after adding 3 elements: \n",
"{0: 'Geeks', 2: 'For', 3: 1}\n"
]
}
],
"source": [
"# Adding elements one at a time \n",
"Dict[0] = 'Geeks'\n",
"Dict[2] = 'For'\n",
"Dict[3] = 1\n",
"print(\"Dictionary after adding 3 elements: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Updated key value: \n",
"{0: 'Geeks', 2: 'Welcome', 3: 1}\n"
]
}
],
"source": [
"# Updating existing Key's Value \n",
"Dict[2] = 'Welcome'\n",
"print(\"Updated key value: \") \n",
"print(Dict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Accessing Elements from a Dictionary\n",
"\n",
"- In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. \n",
"- There is also a method called **get()** that will also help in accessing the element from a dictionary."
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accessing a element using key:\n",
"For\n"
]
}
],
"source": [
"# Creating a Dictionary \n",
"Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} \n",
" \n",
"# accessing a element using key \n",
"print(\"Accessing a element using key:\") \n",
"print(Dict['name'])"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accessing a element using get:\n",
"Geeks\n"
]
}
],
"source": [
"# accessing a element using get() method \n",
"print(\"Accessing a element using get:\") \n",
"print(Dict.get(3)) "
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The len function returns the number of key-value pairs\n",
"len(Dict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Removing Elements from Dictionary\n",
"\n",
"- In Python Dictionary, deletion of keys can be done by using the ***del*** keyword. \n",
"- Using ***del*** keyword, specific values from a dictionary as well as whole dictionary can be deleted. \n",
"- Other functions like ***pop()*** and ***popitem()*** can also be used for deleting specific values and arbitrary values from a Dictionary. \n",
"- All the items from a dictionary can be deleted at once by using ***clear()*** method."
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Initial Dictionary: \n",
"{5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n"
]
}
],
"source": [
"# Initial Dictionary \n",
"Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', \n",
" 'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, \n",
" 'B' : {1 : 'Geeks', 2 : 'Life'}} \n",
"print(\"Initial Dictionary: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Deleting a specific key: \n",
"{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n"
]
}
],
"source": [
"# Deleting a Key value \n",
"del Dict[6] \n",
"print(\"Deleting a specific key: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Popping specific element: \n",
"{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n"
]
}
],
"source": [
"# Deleting a Key using pop() \n",
"x = Dict.pop(5) \n",
"print(\"Popping specific element: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Welcome\n"
]
}
],
"source": [
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pops an arbitrary key-value pair: \n",
"{7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}}\n"
]
}
],
"source": [
"# Deleting an arbitrary Key-value pair using popitem() \n",
"y = Dict.popitem() \n",
"print(\"Pops an arbitrary key-value pair: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('B', {1: 'Geeks', 2: 'Life'})\n"
]
}
],
"source": [
"print(y)"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Deleting Entire Dictionary: \n",
"{}\n"
]
}
],
"source": [
"# Deleting entire Dictionary \n",
"Dict.clear() \n",
"print(\"Deleting Entire Dictionary: \") \n",
"print(Dict) "
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Looping through the Keys:\n",
"one\n",
"two\n",
"three\n",
"\n",
"\n",
"Looping through the Values:\n",
"uno\n",
"dos\n",
"tres\n"
]
}
],
"source": [
"# You can loop through keys or values by using the keys and values functions\n",
"\n",
"eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}\n",
"\n",
"print(\"Looping through the Keys:\")\n",
"for keys in eng2sp.keys():\n",
" print(keys)\n",
"\n",
"print(\"\\n\") \n",
"print(\"Looping through the Values:\")\n",
"for vals in eng2sp.values():\n",
" print(vals)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Tuple\n",
"\n",
"- Tuple is an ordered collection of Python objects much like a list. \n",
"- The sequence of values stored in a tuple can be of any type, and they are indexed by integers. \n",
"- The important difference between a list and a tuple is that tuples are immutable. \n",
"- Also, Tuples are hashable whereas lists are not. \n",
"- It is represented by ***tuple*** class.\n",
"\n",
"\n",
"- In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence.\n",
"- Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple."
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Initial empty Tuple: \n",
"()\n"
]
}
],
"source": [
"# Creating an empty tuple \n",
"Tuple1 = () \n",
"print(\"Initial empty Tuple: \") \n",
"print (Tuple1) "
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tuple with the use of String: \n",
"('Geeks', 'For')\n"
]
}
],
"source": [
"# Creating a Tuple with the use of Strings \n",
"Tuple1 = ('Geeks', 'For') \n",
"print(\"Tuple with the use of String: \") \n",
"print(Tuple1)"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tuple using List: \n",
"(1, 2, 4, 5, 6)\n"
]
}
],
"source": [
"# Creating a Tuple with the use of list \n",
"list1 = [1, 2, 4, 5, 6] \n",
"print(\"Tuple using List: \") \n",
"print(tuple(list1)) "
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tuple with the use of function: \n",
"('G', 'e', 'e', 'k', 's')\n"
]
}
],
"source": [
"# Creating a Tuple with the use of built-in function \n",
"Tuple1 = tuple('Geeks') \n",
"print(\"Tuple with the use of function: \") \n",
"print(Tuple1) "
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tuple with nested tuples: \n",
"((0, 1, 2, 3), ('python', 'geek'))\n"
]
}
],
"source": [
"# Creating a Tuple with nested tuples \n",
"Tuple1 = (0, 1, 2, 3) \n",
"Tuple2 = ('python', 'geek') \n",
"Tuple3 = (Tuple1, Tuple2) \n",
"print(\"Tuple with nested tuples: \") \n",
"print(Tuple3) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Accessing Elements of a Tuple\n",
"\n",
"- In order to access the tuple items refer to the index number. \n",
"- Use the index operator **[ ]** to access an item in a tuple. \n",
"- The index must be an integer. \n",
"- Nested tuple are accessed using nested indexing."
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Frist element of tuple\n",
"1\n"
]
}
],
"source": [
"tuple1 = tuple([1, 2, 3, 4, 5]) \n",
" \n",
"# Accessing element using indexing \n",
"print(\"Frist element of tuple\") \n",
"print(tuple1[0]) "
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Last element of tuple\n",
"5\n",
"Third last element of tuple\n",
"3\n"
]
}
],
"source": [
"# Accessing element from last (negative indexing) \n",
"print(\"Last element of tuple\") \n",
"print(tuple1[-1]) \n",
" \n",
"print(\"Third last element of tuple\") \n",
"print(tuple1[-3]) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Deleting/Updating Elements of Tuple\n",
"\n",
"- In python, deletion or Updation of a tuple is not allowed. \n",
"- This will cause an error because updating or deleting from a tuple is not supported. \n",
"- This is because tuples are immutable, hence elements of a tuple cannot be changed once it has been assigned. \n",
"- Only new tuples can be reassigned to the same name."
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Initial tuple\n",
"(1, 2, 3, 4, 5)\n"
]
}
],
"source": [
"tuple1 = tuple([1, 2, 3, 4, 5]) \n",
"print(\"Initial tuple\") \n",
"print(tuple1)"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'tuple' object does not support item assignment",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Updating an element of a tuple\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mtuple1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtuple1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
]
}
],
"source": [
"# Updating an element of a tuple \n",
"tuple1[0] = -1\n",
"print(tuple1)"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"ename": "TypeError",
"evalue": "'tuple' object doesn't support item deletion",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Deleting an element from a tuple\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;32mdel\u001b[0m \u001b[0mtuple1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtuple1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: 'tuple' object doesn't support item deletion"
]
}
],
"source": [
"# Deleting an element from a tuple \n",
"del tuple1[2] \n",
"print(tuple1) "
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('A', 1, 2, 3, 4, 5)\n"
]
}
],
"source": [
"# You can’t modify the elements of a tuple, but you can replace one tuple with another\n",
"\n",
"tuple1 = ('A',) + tuple1[0:]\n",
"print(tuple1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Operators and Operands\n",
"\n",
"- Operators are special symbols that represent computations like addition and multiplication. \n",
"- The values the operator is applied to are called operands."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Arithmetic Operators\n",
"\n",
"| Operator | Meaning | Example |\n",
"|----------|---------|---------|\n",
"| + (unary) | Unary Positive | \t+a |\n",
"| + (binary) | Addition | a + b | \n",
"| - (unary) | Unary Negation | \t-a |\n",
"| - (binary) | Subtraction | a - b |\n",
"| * | Multiplication | a * b |\n",
"| / | Division | a / b |\n",
"| %\t| Modulus | a % b |\n",
"| //| Floor Division (also called Integer Divison | a // b |\n",
"| ** | Exponentiation | a ** b |"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12\n",
"1.3333333333333333\n",
"4\n",
"2\n",
"64\n"
]
}
],
"source": [
"a = 4\n",
"b = 3\n",
"\n",
"print(a * b)\n",
"print(a / b)\n",
"print(3 * a // b)\n",
"print(2 * a % b)\n",
"print(a ** b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Comparison Operators\n",
"\n",
"- Can be used for both numbers and strings\n",
"- Python compares string lexicographically i.e using ASCII value of the characters\n",
"\n",
"| Operator | Meaning | Example |\n",
"|----------|---------|---------|\n",
"| == | Equal to | a == b |\n",
"| != | Not equal to | a != b |\n",
"| < | Less than | a < b |\n",
"| <= |Less than or equal to | a <= b |\n",
"| >\t | Greater than | a > b |\n",
"| >= | Greater than or equal to | a >= b |"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"a = 10\n",
"b = 20\n",
"print(a == b)"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n",
"True\n",
"72 104 105\n"
]
}
],
"source": [
"c = 'Hi'\n",
"d = 'hi'\n",
"print(c == d)\n",
"print( c < d)\n",
"print(ord('H'),ord('h'),ord('i'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Consider two strings 'Hi' and 'HI' for comparison. \n",
"- The first two characters ( H and H ) are compared. \n",
"- Since 'i' has a greater ASCII value (105) than 'I' with ASCII value (73), 'Hi' is greater than 'HI'"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 80,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'HI' < 'Hi'"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Logical Operators\n",
"\n",
"| Operator | Example | Meaning |\n",
"|----------|---------|---------|\n",
"| not | not x | True if x is False
False if x is True
(Logically reverses the sense of x) |\n",
"| or | x or y | True if either x or y is True
False otherwise |\n",
"| and | x and y | True if both x and y are True
False otherwise |"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"True\n"
]
}
],
"source": [
"x = 5\n",
"y = 10\n",
"\n",
"print(x > 6 or y < 15)\n",
"print(x < 10 and y > 5)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Conditional Execution\n",
"\n",
"- **Conditional Statements** gives the programmer an ability to check conditions and change the behavior of the program accordingly.\n",
"- The simplest form is the ***if statement***:\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"**Syntax**:\n",
"\n",
"if condition:\n",
" statements\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- There may be a situation where you want to execute a series of statements if the *condition*\n",
" is false\n",
"- Python provides an if ... else ...
conditional\n",
"- Syntax\n",
"\n",
"if condition:\n",
" statments_1\n",
"else:\n",
" statements_2\n",
"
"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is odd\n"
]
}
],
"source": [
"x = 13\n",
"\n",
"if x % 2 == 0:\n",
" print('x is even')\n",
"else:\n",
" print('x is odd')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- Sometimes there are more than two possibilities and we need more than two branches.\n",
"- Python provides a if ... elif ... else
conditional\n",
"- Syntax\n",
"\n",
"if condition1:\n",
" statements_1\n",
"elif condition2:\n",
" statements_2\n",
"else\n",
" statements_3\n",
"
"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is greater than y\n"
]
}
],
"source": [
"y = 10\n",
"if x < y:\n",
" print('x is less than y')\n",
"elif x > y:\n",
" print('x is greater than y')\n",
"else:\n",
" print('x and y are equal')"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is greater than y\n"
]
}
],
"source": [
"if x == y:\n",
" print('x and y are equal')\n",
"else:\n",
" if x < y:\n",
" print('x is less than y')\n",
" else:\n",
" print('x is greater than y')"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is not a positive single-digit number.\n"
]
}
],
"source": [
"# Nested If\n",
"\n",
"if 0 < x:\n",
" if x < 10:\n",
" print('x is a positive single-digit number.')\n",
" else:\n",
" print('x is not a positive single-digit number.')\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Loopoing Statements\n",
"\n",
"- There may be a situation when you need to execute a block of code a number of times.\n",
"\n",
"- A loop statement allows us to execute a statement or group of statements multiple times.\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## for loops\n",
"\n",
"- The ***for*** statement has the ability to iterate over the items of any sequence, such as a list or a string \n",
"- If a sequence contains an expression list, it is evaluated first. \n",
"- Then, the first item in the sequence is assigned to the iterating variable iterating_var. \n",
"- Next, the statements block is executed. \n",
"- Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.\n",
"\n",
"\n",
"for iterating_var in sequence:\n",
" statements(s)\n",
"
"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current fruit : banana\n",
"Current fruit : apple\n",
"Current fruit : mango\n"
]
}
],
"source": [
"fruits = ['banana', 'apple', 'mango']\n",
"for fruit in fruits: \n",
" print ('Current fruit :', fruit)"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current Letter : H\n",
"Current Letter : o\n",
"Current Letter : l\n",
"Current Letter : a\n"
]
}
],
"source": [
"for letter in 'Hola': \n",
" print('Current Letter :', letter)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"#### range function\n",
"\n",
"- The built-in function ***range()*** iterates over a sequence of numbers."
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"range(0, 5)"
]
},
"execution_count": 88,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"range(5)"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4]"
]
},
"execution_count": 89,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(range(5))"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"for var in list(range(5)):\n",
" print(var)"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current fruit : banana\n",
"Current fruit : apple\n",
"Current fruit : mango\n"
]
}
],
"source": [
"for index in range(len(fruits)):\n",
" print ('Current fruit :', fruits[index])"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## while loop\n",
"\n",
"- A ***while*** loop statement repeatedly executes a target statement as long as a given condition is true.\n",
"- Here, **statement(s)** may be a single statement or a block of statements with uniform indent. \n",
"- The **condition** may be any expression, and true is any non-zero value. The loop iterates while the condition is true.\n",
"- When the condition becomes false, program control passes to the line immediately following the loop.\n",
"\n",
"\n",
"while expression:\n",
" statement(s)\n",
"
"
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter any integer: 6\n",
"Factorial of 6 is 720\n"
]
}
],
"source": [
"number = int(input('Enter any integer: '))\n",
"\n",
"fact = count = 1\n",
"while (count <= number ):\n",
" fact = count * fact\n",
" count += 1\n",
"print('Factorial of %d is %d' % (number, fact))"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 is less than 5\n",
"1 is less than 5\n",
"2 is less than 5\n",
"3 is less than 5\n",
"4 is less than 5\n",
"5 is not less than 5\n"
]
}
],
"source": [
"count = 0\n",
"while count < 5:\n",
" print (count, \" is less than 5\")\n",
" count = count + 1\n",
"else:\n",
" print (count, \" is not less than 5\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Control Statements\n",
"\n",
"- Using loops in Python automates and repeats the tasks in an efficient manner. \n",
"- But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. \n",
"- These can be done by loop control statements. Loop control statements change execution from its normal sequence. \n",
"\n",
"\n",
"- Python supports the following control statements.\n",
"\n",
" - **Break statement**\n",
" - **Continue statement**\n",
" - **Pass statement**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Break Statement\n",
"\n",
"- The break statement is used to terminate the loop or statement in which it is present. \n",
"- After that, the control will pass to the statements that are present after the break statement, if available. \n",
"- If the break statement is present in the nested loop, then it terminates only those loops which contains break statement."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Flow Chart - Break\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"g\n",
"e\n",
"Out of for loop\n"
]
}
],
"source": [
"s = 'geeksforgeeks'\n",
"# Using for loop \n",
"for letter in s: \n",
" print(letter) \n",
" # break the loop as soon it sees 'e' or 's' \n",
" if letter == 'e' or letter == 's': \n",
" break\n",
" \n",
"print(\"Out of for loop\") "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Continue Statement\n",
"\n",
"- ***continue*** statement is opposite to that of ***break*** statement, instead of terminating the loop, it forces to execute the next iteration of the loop.\n",
"- As the name suggests the continue statement forces the loop to continue or execute the next iteration. \n",
"- When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Flow Chart - Continue\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"7\n",
"8\n",
"9\n",
"10\n"
]
}
],
"source": [
"for i in range(1, 11): \n",
" \n",
" # If i is equals to 6, continue to next iteration without printing \n",
" if i == 6: \n",
" continue\n",
" else: \n",
" # otherwise print the value of i \n",
" print(i) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Pass Statement\n",
"\n",
"- As the name suggests pass statement simply does nothing. \n",
"- The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. \n",
"- It is like ***null*** operation, as nothing will happen is it is executed. \n",
"- ***Pass*** statement can also be used for writing empty loops. \n",
"- ***Pass*** is also used for empty control statement, function and classes."
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Last Letter : s\n"
]
}
],
"source": [
"for letter in 'geeksforgeeks': \n",
" pass\n",
"print ('Last Letter :', letter) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Functions in Python\n",
"\n",
"- Function is a set of statements that take inputs, do some specific computation and produces output. \n",
"- The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.\n",
"\n",
"\n",
"- Python provides built-in functions like print(), etc. but we can also create your own functions."
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n"
]
}
],
"source": [
"x = 10\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Built-in Type Conversion Functions\n",
"\n",
"| Function\t| Description |\n",
"|-----------|-------------|\n",
"| ascii()\t| Returns a string containing a printable representation of an object |\n",
"| bin()\t| Converts an integer to a binary string |\n",
"| bool()\t| Converts an argument to a Boolean value |\n",
"| callable() | Returns whether the object is callable (i.e., some kind of function)\n",
"| chr()\t| Returns string representation of character given by integer argument |\n",
"| complex()\t| Returns a complex number constructed from arguments |\n",
"| float()\t| Returns a floating-point object constructed from a number or string |\n",
"| hex()\t| Converts an integer to a hexadecimal string |\n",
"| int()\t| Returns an integer object constructed from a number or string |\n",
"| oct()\t| Converts an integer to an octal string |\n",
"| ord()\t| Returns integer representation of a character |\n",
"| repr()\t| Returns a string containing a printable representation of an object |\n",
"| str()\t| Returns a string version of an object |\n",
"| type()\t| Returns the type of an object or creates a new type object |"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Math\n",
"\n",
"- Python has a math module that provides most of the familiar mathematical functions\n",
"\n",
"| Function | Description |\n",
"|----------|-------------|\n",
"| abs()\t| Returns absolute value of a number |\n",
"| divmod()\t| Returns quotient and remainder of integer division |\n",
"| max()\t| Returns the largest of the given arguments or items in an iterable |\n",
"| min()\t| Returns the smallest of the given arguments or items in an iterable |\n",
"| pow()\t| Raises a number to a power |\n",
"| round()\t| Rounds a floating-point value |\n",
"| sum()\t| Sums the items of an iterable |\n",
"\n",
"- A **module** is a file that contains a collection of related functions\n",
"- Before we can use the module, we have to import it"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.7071067811865476"
]
},
"execution_count": 99,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import math\n",
"degrees = 45\n",
"radians = degrees / 360.0 * 2 * math.pi\n",
"math.sin(radians)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Iterables and Iterators\n",
"\n",
"| Function\t| Description |\n",
"|-----------|-------------|\n",
"| all() | Returns True if all elements of an iterable are true |\n",
"| any() | Returns True if any elements of an iterable are true |\n",
"| enumerate() | Returns a list of tuples containing indices and values from an iterable |\n",
"| filter() | Filters elements from an iterable |\n",
"| iter() | Returns an iterator object |\n",
"| len() | Returns the length of an object |\n",
"| map() | Applies a function to every item of an iterable |\n",
"| next() | Retrieves the next item from an iterator |\n",
"| range() | Generates a range of integer values |\n",
"| reversed() | Returns a reverse iterator |\n",
"| slice() | Returns a slice object |\n",
"| sorted() | Returns a sorted list from an iterable |\n",
"| zip() | Creates an iterator that aggregates elements from iterables |"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## User Defined Functions\n",
"\n",
"- Python allows programmers to define their OWN **function**\n",
"- A **function definition** specifies the name of a new function and the sequence of statements that execute when the function is called.\n",
"\n",
"### Why create your own functions?\n",
"\n",
"- Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.\n",
"- Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.\n",
"- Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.\n",
"- Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it."
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"even\n",
"odd\n"
]
}
],
"source": [
"# A simple Python function to check whether x is even or odd \n",
"def evenOdd( x ): \n",
" if (x % 2 == 0): \n",
" print (\"even\")\n",
" else: \n",
" print (\"odd\")\n",
" \n",
"# Driver code \n",
"evenOdd(2) \n",
"evenOdd(3) "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## File Handling\n",
"\n",
"\n",
"- To read/write a file, you have to open it with an appropriate mode as the second parameter\n",
"\n",
"\n",
"open(filename, mode) \n",
"
\n",
"\n",
"| mode | description |\n",
"|------|-------------|\n",
"| r | Opens a file for reading only, default mode |\n",
"| w | Opens a file for writing only |\n",
"| a | Opens a file for appending only. File pointer is at end of file |\n",
"| rb | Opens a file for reading only in binary |\n",
"| wb | Opens a file for writing only in binary|"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<_io.TextIOWrapper name='output.txt' mode='w' encoding='cp1252'>\n"
]
}
],
"source": [
"fout = open('output.txt', 'w')\n",
"print(fout)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- If the file already exists, opening it in write mode clears out the old data.\n",
"- If the file doesn’t exist, a new one is created.\n",
"- The ***write*** method puts data into the file."
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"24"
]
},
"execution_count": 104,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"line1 = \"This here's the wattle,\\n\"\n",
"fout.write(line1)"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"24"
]
},
"execution_count": 105,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"line2 = \"the emblem of our land.\\n\"\n",
"fout.write(line2)"
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {},
"outputs": [],
"source": [
"# When you are done writing, you have to close the file.\n",
"\n",
"fout.close()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Reading data from the file\n",
"\n",
"- To read data back from the file you need one of these three methods\n",
"\n",
"| Method | Description |\n",
"|--------|-------------|\n",
"| read([number]) | Return specified number of characters from the file.
if omitted it will read the entire contents of the file.|\n",
"| readline() | Return the next line of the file.|\n",
"| readlines() | Read all the lines as a list of strings in the file|"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"This here's the wattle,\\nthe emblem of our land.\\n\""
]
},
"execution_count": 110,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Reading all the data at once\n",
"\n",
"f = open('output.txt', 'r')\n",
"f.read() "
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {},
"outputs": [],
"source": [
"f.close()"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[\"This here's the wattle,\\n\", 'the emblem of our land.\\n']"
]
},
"execution_count": 112,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Reading all lines as an array\n",
"\n",
"f = open('output.txt', 'r')\n",
"f.readlines() "
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {},
"outputs": [],
"source": [
"f.close()"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"This here's the wattle,\\n\""
]
},
"execution_count": 114,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Reading only 1 line\n",
"\n",
"f = open('output.txt', 'r')\n",
"f.readline()"
]
},
{
"cell_type": "code",
"execution_count": 115,
"metadata": {},
"outputs": [],
"source": [
"f.close()"
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This here's the wattle,\n",
"\n",
"the emblem of our land.\n",
"\n"
]
}
],
"source": [
"# Iterating through the file using file pointer\n",
"\n",
"f = open('output.txt', 'r')\n",
"for line in f:\n",
" print(line)\n",
"f.close() "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## NumPy\n",
"\n",
"- NumPy is the fundamental package for scientific computing with Python. \n",
"- It contains among other things\n",
" - a powerful N-dimensional array object\n",
" - sophisticated (broadcasting) functions\n",
" - tools for integrating C/C++ and Fortran code\n",
" - useful linear algebra, Fourier transform, and random number capabilities\n",
"- NumPy can also be used as an efficient multi-dimensional container of generic data. \n",
"- Numpy arrays are a great alternative to Python Lists"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- NumPy’s main object is the homogeneous multidimensional array.\n",
"- NumPy’s array class is called *ndarray*. It is also known by the alias *array*\n",
"- The more important attributes of an *ndarray* object are:\n",
" - ***ndarray.ndim***: the number of axes (dimensions) of the array.\n",
" - ***ndarray.shape***: the dimensions of the array.\n",
" - ***ndarray.size***: the total number of elements of the array.\n",
" - ***ndarray.dtype***: an object describing the type of the elements in the array.\n",
" - ***ndarray.itemsize***: the size in bytes of each element of the array.\n",
" - ***ndarray.data***: the buffer containing the actual elements of the array."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Numpy Arrays\n",
"\n",
"- create an array from a regular Python ***list*** or ***tuple*** using the ***array*** function"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2 3 4] int32\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"a = np.array([2,3,4])\n",
"print(a, a.dtype)"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1.2 3.5 5.1]\n",
" [4.1 6.1 0.5]] float64\n",
"(2, 3)\n"
]
}
],
"source": [
"# array transforms sequences of sequences into two-dimensional arrays, \n",
"# sequences of sequences of sequences into three-dimensional arrays\n",
"\n",
"b = np.array([(1.2, 3.5, 5.1),(4.1,6.1,0.5)])\n",
"print(b, b.dtype)\n",
"print(b.shape)"
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1.+0.j, 2.+0.j],\n",
" [3.+0.j, 4.+0.j]])"
]
},
"execution_count": 120,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The type of the array can also be explicitly specified at creation time\n",
"\n",
"c = np.array( [ [1,2], [3,4] ], dtype=complex )\n",
"c"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"- The function ***zeros*** creates an array full of zeros, \n",
"- the function ***ones*** creates an array full of ones, and \n",
"- the function ***empty*** creates an array whose initial content is random and depends on the state of the memory."
]
},
{
"cell_type": "code",
"execution_count": 121,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Zeros: [[0. 0. 0. 0.]\n",
" [0. 0. 0. 0.]\n",
" [0. 0. 0. 0.]]\n",
"Ones [[1. 1. 1. 1.]\n",
" [1. 1. 1. 1.]]\n",
"Empty [[1.2 3.5 5.1]\n",
" [4.1 6.1 0.5]]\n"
]
}
],
"source": [
"print('Zeros: ',np.zeros( (3,4) ))\n",
"print('Ones', np.ones( (2,4), dtype=np.float64 ))\n",
"print('Empty', np.empty( (2,3) ))"
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"data": {
"text/plain": [
"array([10, 15, 20, 25])"
]
},
"execution_count": 122,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# NumPy provides a function analogous to range that returns arrays instead of lists.\n",
"\n",
"np.arange( 10, 30, 5 )"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0, 1, 2, 3, 4],\n",
" [ 5, 6, 7, 8, 9],\n",
" [10, 11, 12, 13, 14]])"
]
},
"execution_count": 123,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The reshape function can be used to convert an array into a matrix\n",
"\n",
"a = np.arange(15).reshape(3, 5)\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"array dimensions: (3, 5)\n",
"number of dimensions: 2\n",
"element types: int32\n",
"size of elements: 4\n",
"total number of elements: 15\n",
"type of object: \n"
]
}
],
"source": [
"print(\"array dimensions: \", a.shape)\n",
"print(\"number of dimensions: \", a.ndim)\n",
"print(\"element types: \", a.dtype.name)\n",
"print(\"size of elements: \", a.itemsize)\n",
"print(\"total number of elements: \",a.size)\n",
"print(\"type of object:\",type(a))"
]
},
{
"cell_type": "code",
"execution_count": 125,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [20 30 40 50]\n",
"b: [0 1 2 3]\n",
"a-b: [20 29 38 47]\n",
"B**2 [0 1 4 9]\n",
"10*sin(a): [ 9.12945251 -9.88031624 7.4511316 -2.62374854]\n",
"Which elements of a < 35: [ True True False False]\n",
"Elements of a < 35: [20 30]\n"
]
}
],
"source": [
"# Arithmetic operators on arrays apply elementwise\n",
"\n",
"a = np.array( [20,30,40,50] )\n",
"b = np.arange( 4 )\n",
"print('a: ', a)\n",
"print('b:', b)\n",
"print('a-b:', a-b)\n",
"print('B**2', b**2)\n",
"print('10*sin(a): ', 10*np.sin(a))\n",
"print('Which elements of a < 35:', a<35)\n",
"print('Elements of a < 35: ',a[a<35])"
]
},
{
"cell_type": "code",
"execution_count": 126,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A = [[1 1]\n",
" [0 1]]\n",
"B = [[2 0]\n",
" [3 4]]\n",
"A*B = [[2 0]\n",
" [0 4]]\n",
"A . B = [[5 4]\n",
" [3 4]]\n",
"Numpy A. B = [[5 4]\n",
" [3 4]]\n"
]
}
],
"source": [
"A = np.array( [[1,1], [0,1]] )\n",
"B = np.array( [[2,0], [3,4]] )\n",
"print('A = ', A)\n",
"print('B = ', B)\n",
"print('A*B = ', A*B)\n",
"print('A . B = ', A.dot(B))\n",
"print('Numpy A. B = ', np.dot(A, B))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Further Reading: Python Books\n",
"\n",
"- **Think Python 2e** - Allen B. Downey\n",
"- **Automate the Boring Stuff with Python** - Al Sweigart\n",
"- **Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython** - Wes McKinney \n",
"- **Think Stats** - Allen B. Downey\n",
"- **Think Bayes: Bayesian Statistics in Python** - Allen B. Downey\n",
"- **Python Data Science Handbook** - Jake VanderPlas"
]
}
],
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"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.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}