Skip to content

Instantly share code, notes, and snippets.

@duangsuse
Last active October 24, 2025 09:22
Show Gist options
  • Select an option

  • Save duangsuse/519411ab618ee57350ee2df93d33f58e to your computer and use it in GitHub Desktop.

Select an option

Save duangsuse/519411ab618ee57350ee2df93d33f58e to your computer and use it in GitHub Desktop.
Five .ipynb tutorial

Five .ipynb Language Tutorial

Thanks for contribution 🤗:

https://github.com/ShixiangWang/iLearning/blob/master/study/Python/learnPython/搞定Python基本操作.ipynb https://github.com/rajathkmp/Python-Lectures/blob/master/03.ipynb https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb https://github.com/jamwine/Python-Beginners-Guide/blob/master/Learn%20Python%20in%20Jupyter%20Notebook.ipynb https://github.com/cs231n/cs231n.github.io/blob/master/python-colab.ipynb

for i in {2..6}; do printf " [🦄](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/duangsuse/519411ab618ee57350ee2df93d33f58e/raw/$i.ipynb)"; done

open a link above, CtrlV, ShiftEnter to run code below.

# <3 Python is REALLY simple, differ from MOST popular languages eg. Java C PHP Ruby 
# 💯 CtrlL https://hellogithub.com/en/report/tiobe 

# No "$" or "-" for var_x/defX/ClassX Names, no ^[0-9] at start.
# indentation & case sensitive, use Tab / Shift+Tab / ?var for docs

["It's not from TOML.io !"]
name = "Alice"      # String
age = 30            # Integer, 10//3 is 3
usdt = 19.99        # Float (USE 1999 FOR BALANCE)
is_active = True    # use with if bool(x):
hex2 = 0xdeadbeef   # int, 0xHex format

prices = {"Apple": 1.99, "Banana": 0.99}
fruits = ["Apple", "Banana", "Cherry"]
top1_fruit = fruits[i:=0]  # try i in range(0, < 3), or row[0:3] slice (supports -1=len()-1)

Composing flow

Compose statement literal containing API callgraph(': block' s) & vartree(GC values), reuse app functions with def(vars):

subprocess.getoutput

n=3 3 3
Hello 5
typed 5
world 5
[('Hello', 5), ('typed', 5), ('world', 5)] [('Hello', 5), ('typed', 5), ('world', 5)]

list(kv)=['Hello', 'typed', 'world']
kv={}
kv['Hello'] = 5
kv['typed'] = 5
kv['world'] = 5
two十(3)=5 666
two十(3)=5 669
More
# for(n=0, i=0;i<3;i+=1) n+=i
n = 0
for i in (rn := range(0, 3)):
  n += i

print(f"{n=}", sum(i + 0 for i in range(0, 3)), sum(rn))

words = "Hello typed  world  ".split(" ")
stdo = []
for w in words:
  if w != "":
    print(w, len(w))
for w in words:
  stdo.append((w, len(w))) if w != "" else None

print(stdo, kv := [(u, len(u)) for u in words], end="\n" * 2)

"deleteMe" or kv.pop(-1)  # , retWhenNone
kv = dict(kv)  # vartype shadowing
print(f"{list(kv)=}")  # = [*kv]
"duck🦆" or kv.pop("typed")

print("kv={}")  # 👎 C-style boilerplates
for col in kv.items():
  k, v = map(repr, col)  # json-compat literal_eval?
  if "explicit":
    k, v = (repr(u) for u in col)
  print(f"kv[{k}] = {v}")


def make_十(n):
  return lambda x: x + n


two十 = make_十(2)
print(f"{two十(3)=}", two十(664))

from argparse import Namespace


def cell_十(n=0):  # constructor(var n)
  def javaSAM(step):
    nonlocal n  # 👍 Py: no let-var style declarations, no (this.n)
    n += step
    return n

  return Namespace(inc=javaSAM)


two十 = cell_十(2).inc
print(f"{two十(3)=}", two十(664))

x = int(input("Please enter an integer: "))
if x < 0:
  x = 0
  print("Negative changed to zero")
elif x == 0:
  print("Zero")
elif x == 1:
  print("Single")
else:
  print("More")

# Let's extract the input(stdin.line),
# and make print a 'callback' by return(str) to sys callstack


def numKind(num):
  match num:
    case 0: it = "Zero"
    case 1: it = "Single"
    case x if x < 0:
      it = f"Negative ({x})"
    case _: it = "Normal"
  return it
  # it = match num: or "match num as it" are unsupported.


def tryInt(s: "123"):
  try:
    return int(s)
  except:
    return None


while "REPL":
  n = tryInt(input("integer: ").strip())
  if not n and n != 0:
    break
  # ^ Oops, NaN means 'invalid input', (0) ALSO DOES? so could nan be Falsey? .: bool(math.nan)
  print(numKind(n))

For spreadsheet guys

import io, pandas as pd
import matplotlib.pyplot as plt

STORE = """csv
Apple,Banana,Cherry
1,2,3
1.99,0.99,2
"""

# module_KV, class, def/arg:Type, (lambda nonlocalVars, codetree..) are ALL DICT AND 'k=v's in Python3.
for k in globals():
  if not all(c.isupper() for c in k):
    continue  # if /^[A-Z]+$/: replaceIt()  # tool regex101.com
  ext, mem = eval(f"{k}").split("\n", 1)  # v with(globalThis) of module.py
  exec(f"{k} = pd.read_{ext}(io.StringIO(mem))")


def main():
  df = STORE
  aapl_sales = df[df["Apple"] > 1]
  all = df.sum()
  # df.to_excel("out_store.xlsx", index=False)
  display(*vars().keys())
  display(*vars().values())

  df["Sale"] = df["Apple"] + df["Banana"]
  df["Sale"].plot(kind="line")
  plt.title("Units Sold Over Time")
  plt.show()


main()

For API designer, metaprogramming

#def With(u, f):  call eg.  With(Box(1), lambda x: x.As(x.v+1)), too long
def With(u):
  def PipeBy(f): f(u); return u
  return PipeBy

@With({})
def js(u):
  u['A'] = 1

print(js) # Yeah, @decorator are just fncall.  cout<< are operator<<(call), printf() are syscall(write,fd=0)
# They're FAKE SYNTAX, but idioms are not constant.

from dataclasses import dataclass, field
def data(T):
  'Trick: create vartree containers w/o def __init__ or call([],{})'
  {setattr(T, k, field(default_factory=v if isFn else v.copy)) for k,v in T.__annotations__.items() if (isFn:=callable(v))or hasattr(v,'copy')}
  return dataclass(T)

@data
class UserQueue:
  id: list
  usd: dict
  def onBuy(u, id):
    u.id.append(id)
    u.usd[id]=100
  def _repr_markdown_(u):
    get_ipython().__class__.__name__
    #^ https://ipython.readthedocs.io/en/stable/config/integrating.html
    return "".join(f"- [{me}]() **\\${u.usd[me]/100}**\n" for me in u.id)



@With(UserQueue())
def uq(u):
  [u.onBuy(id) for id in "Amy Jack Rose".split()]
  u.usd['Jack']=10_000
display(uq)

# got tired of `def try$Int` templates?
# cool @decorator to convert raise ValueError() to None
def tryFill(op, v0=None):
  def safe(*a, **kw):
    try: return op(*a, **kw)
    except: return (v0(a[0]) if callable(v0) else v0)
  return safe


@tryFill
def faulty(x):
  if x: raise x
  return x

if "": # edit, re-run!
    @tryFill
    def faulty(a):
      try:
        for x in a: raise x
      except TypeError: pass

tryFill(int)('abc'), tryFill(int, len)('abc')

HTTPd echo

4 major IO demo: EchoArgs, Counter, Checklist_DDL, SplitJoinWalk

first one (async Flask + cookie):

#sudo setcap 'cap_net_bind_service=+pie' /usr/bin/python3.*

from fastapi import FastAPI, Request
from fastapi.responses import Response
from uvicorn import run as bun
from pydantic import BaseModel, Field

I = FastAPI()

if "real world":

  @I.get("/login")
  async def setJsGlobal():
    # Create response with login message
    rpc = Response("Login successful. Session address set.")

    # Set session cookie with 1-day expiration
    rpc.set_cookie(
      key="USER",
      value="objectID",  # In production, use a hash(random+salt) token
      max_age=dur,
      expires=dur,
      path="/",  # Cookie available for HOST/*
      secure=False,  # Set to True in production with HTTPS
      httponly=True,  # Prevent XSS attacks
      samesite="lax",  # Prevent CSRF with modern browsers
    )
    return rpc

  class Blog(BaseModel):
    "try connect DB"

    id: int = Field(None, description="TBD, eg. UUID, auto-increment")
    slug: str = Field(min_length=4, max_length=15)
    html: str = Field(min_length=1, max_length=3000)  # no optional, age range


# @I.get("/{path:path}")
async def echo(path: str, u: Request):
  output = [
    f"curl $I/{path}",
    f"location.search: {u.query_params}",
    "Body: None (call PUT for write)\n\n",
    f"Client IP: {u.client.host}",
  ]
  auth(output, u)
  output.append("kwargs = {")
  for key, value in u.headers.items():  # try shorten!
    output.append(f"  {key} = {value}, ")
  output.append("}\n")

  return Response(content="\n".join(output), media_type="text/plain")


superFn = echo
@I.get("/{path}") # dont GET /
async def echo(
  path: str,
  q: str = "",
  p: int = 1,
  sort: str = "-1create_at",
  per_page: int = 100,
  u: Request = None,
):
  curs = (p - 1) * per_page
  res = await superFn(path, u)  # middleware are just "override fun" or pipes
  return Response(
    f"db.filter({q})[{curs}:{curs + per_page}].sort_({sort})\n".encode() + res.body
  )


@I.post("/{path}")
async def echo(path: str, u: Request):  # orderBy created, [0 1 2..]
  output = [
    "",
    f"location.search: {u.query_params}",
    f"Client IP: {u.client.host}",
  ]
  auth(output, u)  # try sort output!
  (output.append)("kwargs:")
  for key, value in u.headers.items():  # try shorten!
    output.append(f"  {key}: {value}")

  body = await u.body()
  output.append(f"\nBody ({len(body)} bytes/octects):")
  output.append(crud := body.decode("utf-8", errors="ignore"))
  output[0] = f"curl $I/{path} -d@'-' <<<{repr(crud)}"
  return Response(content="\n".join(output), media_type="text/plain")


if __name__ == "__main__":
  dur = 10 or 86400  # 24 hours in seconds
  foreign = {
    "objectID": f"Proxy.revocable(SQL_pointer,{dur}s)",
    None: "readonly, no-REST",
  }
  auth = lambda ln, u: ln.append(
    f"SK_ *(&api): {foreign.get(u.cookies.get('USER', None), 'expired')}"
  )
  bun(I, host="0.0.0.0", port=8080)
  if "fetch() fail":
    see = "https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware"
    see = "https://jsonplaceholder.typicode.com/"

if "f-string and let-match were not born" or "ES6 = uglify JS":
  from bottle import route, run, template

  @route('/hello/<name>')
  def index(name):
      return template('<b>Hello {{name}}</b>!', name=name)

  run(host='localhost', port=8080)
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Learn Python in Jupyter Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Different types of comments"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Comments are added using **#**. Adding comments to code helps in explaining what the code is intended to do."
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"#### Single-line comment"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"# This is a Jupyter notebook used for Python. It consists of cells."
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"#### Multi-line comment"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"# In order to execute the current cell, press Ctrl + Enter\n",
"# In order to execute the current cell and switch to the next new cell, press Shift + Enter"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"#### In-line comment"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"12"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"12 # Any random number"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"12 is returned as the output"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Arithmetic Operations"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"16"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Operation like a calculator\n",
"45 - 29"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">\n",
"<ul>\n",
"<li>Variables are used to store all different types of data.\n",
"<li>OVariable name should not start with digit.\n",
"<li> Here,<b><i>a,b,c,d,e,f,g</i></b> are the variables used to store arithmetic operations. \n",
"<li><b>print()</b> is used to display the output. \n",
"</ul></div>"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Addition 11+5 : 16\n",
"Subtraction 11-5 : 6\n",
"Multiplication 11*5 : 55\n",
"Division 11/5 : 2.2\n",
"Division (// returns quotient) 11//5 : 2\n",
"Division (% returns remainder) 11%5 : 1\n",
"Exponent 11**5 : 161051\n"
]
}
],
"source": [
"a = 11 + 5 # addition\n",
"print(\"Addition 11+5 :\", a)\n",
"\n",
"b = 11 - 5 # subtraction\n",
"print(\"Subtraction 11-5 :\", b)\n",
"\n",
"c = 11 * 5 # multiplication\n",
"print(\"Multiplication 11*5 :\", c)\n",
"\n",
"d = 11 / 5 # division\n",
"print(\"Division 11/5 :\", d)\n",
"\n",
"e = 11 // 5 # returns quotient as result\n",
"print(\"Division (// returns quotient) 11//5 :\", e)\n",
"\n",
"f = 11 % 5 # (modulus) returns remainder as result\n",
"print(\"Division (% returns remainder) 11%5 :\", f)\n",
"\n",
"g = 11**5 # exponents\n",
"print(\"Exponent 11**5 :\", g)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Remember, the arithmetic operations always follow the <b>PEDMAS</b> rule. Consider the two examples below:</div>"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Result of 5+2*7-8/2**2+1 is : 18.0\n"
]
}
],
"source": [
"print(\"Result of 5+2*7-8/2**2+1 is :\", 5 + 2 * 7 - 8 / 2**2 + 1)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Result of (5+2)*7-(8/2**2)+1 is : 48.0\n"
]
}
],
"source": [
"print(\"Result of (5+2)*7-(8/2**2)+1 is :\", (5 + 2) * 7 - (8 / 2**2) + 1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Boolean Operations"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11 is greater than 5: True\n",
"11 is less than 5: False\n",
"\n",
"11 is lesser than or equal to 5: False\n",
"11 is greater than or equal to 5: True\n",
"\n",
"11 is equal to 5: False\n",
"11 is not equal to 5: True\n"
]
}
],
"source": [
"# Boolean expressions\n",
"\n",
"print(\"11 is greater than 5:\", 11 > 5) # greater than\n",
"print(\"11 is less than 5:\", 11 < 5) # less than\n",
"\n",
"print(\"\\n11 is lesser than or equal to 5:\", 11 <= 5) # less than equal to\n",
"print(\"11 is greater than or equal to 5:\", 11 >= 5) # greater than equal to\n",
"\n",
"print(\"\\n11 is equal to 5:\", 11 == 5) # equal to\n",
"print(\"11 is not equal to 5:\", 11 != 5) # not equal to"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Boolean operators (<i>AND</i>, <i>OR</i>, <i>NOT</i>)</div>"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11>5 or 11<5: True\n",
"11>5 and 11<5: False\n",
"\n",
"False or True: True\n",
"False and True: False\n",
"\n",
"not(True): False\n",
"not(False): True\n"
]
}
],
"source": [
"# AND: Returns true only if both conditions are true\n",
"# OR: Returns true if either one of both the conditions is true\n",
"# NOT: reverses the result\n",
"\n",
"print(\"11>5 or 11<5: \", 11 > 5 or 11 < 5)\n",
"print(\"11>5 and 11<5: \", 11 > 5 and 11 < 5)\n",
"\n",
"print(\"\\nFalse or True: \", False or True)\n",
"print(\"False and True: \", False and True)\n",
"\n",
"print(\"\\nnot(True): \", not (True))\n",
"print(\"not(False): \", not (False))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Importing Libraries"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Use <b>import</b> and <b>from</b> for using external libraries<li><b>as</b> is used to define alias <li><b>help</b> is used for getting more information<li><b>dir</b> is used for viewing all methods</div>"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"m.sqrt(16): 4.0\n",
"m.pi: 3.141592653589793\n",
"m.e: 2.718281828459045 \n",
"\n",
"Help on built-in function sqrt in module math:\n",
"\n",
"sqrt(x, /)\n",
" Return the square root of x.\n",
"\n"
]
}
],
"source": [
"# math library is a library of mathematical functions and constants.\n",
"import math as m\n",
"\n",
"# square root\n",
"print(\"m.sqrt(16): \", m.sqrt(16)) \n",
"\n",
"# value of pi\n",
"print(\"m.pi: \", m.pi) \n",
"\n",
"# value of e\n",
"print(\"m.e: \", m.e, \"\\n\") \n",
"\n",
"# getting help for sqrt(math library)\n",
"help(m.sqrt)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tau: 6.283185307179586\n"
]
}
],
"source": [
"# Only importing specific attributes or methods\n",
"from math import tau\n",
"\n",
"# Value of Tau\n",
"print(\"tau: \", tau)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* [How Imports Work in Python](https://betterprogramming.pub/how-imports-work-in-python-59c2943d87dc)\n",
"* [PythonImportExample](https://github.com/Polaris000/BlogCode/tree/main/PythonImportExample)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### help()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Here is a list of the Python keywords. Enter any keyword to get more help.\n",
"\n",
"False break for not\n",
"None class from or\n",
"True continue global pass\n",
"__peg_parser__ def if raise\n",
"and del import return\n",
"as elif in try\n",
"assert else is while\n",
"async except lambda with\n",
"await finally nonlocal yield\n",
"\n"
]
}
],
"source": [
"# We should not use these reserved keywords as our variable names\n",
"help('keywords')"
]
},
{
"cell_type": "code",
"execution_count": 222,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
]
}
],
"source": [
"# keyword library contains all Python built-in keywords\n",
"\n",
"import keyword\n",
"print(keyword.kwlist)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### dir()"
]
},
{
"cell_type": "code",
"execution_count": 223,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"['__all__',\n",
" '__builtins__',\n",
" '__cached__',\n",
" '__doc__',\n",
" '__file__',\n",
" '__loader__',\n",
" '__name__',\n",
" '__package__',\n",
" '__spec__',\n",
" 'iskeyword',\n",
" 'issoftkeyword',\n",
" 'kwlist',\n",
" 'softkwlist']"
]
},
"execution_count": 223,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Getting list of all methods in the keyword library\n",
"dir(keyword)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* [Reserved Keywords in Python](https://www.programiz.com/python-programming/keyword-list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## type()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**type()** is used to determine the type of the object\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<img width=\"60%\" src=\"imgs/data_types.png\" alt=\"data_types.png\">"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"int"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 1\n",
"type(a)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"float"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = 2.5\n",
"type(b)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c = 'Hello'\n",
"type(c)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"bool"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = False\n",
"type(d)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"list"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"e = [1,2,3]\n",
"type(e)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"tuple"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f = (10,20,30)\n",
"type(f)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"set"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"g = {1,2,3}\n",
"type(g)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"dict"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"h = {1:10, 2:20, 3:30}\n",
"type(h)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Data types and structures"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<img width=\"60%\" src=\"imgs/data_structures.png\" alt=\"data_structures.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"A data structure allows us to organize and arrange our data to perform operations on them. Python has the following built-in data structures: **List**, **dictionary**, **tuple** and **set**. These are all considered **non-primitive** data structures. \n",
"\n",
"Data Structures can be **mutable** or **immutable**. Mutability refers to data inside the data structure that can be modified. For example, we can either change, update, or delete the data when needed. An immutable data structure will not allow modification once the data has been set. \n",
"\n",
"For example, a List is a mutable data structure whereas a tuple is an example of an immutable data structure."
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Strings"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Strings can be specified using both <i>single</i> or <i>double</i> quotes. <li>Strings are immutable.</div>"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"''"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# This is an empty string\n",
"s = ''\n",
"s"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x: orange\n",
"y: yellow\n",
"\n",
"x == y: False\n",
"x is y: False\n",
"x != y: True\n",
"x < y: True\n",
"x > y False\n"
]
}
],
"source": [
"x = \"orange\" # using double quotes\n",
"y = 'yellow' # using single quotes\n",
"\n",
"print(\"x:\", x)\n",
"print(\"y:\", y)\n",
"\n",
"# equal to\n",
"print(\"\\nx == y:\", x == y)\n",
"\n",
"# is statement is equivalent to ==\n",
"print(\"x is y:\", x is y)\n",
"\n",
"# not equal to\n",
"print(\"x != y:\", x != y)\n",
"\n",
"# less than, returns true as 'o' comes before 'y'\n",
"print(\"x < y:\", x < y)\n",
"\n",
"# greater than, returns false as 'o' comes before 'y'\n",
"print(\"x > y\", x > y)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1=='1': False\n"
]
}
],
"source": [
"# 1 is an integer while '1' is a string\n",
"print(\"1=='1':\", 1 == '1')"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s1: abcdef\n",
"s2: abcdef\n",
"s1 == s2: True\n",
"s1 is s2: True\n",
"\n",
"s3: abc-def\n",
"s4: abc-def\n",
"s3 == s4: True\n",
"s3 is s4: False\n"
]
}
],
"source": [
"# A String Peculiarity\n",
"\n",
"s1 = 'abcdef'\n",
"s2 = 'abcdef'\n",
"print('s1:', s1)\n",
"print('s2:', s2)\n",
"print(\"s1 == s2:\", s1 == s2) # returns True\n",
"print(\"s1 is s2:\", s1 is s2) # returns True\n",
"\n",
"s3 = 'abc-def'\n",
"s4 = 'abc-def'\n",
"print('\\ns3:', s3)\n",
"print('s4:', s4)\n",
"print(\"s3 == s4:\", s3 == s4) # returns True\n",
"\n",
"# returns False because of the introduction of special character\n",
"print(\"s3 is s4:\", s3 is s4)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>len()</b> is used to determine the length of specified variable, string, list, etc. <li>Spaces are also counted.</div>\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: This is a sample text.\n",
"\n",
"Length of the string 's' is: 22\n"
]
}
],
"source": [
"s = \"This is a sample text.\"\n",
"print(\"s:\", s)\n",
"\n",
"# special characters and white spaces are also counted\n",
"print(\"\\nLength of the string 's' is:\", len(s))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>in</b> operator is used to check whether a substring is present in the main string</div>"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: This is a sample string\n",
"\n",
"'sample' in a: True\n",
"'test' in a: False\n",
"'sample' not in a: False\n"
]
}
],
"source": [
"a = \"This is a sample string\"\n",
"print(\"a:\", a)\n",
"\n",
"print(\"\\n'sample' in a:\", 'sample' in a)\n",
"print(\"'test' in a:\", 'test' in a)\n",
"print(\"'sample' not in a:\", 'sample' not in a) # not in means not a substring"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Indexes in string</div>"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: Some text\n",
"len(s): 9\n",
"\n",
"First character, s[0]: S\n",
"\n",
"Character at index position 7, s[7]: x\n",
"\n",
"Last character, ,s[length-1]: t\n",
"\n",
"Last character using negative indexing, s[-1]: t\n",
"\n",
"Character at index position 4 from the end, s[-4]: t\n",
"\n",
"First character, s[-(length)]: S\n"
]
}
],
"source": [
"s = \"Some text\"\n",
"print(\"s:\", s)\n",
"length = len(s)\n",
"print(\"len(s):\", length)\n",
"\n",
"print(\"\\nFirst character, s[0]:\", s[0]) # first character\n",
"\n",
"# fetches the character at index position 7 in the string\n",
"print(\"\\nCharacter at index position 7, s[7]:\", s[7])\n",
"\n",
"# last character\n",
"print(\"\\nLast character, ,s[length-1]:\", s[length - 1])\n",
"\n",
"# Negative indexing is also possible, fetches last element\n",
"print(\"\\nLast character using negative indexing, s[-1]:\", s[-1])\n",
"\n",
"# fetches 4th element from the end (equivalent to index position 7 from the beginning)\n",
"print(\"\\nCharacter at index position 4 from the end, s[-4]:\", s[-4])\n",
"\n",
"# fetches first element (equivalent to s[0])\n",
"print(\"\\nFirst character, s[-(length)]:\", s[-(length)])"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: this is a sample string.\n",
"\n",
"s[1:12]: his is a sa\n",
"s[1:12:2]: hsi a\n",
"s[::-1]: .gnirts elpmas a si siht\n"
]
}
],
"source": [
"s = \"this is a sample string.\"\n",
"print(\"s:\", s)\n",
"\n",
"# extracts substring from index position 1 to index position 11\n",
"print(\"\\ns[1:12]:\", s[1:12])\n",
"\n",
"# extracts substring from index position 1 to index position 11 while skipping two places\n",
"print(\"s[1:12:2]:\", s[1:12:2])\n",
"\n",
"# reverses the string\n",
"print(\"s[::-1]:\", s[::-1])"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Escape sequences are specified using <b>backslash (\\\\)</b>.\n",
"<li><b>\\n</b> is used as a wildcard in order to print a new blank line.</div>"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Text 1\n",
"Text 2\n"
]
}
],
"source": [
"print(\"Text 1\\nText 2\") # two separate lines are printed"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Text 1\\nText 2\n"
]
}
],
"source": [
"# In order to print \\n as text, we insert a backslash as an escape sequence.\n",
"print(\"Text 1\\\\nText 2\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Text 1\\nText 2\n"
]
}
],
"source": [
"# Letter 'r' can also be placed before the string as an alternative to escape sequence (works similar to above)\n",
"print(r\"Text 1\\nText 2\")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Text 1\tText 2\n"
]
}
],
"source": [
"# \\t represents a tab\n",
"print(\"Text 1\\tText 2\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>Three quotes</b> (single or double) are used to define a <b>paragraph</b>, example:</div>"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is a test paragraph using double quotes.\n",
"This is another line.\n",
"\n",
"This is a second paragraph using single quotes.\n",
"Multiple lines can be used.\n",
"\n",
"This is a third paragraph. Multiple lines can be used. If we use \\ in the end of line, it continues to remain in the same line.\n",
"\n",
"Class of paragraph: <class 'str'>\n",
"Length of paragraph: 68\n"
]
}
],
"source": [
"paragraph = \"\"\"This is a test paragraph using double quotes.\n",
"This is another line.\\n\"\"\"\n",
"print(paragraph)\n",
"\n",
"second_paragraph = '''This is a second paragraph using single quotes.\n",
"Multiple lines can be used.\\n'''\n",
"print(second_paragraph)\n",
"\n",
"third_paragraph = '''This is a third paragraph. \\\n",
"Multiple lines can be used. \\\n",
"If we use \\ in the end of line, it continues to remain in the same line.\\n'''\n",
"print(third_paragraph)\n",
"\n",
"# paragraph is used mostly for documentation. It is of String datatype.\n",
"print(\"Class of paragraph:\", type(paragraph))\n",
"print(\"Length of paragraph:\", len(paragraph))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>Multiplication</b> of strings</div>"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hey! Hey! Hey! \n"
]
}
],
"source": [
"s1 = 'Hey! '\n",
"print(s1 * 3) # 3 copies of string s1"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Strings can be <b>concatenated</b> using the <b>+</b> sign.</div>"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"'This is a concatenated string.'"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\"This is a \" + 'concatenated string.'"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>Functions</b> on String</div>"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: this is a sample string.\n",
"\n",
"s.upper(): THIS IS A SAMPLE STRING.\n",
"s.lower(): this is a sample string.\n",
"s.capitalize(): This is a sample string.\n",
"s.title(): This Is A Sample String.\n"
]
}
],
"source": [
"s = \"this is a sample string.\"\n",
"print(\"s:\", s)\n",
"\n",
"# converts string into upper case\n",
"print(\"\\ns.upper():\", s.upper())\n",
"\n",
"# converts string into lower case\n",
"print(\"s.lower():\", s.lower())\n",
"\n",
"# capitalize the first letter\n",
"print(\"s.capitalize():\", s.capitalize())\n",
"\n",
"# returns the string with first capital letter of each word\n",
"print(\"s.title():\", s.title())"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: this is a sample string.\n",
"\n",
"s.replace(\" \",\"_\"): this_is_a_sample_string.\n",
"s.replace('sample','test'): this is a test string.\n",
"\n",
"s.count('s'): 4\n",
"\n",
"s.split(): ['this', 'is', 'a', 'sample', 'string.']\n",
"s.split('s'): ['thi', ' i', ' a ', 'ample ', 'tring.']\n"
]
}
],
"source": [
"s = \"this is a sample string.\"\n",
"print(\"s:\", s)\n",
"\n",
"# replaces blank space with underscore\n",
"print('\\ns.replace(\" \",\"_\"):', s.replace(\" \", \"_\"))\n",
"\n",
"# replaces sample with test\n",
"print(\"s.replace('sample','test'):\", s.replace('sample', 'test'))\n",
"\n",
"# returns the number of occurrences, without overlap\n",
"print(\"\\ns.count('s'):\", s.count('s'))\n",
"\n",
"# splits the string (on blank spaces), returns a list\n",
"print(\"\\ns.split():\", s.split())\n",
"\n",
"# splits the string (on character 's')\n",
"print(\"s.split('s'):\", s.split('s'))"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: this is a sample string.\n",
"\n",
"s.find('amp'): 11\n",
"s.index('amp'): 11\n",
"\n",
"s.startswith('this'): True\n",
"s.endswith('this'): False\n"
]
}
],
"source": [
"s = \"this is a sample string.\"\n",
"print(\"s:\", s)\n",
"\n",
"# returns the starting index position of the first occurence\n",
"print(\"\\ns.find('amp'):\", s.find('amp'))\n",
"\n",
"# returns the index of specified string\n",
"print(\"s.index('amp'):\", s.index('amp'))\n",
"\n",
"# checks the start of the string\n",
"print(\"\\ns.startswith('this'):\", s.startswith('this'))\n",
"\n",
"# checks the end of the string\n",
"print(\"s.endswith('this'):\", s.endswith('this'))"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: String with spaces \n",
"len(a): 28\n",
"\n",
"a.lstrip():String with spaces \n",
"len(a.lstrip()): 24\n",
"\n",
"a.rstrip(): String with spaces\n",
"len(a.rstrip()): 22\n",
"\n",
"a.strip():String with spaces\n",
"len(a.strip()): 18\n"
]
}
],
"source": [
"a = \" String with spaces \"\n",
"print(\"a:\" + a)\n",
"print(\"len(a):\", len(a))\n",
"\n",
"# lstrip removes the white spaces from the left side\n",
"print(\"\\na.lstrip():\" + a.lstrip())\n",
"print(\"len(a.lstrip()):\", len(a.lstrip()))\n",
"\n",
"# rstrip removes the white spaces from the right side\n",
"print(\"\\na.rstrip():\" + a.rstrip())\n",
"print(\"len(a.rstrip()):\", len(a.rstrip()))\n",
"\n",
"# strip() removes the white spaces from the left and right end\n",
"print(\"\\na.strip():\" + a.strip())\n",
"print(\"len(a.strip()):\", len(a.strip()))"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: 00543\n",
"s.lstrip('0'): 543\n"
]
}
],
"source": [
"s = \"00543\"\n",
"print(\"s:\", s)\n",
"print(\"s.lstrip('0'):\", s.lstrip('0'))"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: SamPlE TeXt\n",
"s.swapcase(): sAMpLe tExT\n"
]
}
],
"source": [
"s = 'SamPlE TeXt'\n",
"print('s:', s)\n",
"\n",
"# Swaps cases for all the letters of the string\n",
"print('s.swapcase():', s.swapcase())"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: 12345ABCdef\n",
"s.isalnum(): True\n"
]
}
],
"source": [
"s = '12345ABCdef'\n",
"print('s:', s)\n",
"\n",
"# Checks whether the string is alphanumeric\n",
"print('s.isalnum():', s.isalnum())"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: 56893\n",
"s.isnumeric(): True\n"
]
}
],
"source": [
"s = '56893'\n",
"print('s:', s)\n",
"\n",
"# Checks whether the string is numeric\n",
"print('s.isnumeric():', s.isnumeric())"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: Learning_Python\n",
"s.isalpha(): False\n"
]
}
],
"source": [
"s = 'Learning_Python'\n",
"print('s:', s)\n",
"\n",
"# Checks whether the string is alphabetic\n",
"print('s.isalpha():', s.isalpha())"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: Coding\n",
"s.isalpha(): True\n",
"s.islower(): False\n",
"s.isupper(): False\n",
"s.istitle(): True\n",
"s.isspace(): False\n"
]
}
],
"source": [
"s = 'Coding'\n",
"print('s:', s)\n",
"\n",
"# Checks whether the string is alphabetic\n",
"print('s.isalpha():', s.isalpha())\n",
"\n",
"# Checks whether the string has lowercase\n",
"print('s.islower():', s.islower())\n",
"\n",
"# Checks whether the string has uppercase\n",
"print('s.isupper():', s.isupper())\n",
"\n",
"# Checks whether the string has a title cased\n",
"print('s.istitle():', s.istitle())\n",
"\n",
"# Checks whether all characters in string are whitespace\n",
"print('s.isspace():', s.isspace())"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>String Partition</b>, different than <b>split()</b>\n",
"<li>The partition() method divides a string into three around a separator: <b>prefix, separator, suffix</b><li>Returns a tuple</div>"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: Test-String\n",
"s.partition('-'): ('Test', '-', 'String')\n",
"\n",
"s: Test-Long-String\n",
"s.partition('-'): ('Test', '-', 'Long-String')\n"
]
}
],
"source": [
"# includes the first occurrence of the separator sandwiched between the first half and the end half\n",
"s = 'Test-String'\n",
"print(\"s:\", s)\n",
"print(\"s.partition('-'):\", s.partition('-'))\n",
"\n",
"# except the first occurrence of separator, the other separators are excluded\n",
"s = 'Test-Long-String'\n",
"print(\"\\ns:\", s)\n",
"print(\"s.partition('-'):\", s.partition('-'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>String Substitution</b>\n",
"<li>Variables can be printed within a string using <b>format()</b> or <b>f-strings</b></div>"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I want two colors\n",
"\n",
"I want three colors\n",
"\n",
"I want four colors\n"
]
}
],
"source": [
"# {} are used for substituting text\n",
"s = \"I want {} colors\".format(\"two\")\n",
"print(s)\n",
"\n",
"# Variable is passed within {}\n",
"print(\"\\nI want {n} colors\".format(n=\"three\"))\n",
"\n",
"# Using f-strings, .format() can be also be replaced using f in the starting\n",
"n = 'four'\n",
"print(f\"\\nI want {n} colors\")"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My 2 favourite colors are blue and pink\n",
"\n",
"My 2 favourite colors are blue and pink\n",
"\n",
"My 2 favourite colors are blue and pink\n",
"\n",
"My 2 favourite colors are blue and pink\n"
]
}
],
"source": [
"color1 = 'blue'\n",
"color2 = 'pink'\n",
"number = 2\n",
"\n",
"# Using .format()\n",
"print('My {} favourite colors are {} and {}'.format(number, color1, color2))\n",
"\n",
"# Using .format(), passing arguments 0,1,2, and so on\n",
"print('\\nMy {0} favourite colors are {1} and {2}'.format(number, color1, color2))\n",
"\n",
"# Using .format(), passing variables instead of arguments\n",
"print('\\nMy {a} favourite colors are {b} and {c}'.format(a=number,\n",
" b=color1,\n",
" c=color2))\n",
"\n",
"# Best Implementation, using f-strings\n",
"print(f'\\nMy {number} favourite colors are {color1} and {color2}')"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My text has string: Hello!\n",
"My text has string containing % sign and Hello!\n",
"\n",
"My text has number: 42\n",
"My text has number with 0 decimal places: 42\n",
"My text has number with 4 decimal places: 42.4000\n"
]
}
],
"source": [
"# C-style substitution and formatting\n",
"print(\"My text has string: %s\" % (\"Hello!\"))\n",
"\n",
"# % sign acts as an escape sequence\n",
"print(\"My text has string containing %% sign and %s\" % (\"Hello!\"))\n",
"\n",
"print(\"\\nMy text has number: %d\" % (42.4))\n",
"print(\"My text has number with 0 decimal places: %.0f\" % (42.4))\n",
"print(\"My text has number with 4 decimal places: %.4f\" % (42.4))"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Values are: pi=3.1415926 and e=2.7182818\n",
"\n",
"Values are: pi=3.14 and e=2.718\n"
]
}
],
"source": [
"pi = 3.1415926\n",
"e = 2.7182818\n",
"print(f'Values are: pi={pi} and e={e}')\n",
"\n",
"values = [pi, e]\n",
"print(f'\\nValues are: pi={values[0]:.2f} and e={values[1]:.3f}')"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Lists"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>A List is created using square brackets []. <li>Lists are mutable</div>"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[]"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# This is an empty List\n",
"a = []\n",
"a"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
" <div class=\"alert alert-info\"><li>A list can have multiple elements of same or different data type.</div>"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [12, 'abc', 8.95, 'xyz', [2, 6]]\n",
"b: [4, 7, 2, 4]\n",
"\n",
"c: [12, 'abc', 8.95, 'xyz', [2, 6], 4, 7, 2, 4]\n",
"Length of c: 9\n",
"\n",
"'abc' in a: True\n",
"35 in b: False\n",
"12 not in a: False\n",
"\n",
"2*b: [4, 7, 2, 4, 4, 7, 2, 4]\n",
"\n",
"min(b): 2\n",
"max(b): 7\n",
"sum(b): 17\n"
]
}
],
"source": [
"a = [12, 'abc', 8.95, \"xyz\", [2, 6]]\n",
"print(\"a:\", a)\n",
"b = [4, 7, 2, 4]\n",
"print(\"b:\", b)\n",
"\n",
"# concatenation of two lists\n",
"c = a + b\n",
"print(\"\\nc:\", c)\n",
"print(\"Length of c:\", len(c))\n",
"\n",
"print(\"\\n'abc' in a:\", 'abc' in a)\n",
"print(\"35 in b:\", 35 in b)\n",
"print(\"12 not in a:\", 12 not in a)\n",
"\n",
"# Multiplication, two copies of list b\n",
"print(\"\\n2*b:\", 2 * b)\n",
"\n",
"# minimum in list (list must not have strings)\n",
"print(\"\\nmin(b):\", min(b))\n",
"\n",
"# maximum in list (list must not have strings)\n",
"print(\"max(b):\", max(b))\n",
"\n",
"# sum of list elements (list must not have strings)\n",
"print(\"sum(b):\", sum(b))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
" <div class=\"alert alert-info\">List functions:<li>append()<li>extend()<li>insert()<li>pop()</div>"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original List: [1, 2, 3, 4, 5]\n",
"List after append(): [1, 2, 3, 4, 5, 6]\n",
"List after extend(): [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"List after pop(): [1, 2, 3, 4, 5, 6, 7, 8]\n",
"List after insert(): [1, 2, 3, 4, 'Text', 5, 6, 7, 8]\n"
]
}
],
"source": [
"a = [1, 2, 3, 4, 5]\n",
"print(\"Original List: {}\".format(a))\n",
"\n",
"# Append method is used to add new elements in the pre-exisiting list.\n",
"a.append(6)\n",
"print(\"List after append(): {}\".format(a))\n",
"\n",
"# extend method is used to extend the list\n",
"a.extend([7, 8, 9])\n",
"print(\"List after extend(): {}\".format(a))\n",
"\n",
"# Pop method is used to remove the last element from the list.\n",
"a.pop()\n",
"print(\"List after pop(): {}\".format(a))\n",
"\n",
"# Insert into position\n",
"a.insert(4, 'Text')\n",
"print(\"List after insert(): {}\".format(a))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
" <div class=\"alert alert-info\">Accessing List elements</div>"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3, 4, 5]\n",
"Length of a (L): 5\n",
"\n",
"a[2]: 3\n",
"a[0]: 1\n",
"a[L-1]: 5\n",
"\n",
"List after setting new value: [1, 2, 6, 4, 5]\n",
"List after pop(2): [1, 2, 4, 5]\n",
"Final List after deleting an element: [2, 4, 5]\n"
]
}
],
"source": [
"# A specific element can be referred from a list. For instance:\n",
"a = [1, 2, 3, 4, 5]\n",
"print(\"a:\", a)\n",
"\n",
"# The length of the list. Indexing starts from zero.\n",
"L = (len(a))\n",
"print(\"Length of a (L): {}\".format(L))\n",
"\n",
"# Accessing Indexes\n",
"print(\"\\na[2]:\", a[2]) # Third element\n",
"print(\"a[0]:\", a[0]) # First element\n",
"print(\"a[L-1]:\", a[L - 1]) # Last element\n",
"\n",
"# Setting a value in list (mutable)\n",
"# For example, set a value of 6 at index position 2\n",
"a[2] = 6 # 3 is changed to 6\n",
"print(\"\\nList after setting new value: {}\".format(a))\n",
"\n",
"# A specific element can be removed from a list using its index position in the pop function.\n",
"# For example, remove element 6\n",
"a.pop(2) # a.pop(index)\n",
"print(\"List after pop(2): {}\".format(a))\n",
"\n",
"# An element can be deleted from a list using del function by specifying its index position\n",
"del (a[0])\n",
"print(\"Final List after deleting an element: {}\".format(a))"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: ['Ravi', 'Rahul', 'Rohan']\n",
"\n",
"a[2][2]: h\n",
"a[1][3]: u\n",
"a[0][2]: v\n"
]
}
],
"source": [
"a = [\"Ravi\", \"Rahul\", \"Rohan\"]\n",
"print(\"a:\", a)\n",
"\n",
"print(\"\\na[2][2]:\", a[2][2]) # Third element, Third character\n",
"print(\"a[1][3]:\", a[1][3]) # Second element, Fourth character\n",
"print(\"a[0][2]:\", a[0][2]) # First element, Third character"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"b: [12, 'abc', ['Text', 5.34, 23, True], 'xyz', [2, 6]]\n",
"\n",
"b[1]: abc\n",
"b[2]: ['Text', 5.34, 23, True]\n",
"b[2][1]: 5.34\n",
"b[2][0][3]: t\n"
]
}
],
"source": [
"# Nesting\n",
"b = [12, 'abc', [\"Text\", 5.34, 23, True], \"xyz\", [2, 6]]\n",
"print(\"b:\", b)\n",
"\n",
"print(\"\\nb[1]:\", b[1])\n",
"print(\"b[2]:\", b[2])\n",
"print(\"b[2][1]:\", b[2][1])\n",
"print(\"b[2][0][3]:\", b[2][0][3])"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 5, 8, 2, 5, 2]\n",
"\n",
"a[3:5]: [2, 5]\n",
"a[1:]: [5, 8, 2, 5, 2]\n",
"a[:3]: [1, 5, 8]\n"
]
}
],
"source": [
"a = [1, 5, 8, 2, 5, 2]\n",
"print(\"a:\", a)\n",
"\n",
"# fetches elements from index position 3 to index position 4\n",
"print(\"\\na[3:5]:\",\n",
" a[3:5]) \n",
"\n",
"# fetches elements from index position 1 till end\n",
"print(\"a[1:]:\", a[1:]) \n",
"\n",
"# fetches elements from starting till index position 2\n",
"print(\"a[:3]:\", a[:3]) "
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
" <div class=\"alert alert-info\">Other list functions:<li>count()<li>index()<li>remove()<li>reverse()<li>sort()</div>"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 5, 8, 2, 5, 2]\n",
"\n",
"a.count(5): 2\n",
"a.index(5): 1\n",
"\n",
"List after removing 5: [1, 8, 2, 5, 2]\n"
]
}
],
"source": [
"a = [1, 5, 8, 2, 5, 2]\n",
"print(\"a:\", a)\n",
"\n",
"# returns the number of occurences of element 5\n",
"print(\"\\na.count(5):\", a.count(5))\n",
"\n",
"# returns the first index position of element 5\n",
"print(\"a.index(5):\", a.index(5))\n",
"\n",
"# removes the first occurence of element 5\n",
"a.remove(5)\n",
"print(\"\\nList after removing 5: \", a)"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 5, 8, 2, 5, 2]\n",
"After a.reverse(), a: [2, 5, 2, 8, 5, 1]\n"
]
}
],
"source": [
"a = [1, 5, 8, 2, 5, 2]\n",
"print(\"a:\", a)\n",
"\n",
"a.reverse() # reverses the list\n",
"print(\"After a.reverse(), a:\", a)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 5, 8, 2, 5, 2]\n",
"\n",
"List after sorting in ascending order: [1, 2, 2, 5, 5, 8]\n",
"\n",
"List after sorting in descending order: [8, 5, 5, 2, 2, 1]\n"
]
}
],
"source": [
"a = [1, 5, 8, 2, 5, 2]\n",
"print(\"a:\", a)\n",
"\n",
"# sorts the list in ascending order\n",
"a.sort()\n",
"print(\"\\nList after sorting in ascending order: \", a)\n",
"\n",
"# sorts the list in descending order\n",
"a.sort(reverse=True)\n",
"print(\"\\nList after sorting in descending order: \", a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Using <b>key</b> argument in <b>sort()</b><li>accepts a function for producing a sort key from an item</div>"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"s: peter piper picked a peck of pickled pepper and a peck of pickled pepper peter piper picked\n",
"\n",
"After split, s:\n",
" ['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'pepper', 'and', 'a', 'peck', 'of', 'pickled', 'pepper', 'peter', 'piper', 'picked']\n",
"\n",
"After normal sorting, s:\n",
" ['a', 'a', 'and', 'of', 'of', 'peck', 'peck', 'pepper', 'pepper', 'peter', 'peter', 'picked', 'picked', 'pickled', 'pickled', 'piper', 'piper']\n",
"\n",
"List after sorting using key argument, s:\n",
" ['a', 'a', 'of', 'of', 'and', 'peck', 'peck', 'peter', 'peter', 'piper', 'piper', 'pepper', 'pepper', 'picked', 'picked', 'pickled', 'pickled']\n"
]
}
],
"source": [
"s = '''peter piper picked a peck of pickled pepper and a peck of pickled pepper peter piper picked'''\n",
"print('s:', s)\n",
"\n",
"s = s.split()\n",
"print('\\nAfter split, s:\\n', s)\n",
"\n",
"# Normal Sorting, lexicographic order is returned\n",
"s.sort()\n",
"print('\\nAfter normal sorting, s:\\n', s)\n",
"\n",
"# Sorting based on length, bigger words will be returned in end\n",
"s.sort(key=len)\n",
"print(\"\\nList after sorting using key argument, s:\\n\", s)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Tuples"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Tuples are exactly similar to Lists, but they are immutable. <li>Tuples are defined inside parenthesis ().<li>Functions like reverse(), remove() and sort() will not work since tuples are not mutable in nature.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"()"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Empty Tuple\n",
"()"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: (1, 5, 8, 2, 5, 2)\n",
"Length: 6\n",
"Sum: 23\n",
"\n",
"a.count(5): 2\n",
"a.index(8): 2\n"
]
}
],
"source": [
"a = (1, 5, 8, 2, 5, 2)\n",
"print(\"a:\", a)\n",
"print(\"Length: \", len(a))\n",
"\n",
"# sum of a tuple containing integers\n",
"print(\"Sum: \", sum(a))\n",
"\n",
"# returns the number of occurences of element 5\n",
"print(\"\\na.count(5): \", a.count(5))\n",
"\n",
"# returns the first index position of element 8\n",
"print(\"a.index(8): \", a.index(8))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>sorted()</b> returns a sorted list and can be called on any iterable series<li>The <b>type()</b> defines the class of the object.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: (1, 5, 8, 2, 5, 2)\n",
"Object Type: <class 'tuple'>\n",
"\n",
"sorted(a): [1, 2, 2, 5, 5, 8]\n",
"Object Type: <class 'list'>\n",
"\n",
"sorted(a, reverse=True): [8, 5, 5, 2, 2, 1]\n"
]
}
],
"source": [
"a = (1, 5, 8, 2, 5, 2)\n",
"print(\"a:\", a)\n",
"print('Object Type:',type(a))\n",
"\n",
"# sorted in ascending order, returns list\n",
"b = sorted(a)\n",
"print(\"\\nsorted(a): \", b)\n",
"print('Object Type:',type(b))\n",
"\n",
"# sorted in descending order\n",
"c = sorted(a, reverse=True)\n",
"print(\"\\nsorted(a, reverse=True): \", c)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Iterable Series: (1, 5, 8, 2, 5, 2)\n",
"\n",
"reversed(a): <reversed object at 0x0000024AECF839A0>\n",
"Object Type: <class 'reversed'>\n",
"\n",
"Reversed List: [2, 5, 2, 8, 5, 1]\n",
"Object Type: <class 'list'>\n"
]
}
],
"source": [
"a = (1, 5, 8, 2, 5, 2)\n",
"print('Iterable Series: {}'.format(a))\n",
"\n",
"# reverses any iterable series (here tuple), returns an object\n",
"d = reversed(a)\n",
"print(\"\\nreversed(a): \", d)\n",
"print('Object Type:', type(d))\n",
"\n",
"# object converted explicitly into list\n",
"d = list(d)\n",
"print('\\nReversed List: {}'.format(d))\n",
"print('Object Type:', type(d))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>Defining Tuple in different ways</b></div>"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(100,) is a tuple: <class 'tuple'>\n"
]
}
],
"source": [
"# only one element, using comma in the end\n",
"a = (100, )\n",
"print('{} is a tuple: {}'.format(a, type(a)))"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(1, 2, 3, 4, 5) is a tuple: <class 'tuple'>\n"
]
}
],
"source": [
"# multiple elements without parenthesis\n",
"b = 1, 2, 3, 4, 5\n",
"print('{} is a tuple: {}'.format(b, type(b)))"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {
"hidden": true,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 10 & b: 20\n",
"\n",
"After Swapping\n",
"a: 20 & b: 10\n"
]
}
],
"source": [
"a, b = 10, 20\n",
"print(f'a: {a} & b: {b}')\n",
"\n",
"# Swapping elements\n",
"a, b = b, a\n",
"print(f'\\nAfter Swapping\\na: {a} & b: {b}')"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: ('A', 'p', 'p', 'l', 'e')\n"
]
}
],
"source": [
"# Separating elements\n",
"a = tuple('Apple')\n",
"print('a: {}'.format(a))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>Tuple Unpacking</b>\n",
"<li>The partition() method divides a string into three around a separator: prefix, separator, suffix<li>Using tuple unpacking, the result can be destructured.<li>Underscore(_) can be used as a dummy name in place of the separator</div>"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: Jack-Martin\n",
"After removing -, name is: Jack Martin\n"
]
}
],
"source": [
"# tuple unpacks values into variables\n",
"a = 'Jack-Martin'\n",
"print(\"a:\", a)\n",
"first_name, separator, last_name = a.partition('-') # returns a tuple\n",
"print(f'After removing {separator}, name is: {first_name} {last_name}')"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: Jack|24\n",
"Name is: Jack\n",
"Age is: 24\n"
]
}
],
"source": [
"# Using _ to ignore invaluable variables\n",
"a = 'Jack|24'\n",
"print(\"a:\", a)\n",
"name, _, age = a.partition('|')\n",
"print('Name is: {}\\nAge is: {}'.format(name, age))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Dictionary"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">\n",
"<li>Dictionaries are defined using a Key-Value pair in curly brackets {}<li>A key-value can be an integer, string, etc.<li>Keys must be unique and immutable objects <b>(lists cannot be the keys)</b><li>If we try to access or modify keys that don't exist in the dictionary, it raise a KeyError and break up our code execution.</div>"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"{}"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"empty_dict = {}\n",
"empty_dict"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"d1: {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five'}\n",
"d2: {4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}\n",
"\n",
"After Updating Dictionary,\n",
"d1: {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}\n",
"\n",
"Updating Dictionary using the | operator: {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}\n",
"\n",
"Updating Dictionary using the ** operator: {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'}\n"
]
}
],
"source": [
"d1 = {0: \"Zero\", 1: \"One\", 2: \"Two\", 3: \"Three\", 4: \"Four\", 5: \"Five\"}\n",
"\n",
"# 0,1,2, etc are the keys. Zero, One, Two, etc are the values.\n",
"print(\"d1:\", d1)\n",
"\n",
"d2 = {4: \"four\", 5: \"five\", 6: \"six\", 7: \"seven\", 8: \"eight\"}\n",
"print(\"d2:\", d2)\n",
"\n",
"# d1 dictionary is updated with keys and values of dictionary d2, only unique values are stored\n",
"d1.update(d2)\n",
"print(\"\\nAfter Updating Dictionary,\\nd1:\", d1)\n",
"\n",
"# Some other ways to merge the dictionaries\n",
"print('\\nUpdating Dictionary using the | operator:',d1|d2)\n",
"print('\\nUpdating Dictionary using the ** operator:',{**d1,**d2})"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>A key in dictionary can hold multiple datatypes (Boolean, Integer, Float, String, Tuple) i.e. datatype should be immutable<li>A value in dictionary can hold multiple datatypes (List, Tuple, Boolean, Integer, Float, String) i.e. both immutable and mutable</div>\n"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dictionary a: {'Text': 'String', 18: 'Integer', True: 'Boolean', (1, 2, 3): 'Tuple', 3.5: 'Float_duplicate'}\n",
"\n",
"a[True]: Boolean\n",
"\n",
"Dictionary a: {'Text': 'String', 18: 'Integer', True: 'Boolean', (1, 2, 3): 'Tuple', 3.5: 'Float_duplicate', 'New Key': 'New Value'}\n"
]
}
],
"source": [
"a = {\n",
" \"Text\": \"String\",\n",
" 18: \"Integer\",\n",
" True: \"Boolean\",\n",
" (1, 2, 3): \"Tuple\",\n",
" 3.5: \"Float\",\n",
" 3.5: \"Float_duplicate\"\n",
"}\n",
"\n",
"# 3.5 is the duplicate key, the returned value will be the last defined value\n",
"print(\"Dictionary a:\", a)\n",
"\n",
"# Accessing the dictionary elements using keys\n",
"print(\"\\na[True]:\", a[True])\n",
"\n",
"# Adding new Key-Values pairs in dictionary\n",
"a[\"New Key\"] = \"New Value\"\n",
"\n",
"# Printing order of dictionary is not ordered\n",
"print(\"\\nDictionary a:\", a)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Dictionary b: {'Name': 'Jack', 'Age': 34, 'Amount': 76890.56, 'Access': False, 'Address': (22, 'ABC', 'XYZ'), 'Mobile': [12345, 95748, '45225']}\n",
"\n",
"b.keys(): dict_keys(['Name', 'Age', 'Amount', 'Access', 'Address', 'Mobile'])\n",
"\n",
"b.values(): dict_values(['Jack', 34, 76890.56, False, (22, 'ABC', 'XYZ'), [12345, 95748, '45225']])\n",
"\n",
"b.items(): dict_items([('Name', 'Jack'), ('Age', 34), ('Amount', 76890.56), ('Access', False), ('Address', (22, 'ABC', 'XYZ')), ('Mobile', [12345, 95748, '45225'])])\n"
]
}
],
"source": [
"b = {\n",
" \"Name\": \"Jack\",\n",
" \"Age\": 34,\n",
" \"Amount\": 76890.56,\n",
" \"Access\": False,\n",
" \"Address\": (22, 'ABC', 'XYZ'),\n",
" \"Mobile\": [12345, 95748, \"45225\"]\n",
"}\n",
"print(\"\\nDictionary b:\", b)\n",
"\n",
"# retrieving the list of keys\n",
"print(\"\\nb.keys():\", b.keys())\n",
"\n",
"# retrieving the list of values\n",
"print(\"\\nb.values():\", b.values())\n",
"\n",
"# returns the list of all items (tuples)\n",
"print(\"\\nb.items():\", b.items())"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x: (('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)) \n",
"Tuple converted into dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}\n"
]
}
],
"source": [
"# Converting a tuple into dictionary\n",
"x = (('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5))\n",
"y = dict(x)\n",
"print(\"x: \", x, \"\\nTuple converted into dictionary: \", y)"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'Access': False,\n",
" 'Address': (22, 'ABC', 'XYZ'),\n",
" 'Age': 34,\n",
" 'Amount': 76890.56,\n",
" 'Mobile': [12345, 95748, '45225'],\n",
" 'Name': 'Jack'}\n"
]
}
],
"source": [
"# Using pprint library (Pretty Printing) for viewing dictionary neatly\n",
"from pprint import pprint as pp\n",
"\n",
"a = {\n",
" \"Name\": \"Jack\",\n",
" \"Age\": 34,\n",
" \"Amount\": 76890.56,\n",
" \"Access\": False,\n",
" \"Address\": (22, 'ABC', 'XYZ'),\n",
" \"Mobile\": [12345, 95748, \"45225\"]\n",
"}\n",
"\n",
"# Keys are arranged in a sorted manner\n",
"pp(a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Sets"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Sets contains unique elements</div>"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"set()"
]
},
"execution_count": 69,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Empty Set\n",
"set()"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Set s1: {1, 2, 3, 4, 5}\n",
"Set s2: {1, 2, 3, 4, 5} , only unique elements are contained in the set\n",
"\n",
"After adding element in List s1: {1, 2, 3, 4, 5, 6}\n",
"After removing element in List s1: {1, 2, 3, 5}\n",
"\n",
"6 in s1: False\n",
"\n",
"s2 (Copy of set s1): {1, 2, 3, 5}\n",
"s2: set()\n"
]
}
],
"source": [
"s1 = {1, 2, 3, 4, 5}\n",
"print(\"Set s1: {}\".format(s1))\n",
"\n",
"# elements are repeated\n",
"s2 = {2, 5, 1, 5, 3, 2, 5, 3, 4, 1, 2, 4, 4, 5, 2, 1, 1, 3}\n",
"print(\"Set s2: {} , only unique elements are contained in the set\".format(s2))\n",
"\n",
"# Adding an element in set using add()\n",
"s1.add(6)\n",
"print(\"\\nAfter adding element in List s1: {}\".format(s1))\n",
"\n",
"# Removing an element in set using remove()\n",
"s1.remove(6)\n",
"\n",
"# always succeeds without raising KeyError\n",
"s1.discard(4) \n",
"print(\"After removing element in List s1: {}\".format(s1))\n",
"\n",
"# Check if element is present in the set\n",
"print(\"\\n6 in s1:\", 6 in s1)\n",
"\n",
"# Making a copy of set\n",
"s2 = s1.copy()\n",
"print(\"\\ns2 (Copy of set s1): \", s2)\n",
"\n",
"# Clearing contents of set s2\n",
"s2.clear()\n",
"print(\"s2: \", s2) # Empty Set"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Set a: {1, 2, 3, 4, 5} \n",
"Set coverted into list: [1, 2, 3, 4, 5]\n",
"\n",
"List a: [3, 4, 2, 4, 3, 2, 4, 1, 1, 1, 4, 5, 3, 4, 2, 2, 3] \n",
"List coverted into set: {1, 2, 3, 4, 5}\n"
]
}
],
"source": [
"# Converting a set into list using the list constructor\n",
"a = {3, 4, 2, 4, 3, 2, 4, 1, 1, 1, 4, 5, 3, 4, 2, 2, 3}\n",
"b = list(a)\n",
"print(\"Set a: \", a, \"\\nSet coverted into list: \", b)\n",
"\n",
"# Converting a list into set using the set constructor\n",
"a = [3, 4, 2, 4, 3, 2, 4, 1, 1, 1, 4, 5, 3, 4, 2, 2, 3]\n",
"b = set(a)\n",
"print(\"\\nList a: \", a, \"\\nList coverted into set: \", b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Set functions</div>"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: {1, 2, 3, 4}\n",
"b: {3, 4, 5, 6}\n",
"c: {5, 6}\n",
"\n",
"a.union(b): {1, 2, 3, 4, 5, 6}\n",
"a.intersection(b): {3, 4}\n",
"a & b: {3, 4}\n",
"a.symmetric_difference(b): {1, 2, 5, 6}\n",
"a^b: {1, 2, 5, 6}\n",
"a.difference(b): {1, 2}\n",
"a-b: {1, 2}\n",
"b.difference(a): {5, 6}\n",
"\n",
"set(a).issuperset(c): False\n",
"set(b).issuperset(c): True\n",
"set(c).issubset(a): False\n",
"set(c).issubset(b): True\n",
"set(c).isdisjoint(a): True\n"
]
}
],
"source": [
"a = {1, 2, 3, 4}\n",
"b = {3, 4, 5, 6}\n",
"c = {5, 6}\n",
"print(\"a:\", a)\n",
"print(\"b:\", b)\n",
"print(\"c:\", c)\n",
"\n",
"# A union B\n",
"print(\"\\na.union(b):\", a.union(b))\n",
"\n",
"# A intersection B\n",
"print(\"a.intersection(b):\", a.intersection(b))\n",
"\n",
"# A intersection B can also be represented as A & B\n",
"print(\"a & b:\", a & b)\n",
"\n",
"# ~(A intersection B), all other uncommon elements\n",
"print(\"a.symmetric_difference(b):\", a.symmetric_difference(b))\n",
"\n",
"# Symmetric difference using ^\n",
"print(\"a^b:\", a^b)\n",
"\n",
"# A prime\n",
"print(\"a.difference(b):\", a.difference(b))\n",
"\n",
"# A prime using -\n",
"print(\"a-b:\", a-b)\n",
"\n",
"# B prime\n",
"print(\"b.difference(a):\", b.difference(a))\n",
"\n",
"print(\"\\nset(a).issuperset(c):\", set(a).issuperset(c))\n",
"print(\"set(b).issuperset(c):\", set(b).issuperset(c))\n",
"print(\"set(c).issubset(a):\", set(c).issubset(a))\n",
"print(\"set(c).issubset(b):\", set(c).issubset(b))\n",
"print(\"set(c).isdisjoint(a):\", set(c).isdisjoint(a))"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"d: {50, 20, 70, 40, 10, 30}\n",
"e: {40, 10, 11, 45, 20, 22, 58, 60}\n",
"\n",
"After updating, d: {70, 40, 10, 11, 45, 50, 20, 22, 58, 60, 30}\n"
]
}
],
"source": [
"d = {10, 20, 30, 40, 20, 10, 20, 30, 50, 70}\n",
"e = {10, 22, 45, 40, 20, 10, 20, 11, 58, 60}\n",
"print(\"d:\", d)\n",
"print(\"e:\", e)\n",
"\n",
"# Update a set with the union of itself and others\n",
"d.update(e) \n",
"print(\"\\nAfter updating, d:\", d)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Frozensets"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Frozen sets are a native data type in Python that have the qualities of sets, but are immutable like tuples. The primary reason to use them is to write more clear, functional code. By defining a variable as a frozen set, we’re telling future readers: do not modify this!"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{1, 2, 3}\n"
]
}
],
"source": [
"scores = {1, 2}\n",
"scores.add(3)\n",
"print(scores)"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'frozenset' object has no attribute 'add'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_17888/672858836.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;31m# AttributeError: 'frozenset' object has no attribute 'add'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mfrozen_scores\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m: 'frozenset' object has no attribute 'add'"
]
}
],
"source": [
"scores = {1, 2}\n",
"frozen_scores = frozenset(scores)\n",
"\n",
"# AttributeError: 'frozenset' object has no attribute 'add'\n",
"frozen_scores.add(3)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"frozenset({1, 2, 3, 4})\n",
"frozenset({'H', 'e', 'l', 'o'})\n"
]
}
],
"source": [
"myList = [1, 1, 2, 3, 4]\n",
"frozenList = frozenset(myList)\n",
"print(frozenList) # frozenset({1, 2, 3, 4})\n",
"\n",
"myString = \"Hello\"\n",
"frozenString = frozenset(myString)\n",
"print(frozenString) # frozenset({'e', 'l', 'H', 'o'})"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## isinstance()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>isinstance()</b> checks the type of objects</div>"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"name = 'Jamwine'\n",
"isinstance(name, str)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"record_id = '12345'\n",
"isinstance(record_id, int)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Explicit Type conversion (Type Casting)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Objects created explicitly using constructors int(), str(), list(), float(), bool(), tuple()</div>"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"int(4): 4\n",
"int(4.5): 4\n",
"int('78'): 78\n",
"int(True): 1\n",
"\n",
"str('Hey'): Hey\n",
"str(53): 53\n",
"str(46.2): 46.2\n",
"str(True): True\n",
"\n",
"float(3.6): 3.6\n",
"float('21.64'): 21.64\n",
"float(435): 435.0\n",
"float(True): 1.0\n",
"\n",
"bool(1): True\n",
"bool(0): False\n",
"\n",
"list([3,6,'fan']): [3, 6, 'fan']\n",
"tuple([2,8,'test', False]): (2, 8, 'test', False)\n",
"tuple('String123'): ('S', 't', 'r', 'i', 'n', 'g', '1', '2', '3')\n",
"\n",
"Default Values\n",
"int(): 0\n",
"float(): 0.0\n",
"str(): \n",
"list(): []\n",
"bool(): False\n"
]
}
],
"source": [
"print(\"int(4): \", int(4))\n",
"print(\"int(4.5): \", int(4.5)) # type conversion from float to integer\n",
"print(\"int('78'): \", int('78')) # type conversion from string to integer\n",
"print(\"int(True): \", int(True)) # type conversion from boolean to integer\n",
"\n",
"print(\"\\nstr('Hey'): \", str('Hey'))\n",
"print(\"str(53): \", str(53)) # type conversion from integer to string\n",
"print(\"str(46.2): \", str(46.2)) # type conversion from float to string\n",
"print(\"str(True): \", str(True)) # type conversion from boolean to string\n",
"\n",
"print(\"\\nfloat(3.6): \", float(3.6))\n",
"print(\"float('21.64'): \",\n",
" float('21.64')) # type conversion from string to float\n",
"print(\"float(435): \", float(435)) # type conversion from integer to float\n",
"print(\"float(True): \", float(True)) # type conversion from boolean to float\n",
"\n",
"print(\"\\nbool(1): \", bool(1))\n",
"print(\"bool(0): \", bool(0))\n",
"\n",
"print(\"\\nlist([3,6,'fan']): \", list([3, 6, 'fan']))\n",
"print(\"tuple([2,8,'test', False]): \", tuple([2, 8, 'test', False]))\n",
"print(\"tuple('String123'): \", tuple('String123'))\n",
"\n",
"# Default Values\n",
"print(\"\\nDefault Values\\nint(): \", int()) # 0\n",
"print(\"float(): \", float()) #0.0\n",
"print(\"str(): \", str()) # '' (blank string)\n",
"print(\"list(): \", list()) # [] (blank list)\n",
"print(\"bool(): \", bool()) # False"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Advanced Numbers: Octal, Hexadecimal, Binary, Complex"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Decimal Value: 50\n"
]
}
],
"source": [
"# Normal Integer\n",
"i = 50\n",
"print(\"Decimal Value:\", i)"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Octal Value: 0o62 , type of o: <class 'str'>\n",
"\n",
"Octal to integer: 0o62 is 50\n"
]
}
],
"source": [
"# converting integer to octal value\n",
"o = oct(i)\n",
"print(\"Octal Value:\", o, \", type of o:\", type(o))\n",
"\n",
"# converting octal to integer value\n",
"print(\"\\nOctal to integer: 0o62 is {}\".format(0o62))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"number prefixed by **0o** (zero and a lowercase \"o\" or uppercase \"O\") represents an **octal number**"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hexadecimal Value: 0x32 , type of h: <class 'str'>\n",
"\n",
"Hexadecimal to integer: 0x32 is 50\n"
]
}
],
"source": [
"# converting integer to hex value\n",
"h = hex(i)\n",
"print(\"Hexadecimal Value:\", h, \", type of h:\", type(h))\n",
"\n",
"# converting hex to integer value\n",
"print(\"\\nHexadecimal to integer: 0x32 is {}\".format(0x32))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"number prefixed by **0x** (zero and a lowercase \"x\" or uppercase \"X\") represents a **hexadecimal number**"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Binary Value: 0b110010 , type of b: <class 'str'>\n",
"\n",
"Binary to integer: 0b110010 is 50\n"
]
}
],
"source": [
"# converting integer to binary value\n",
"b = bin(i)\n",
"print(\"Binary Value:\", b, \", type of b:\", type(b))\n",
"\n",
"# converting binary to integer value\n",
"print(\"\\nBinary to integer: 0b110010 is {}\".format(0b110010))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"number prefixed by **0b** (zero and a lowercase \"b\" or uppercase \"B\") represents a **binary number**"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Complex Number: (5+6j) , type of x: <class 'complex'>\n",
"Defining complex number using complex(): (4+3j)\n",
"\n",
"Float Representation:\n",
"4e8 is 400000000.0\n",
"-9.53e18 is -9.53e+18\n",
"float(nan) is nan\n",
"float(inf) is inf\n",
"float(-inf) is -inf\n"
]
}
],
"source": [
"# Real & Imaginary Number\n",
"x = 5 + 6j\n",
"print(\"Complex Number:\", x, \", type of x:\", type(x))\n",
"print(\"Defining complex number using complex():\", complex(4, 3))\n",
"\n",
"# Float numbers representation\n",
"print('\\nFloat Representation:\\n4e8 is {}'.format(4e8))\n",
"print('-9.53e18 is {}'.format(-9.53e18))\n",
"print('float(nan) is', float('nan'))\n",
"print('float(inf) is', float('inf'))\n",
"print('float(-inf) is', float('-inf'))"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String Representation:\n",
"Unicode: \\u0e21 is ม\n",
"Octal: \\521 is ő\n",
"Hex: \\x521 is R1\n"
]
}
],
"source": [
"# String representation\n",
"print('String Representation:\\nUnicode: \\\\u0e21 is {}'.format('\\u0e21'))\n",
"print('Octal: \\\\521 is {}'.format('\\521'))\n",
"print('Hex: \\\\x521 is {}'.format('\\x521'))"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 84,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# None keyword is different than float('nan') \n",
"None == float('nan')"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Multiple Variables Assignment"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Multiple variables of different datatypes can also be assigned together\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 4\n",
"b: 5.5\n",
"c: Hello\n"
]
}
],
"source": [
"a, b, c = 4, 5.5, 'Hello'\n",
"print('a:',a)\n",
"print('b:',b)\n",
"print('c:',c)"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 1\n",
"b: 2\n",
"c: [3, 4, 5]\n"
]
}
],
"source": [
"# Variables a and b are extracted individually, other elements are returned within the list\n",
"a, b, *c = [1, 2, 3, 4, 5]\n",
"print('a:',a)\n",
"print('b:',b)\n",
"print('c:',c)"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 1\n",
"b: Hello\n",
"c: ['Hi', 'Hey']\n",
"d: 4.5\n",
"e: True\n",
"f: ('Ten', 20, 30.5, False)\n",
"\n",
"Class of a: <class 'int'>\n",
"Class of b: <class 'str'>\n",
"Class of c: <class 'list'>\n",
"Class of d: <class 'float'>\n",
"Class of e: <class 'bool'>\n",
"Class of f: <class 'tuple'>\n"
]
}
],
"source": [
"# multiple assignment to various variables\n",
"a, b, c, d, e, f = 1, 'Hello', [\"Hi\",\n",
" \"Hey\"], 4.5, True, (\"Ten\", 20, 30.5, False)\n",
"print(\"a:\", a)\n",
"print(\"b:\", b)\n",
"print(\"c:\", c)\n",
"print(\"d:\", d)\n",
"print(\"e:\", e)\n",
"print(\"f:\", f)\n",
"\n",
"print(\"\\nClass of a:\", type(a))\n",
"print(\"Class of b:\", type(b))\n",
"print(\"Class of c:\", type(c))\n",
"print(\"Class of d:\", type(d))\n",
"print(\"Class of e:\", type(e))\n",
"print(\"Class of f:\", type(f))"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: (1, 2, 3, 4, 5)\n"
]
}
],
"source": [
"# Tuple\n",
"a = 1, 2, 3, 4, 5\n",
"print('a:', a)"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: Ten\n",
"b: 20\n",
"c: 30.5\n",
"d: False\n"
]
}
],
"source": [
"# Unpacking tuple\n",
"a, b, c, d = (\"Ten\", 20, 30.5, False)\n",
"print(\"a:\", a)\n",
"print(\"b:\", b)\n",
"print(\"c:\", c)\n",
"print(\"d:\", d)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## `is` statement and id()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>id()</b> return a unique identifier for an object within the memory<li><b>==</b> is the <b>equality comparison</b><li><b>is</b> the <b>identity comparison</b></div>"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3]\n",
"b: [1, 2, 3]\n",
"\n",
"a==b: True\n",
"a is b: False\n",
"\n",
"id(a): 2520830847488\n",
"id(b): 2520830847424\n",
"id(a)==id(b): False\n"
]
}
],
"source": [
"a = [1, 2, 3]\n",
"b = [1, 2, 3]\n",
"print('a:',a)\n",
"print('b:',b)\n",
"\n",
"print('\\na==b:', a == b) # Values are equivalent\n",
"print('a is b:', a is b) # Separate objects\n",
"\n",
"print('\\nid(a):', id(a))\n",
"print('id(b):', id(b))\n",
"\n",
"# id of 'b' is not same as id of 'a' as they both refer to the different object in memory\n",
"print(\"id(a)==id(b):\", id(a)==id(b))"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x: 4\n",
"y: 5\n",
"x+y: 9\n",
"\n",
"a: 1 , id of a is: 2520354875696\n",
"b: 1 , id of b is: 2520354875696\n",
"id(a)==id(b): True\n",
"\n",
"b: 2 , id of b is: 2520354875728\n",
"id(a)==id(b): False\n"
]
}
],
"source": [
"x = 4\n",
"y = 5\n",
"print('x:', x)\n",
"print('y:', y)\n",
"print(\"x+y:\", x + y)\n",
"\n",
"# demonstrating the id function\n",
"a = 1\n",
"print(\"\\na:\", a, \", id of a is:\", id(a))\n",
"\n",
"# variable 'b' is pointing to 'a'\n",
"b = a\n",
"print(\"b:\", b, \", id of b is:\", id(b))\n",
"\n",
"# id of 'b' is same as id of 'a' as they both refer to the same object in memory\n",
"print(\"id(a)==id(b):\", id(a) == id(b))\n",
"\n",
"# value of variable 'b' is changed\n",
"b = 2\n",
"# id of 'b' will be changed\n",
"print(\"\\nb:\", b, \", id of b is:\", id(b))\n",
"print(\"id(a)==id(b):\", id(a) == id(b))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* `not` is also used to check empty objects\n",
"* **a is not b** is a special operator which is equivalent to **not a is b**"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3]\n",
"not a: False\n"
]
}
],
"source": [
"a = [1, 2, 3]\n",
"print('a:',a)\n",
"\n",
"# a is not empty, returns False\n",
"print('not a:', not a) "
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: []\n",
"not a: True\n"
]
}
],
"source": [
"a = []\n",
"print('a:',a)\n",
"\n",
"# a is empty, returns True\n",
"print('not a:', not a) "
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3]\n",
"b: [1, 2, 3]\n",
"\n",
"a is a: True\n",
"a is not a: False\n",
"\n",
"a is b: False\n",
"a is not b: True\n",
"not a is b: True\n"
]
}
],
"source": [
"a = [1, 2, 3]\n",
"b = [1, 2, 3]\n",
"print('a:', a)\n",
"print('b:', b)\n",
"\n",
"print('\\na is a:', a is a)\n",
"print('a is not a:', a is not a)\n",
"\n",
"print('\\na is b:', a is b)\n",
"print('a is not b:', a is not b)\n",
"print('not a is b:', not a is b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Difference between Referencing and Cloning</div>"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A: [1, 2, 3]\n",
"B: [1, 2, 3]\n",
"C: [1, 2, 3]\n",
"\n",
"Changing a[2]=5,\n",
"\n",
"A: [1, 2, 5]\n",
"B: [1, 2, 5]\n",
"C: [1, 2, 3]\n"
]
}
],
"source": [
"a = [1, 2, 3]\n",
"print('A:', a)\n",
"\n",
"# list B is referencing to list A\n",
"b = a\n",
"print('B:', b)\n",
"\n",
"# List C is created by cloning list A, a new list is created and not referenced\n",
"c = a[:]\n",
"print('C:', c)\n",
"\n",
"# change in List A\n",
"print('\\nChanging a[2]=5,')\n",
"a[2] = 5\n",
"\n",
"print('\\nA:', a)\n",
"\n",
"# notice that list B also changes at the same position since both are referencing to the same list in memory.\n",
"print('B:', b)\n",
"\n",
"# notice that list C doesn't changes because both are the different lists and they are not referencing to the same list in memory.\n",
"print('C:', c)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Input at runtime"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter number: 63\n",
"User entered: 63. It is a string\n",
"<class 'str'>\n",
"\n",
"After conversion, 63 is a integer\n",
"<class 'int'>\n"
]
}
],
"source": [
"# input function is used for inputting through keyboard\n",
"a = input(\"Enter number: \")\n",
"print(\"User entered: {}. It is a string\".format(a))\n",
"print(type(a)) # result is of string data type\n",
"\n",
"# In order to convert string into number, we can use object constructor int()\n",
"b = int(a)\n",
"print(\"\\nAfter conversion, {} is a integer\".format(b))\n",
"print(type(b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conditional statements if-else, elif statements"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Indentation is critical in order to avoid error"
]
},
{
"cell_type": "code",
"execution_count": 375,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x == 5 is correct\n"
]
}
],
"source": [
"x = 2 + 3\n",
"\n",
"if x == 5:\n",
" print(\"x == 5 is correct\")\n",
"else:\n",
" print(\"x == 5 is incorrect\")"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter Marks: 85\n",
"Marks scored: 85\n",
"Grade A\n"
]
}
],
"source": [
"# input() is enclosed inside int() which converts string into integer\n",
"marks = int(input(\"Enter Marks: \"))\n",
"print(\"Marks scored: {}\".format(marks))\n",
"\n",
"if marks >= 75: # if statement\n",
" print(\"Grade A\")\n",
"elif marks >= 60 and marks < 75: # else if statement\n",
" print(\"Grade B\")\n",
"else: # else statement\n",
" print(\"Grade C\")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Value of x: 8\n",
"Value of y: 11\n",
"\n",
"y == 11 is Correct\n",
"\n",
"Value of z: 19\n"
]
}
],
"source": [
"#any ammount of whitespace on a single line is ok\n",
"x = 4 + 2 + 2\n",
"\n",
"# Defining x in multiple rows by using backslash `\\`\n",
"y = 2 + 4 +\\\n",
"5\n",
"\n",
"print(f\"Value of x: {x}\")\n",
"print(f\"Value of y: {y}\")\n",
"\n",
"print() # Printing blank line\n",
"\n",
"# Single line expression\n",
"print(\"y == 11 is Correct\") if y == 11 else print(\"y == 11 is Incorrect\")\n",
"\n",
"z = 0\n",
"if x%2 == 0: z = x+y\n",
"else: z = y-x\n",
"print()\n",
"print(f\"Value of z: {z}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## range()"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"range(0, 5) [0, 1, 2, 3, 4]\n",
"range(4, 8) [4, 5, 6, 7]\n",
"range(1, 10, 2) [1, 3, 5, 7, 9]\n"
]
}
],
"source": [
"# range(n) generates a sequence from 0 to n-1\n",
"# list(range(n)) is used to represent the range in form of a list\n",
"\n",
"print(range(5), list(range(5)))\n",
"print(range(4, 8), list(range(4, 8)))\n",
"print(range(1, 10, 2), list(range(1, 10, 2)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## For Loop "
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [5, 2, 6, 2, 5, 1, 5]\n",
"5\n",
"2\n",
"6\n",
"2\n",
"5\n",
"1\n",
"5\n"
]
}
],
"source": [
"a = [5, 2, 6, 2, 5, 1, 5]\n",
"print(\"a: \", a)\n",
"\n",
"for i in a: # iterates over each element in list\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [5, 2, 6, 2, 5, 1, 5]\n",
"Element 0: 5\n",
"Element 1: 2\n",
"Element 2: 6\n",
"Element 3: 2\n",
"Element 4: 5\n",
"Element 5: 1\n",
"Element 6: 5\n"
]
}
],
"source": [
"a = [5, 2, 6, 2, 5, 1, 5]\n",
"print(\"a: \", a)\n",
"\n",
"for i in range(len(a)): # iterates over each index in list\n",
" print(\"Element {}: {}\".format(i, a[i]))"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [10, 20, 30, 40, 50]\n",
"b: [100, 200, 300, 400, 500]\n"
]
}
],
"source": [
"a = [10, 20, 30, 40, 50]\n",
"b = []\n",
"print(\"a: \", a)\n",
"\n",
"for i in a:\n",
" b.append((i * 10))\n",
"print(\"b: \", b)"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [10, 20, 30, 40, 50]\n",
"b: [100, 200, 300, 400, 500]\n"
]
}
],
"source": [
"# List Comprehension using for loop\n",
"\n",
"a = [10, 20, 30, 40, 50]\n",
"print(\"a: \", a)\n",
"\n",
"b = [i * 10 for i in a]\n",
"print(\"b: \", b)"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"b: [1, 4, 27, 16, 125, 36, 343, 64, 729]\n"
]
}
],
"source": [
"# Example: number squared for even and cubed for odd\n",
"\n",
"a = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"print(\"a: \", a)\n",
"\n",
"b = [num**2 if num % 2 == 0 else num**3 for num in a]\n",
"print(\"b: \", b)"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"{10: 100, 20: 400, 30: 900, 40: 1600, 50: 2500}"
]
},
"execution_count": 107,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Dictionary Comprehension\n",
"\n",
"a = [10, 20, 30, 40, 50]\n",
"{x: x**2 for x in a}"
]
},
{
"cell_type": "code",
"execution_count": 148,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{10, 11, 13, 15, 17, 18, 19}\n"
]
}
],
"source": [
"# Set Comprehension\n",
"\n",
"a = {x for x in range(10,20) if x not in [12,14,16]}\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## enumerate()"
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [5, 2, 6, 2, 5, 1, 5]\n",
"Element 1: 5\n",
"Element 2: 2\n",
"Element 3: 6\n",
"Element 4: 2\n",
"Element 5: 5\n",
"Element 6: 1\n",
"Element 7: 5\n"
]
}
],
"source": [
"a = [5, 2, 6, 2, 5, 1, 5]\n",
"print(\"a: \", a)\n",
"\n",
"# enumerate() yields (index,value) tuples\n",
"for i, k in enumerate(a, start=1):\n",
" print(\"Element {}: {}\".format(i, k))"
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 5), (2, 2), (3, 6), (4, 2), (5, 5), (6, 1), (7, 5)]"
]
},
"execution_count": 109,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# enumerate function can also be used directly on the list\n",
"list(enumerate(a, start=1))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## While loop"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [5, 2, 6, 2, 5, 1, 5]\n",
"Element 0: 5\n",
"Element 1: 2\n",
"Element 2: 6\n",
"Element 3: 2\n",
"Element 4: 5\n",
"Element 5: 1\n",
"Element 6: 5\n"
]
}
],
"source": [
"a = [5, 2, 6, 2, 5, 1, 5]\n",
"print(\"a: \", a)\n",
"\n",
"i = 0\n",
"while i < len(a):\n",
" print(\"Element {}: {}\".format(i, a[i]))\n",
" i = i + 1"
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original list: ['String', 84.1, 'text', 45.32, 23, 'Number', 24, 36.4, 'Some text', 31]\n",
"\n",
"After Data cleaning,\n",
"List with numbers: [84.1, 45.32, 23, 24, 36.4, 31]\n",
"List with strings: ['String', 'text', 'Number', 'Some text']\n"
]
}
],
"source": [
"# Data cleaning program (list containing numbers and string are filtered)\n",
"\n",
"i = 0\n",
"main_list = [\n",
" \"String\", 84.1, \"text\", 45.32, 23, \"Number\", 24, 36.4, \"Some text\", 31\n",
"]\n",
"new_list = []\n",
"length = len(main_list)\n",
"print(\"Original list: {}\".format(main_list))\n",
"\n",
"while i < length:\n",
" if isinstance(main_list[i], int) or isinstance(main_list[i], float):\n",
" new_list.append(main_list[i])\n",
" main_list.pop(i)\n",
" length -= 1\n",
" i -= 1\n",
" i += 1\n",
"\n",
"print(\"\\nAfter Data cleaning,\\nList with numbers: {}\".format(new_list))\n",
"print(\"List with strings: {}\".format(main_list))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Break and continue statements"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"5\n",
"6\n",
"7\n"
]
}
],
"source": [
"for i in range(10):\n",
" if (i == 4):\n",
" continue # element 4 is skipped\n",
" if (i == 8):\n",
" break # loop stops as it reaches 8\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Creating Functions using `def`"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Functions are defined for code-reusability<li>Indentation is critical</div>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Learner!\n"
]
}
],
"source": [
"# Function definition\n",
"def hello():\n",
" print(\"Hello Learner!\")\n",
" \n",
"# Function calling\n",
"hello()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Jamwine!\n"
]
}
],
"source": [
"# Adding a parameter name\n",
"def hello(name): print(f\"Hello {name}!\")\n",
"# Writing the function in a singlr line, as the function has only a single line\n",
"\n",
"hello('Jamwine')"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Returning function data_clean: ['String', 'text', 'Number', 'Some text'] [] \n",
"\n",
"Help on function data_clean in module __main__:\n",
"\n",
"data_clean(main_list)\n",
" List containing numbers and string are filtered\n",
"\n"
]
}
],
"source": [
"# Compiling the Data cleaning program inside function\n",
"\n",
"def data_clean(main_list): # function declaration\n",
" ''' \n",
" List containing numbers and string are filtered \n",
" ''' # Documentation of function is enclosed in paragraph\n",
" i = 0\n",
" new_list = [] # Local variable\n",
" length = len(main_list)\n",
" while i < length:\n",
" if isinstance(main_list[i], int) or isinstance(main_list[i], float):\n",
" new_list.append(main_list[i])\n",
" main_list.pop(i)\n",
" length -= 1\n",
" i -= 1\n",
" i += 1\n",
" return main_list, new_list # return statement returns the value\n",
"\n",
"\n",
"# function calling\n",
"b, c = data_clean(a)\n",
"print(\"Returning function data_clean:\", b, c, \"\\n\")\n",
"\n",
"# On calling the help(), we can see the documentation of the function.\n",
"help(data_clean)"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original list: ['String', 84.1, 'text', 45.32, 23, 'Number', 24, 36.4, 'Some text', 31] \n",
"\n",
"Returning function sum_list: 243.82 \n",
"\n",
"Help on function sum_list in module __main__:\n",
"\n",
"sum_list(x)\n",
" Sum of list elements\n",
"\n"
]
}
],
"source": [
"def sum_list(x):\n",
" '''\n",
" Sum of list elements \n",
" '''\n",
" total = 0\n",
" for i in x:\n",
" if isinstance(i, int) or isinstance(i, float):\n",
" total = total + i\n",
" else:\n",
" pass # pass statement means do nothing\n",
" return total\n",
"\n",
"\n",
"a = [\"String\", 84.1, \"text\", 45.32, 23, \"Number\", 24, 36.4, \"Some text\", 31]\n",
"print(\"Original list: {}\".format(a), \"\\n\")\n",
"\n",
"d = sum_list(a)\n",
"print(\"Returning function sum_list:\", d, \"\\n\")\n",
"\n",
"help(sum_list)"
]
},
{
"cell_type": "code",
"execution_count": 121,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Calling function when only one parameter is defined: 8\n",
"Calling function when both parameters are defined: 12\n"
]
}
],
"source": [
"def add(a, b=5):\n",
" total = a + b\n",
" return total\n",
"\n",
"\n",
"# default value for b is taken\n",
"print(\"Calling function when only one parameter is defined: \", add(3))\n",
"\n",
"# default value is replaced\n",
"print(\"Calling function when both parameters are defined: \", add(4, 8))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Defining <b>Histogram</b> using dictionary</div>"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String: This is a sample text string\n",
"\n",
"Histogram h1: {'T': 1, 'h': 1, 'i': 3, 's': 4, ' ': 5, 'a': 2, 'm': 1, 'p': 1, 'l': 1, 'e': 2, 't': 3, 'x': 1, 'r': 1, 'n': 1, 'g': 1}\n",
"No. of times 'i' present in h1: 3\n",
"No. of times 's' present in h1: 4\n"
]
}
],
"source": [
"def histogram(x):\n",
" a = dict()\n",
" for i in x:\n",
" if i not in a:\n",
" a[i] = 1\n",
" else:\n",
" a[i] += 1\n",
" return a\n",
"\n",
"\n",
"# Example_1\n",
"s = 'This is a sample text string'\n",
"print(\"String:\", s)\n",
"\n",
"h1 = histogram(s)\n",
"print(\"\\nHistogram h1:\", h1)\n",
"print(\"No. of times 'i' present in h1: %d\" % (h1.get('i'))\n",
" ) # fetching a particular frequency of an individual element using get()\n",
"print(\"No. of times 's' present in h1: %d\" % (h1.get('s')))"
]
},
{
"cell_type": "code",
"execution_count": 125,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List: [9, 9, 2, 7, 0, 7, 4, 6, 8, 8, 7, 9, 0, 4, 7, 8, 0, 9, 5, 2, 7, 9, 0, 3, 7, 1, 7, 0, 5, 2, 7, 9, 9, 8, 6, 3, 1, 2, 6, 5, 9, 3, 1, 8, 1, 2, 5, 6, 9, 0, 6, 3, 2, 9, 0, 9, 1, 2, 5, 1, 6, 4, 8, 7, 6, 5, 9, 1, 9, 8, 2, 2, 6, 5, 3, 7, 4, 0, 0, 3, 9, 7, 6, 9, 0, 2, 7, 8, 4, 0, 4, 2, 7, 3, 7, 8, 4, 4, 5, 2]\n",
"\n",
"Histogram h2: {9: 15, 2: 12, 7: 14, 0: 11, 4: 8, 6: 9, 8: 9, 5: 8, 3: 7, 1: 7}\n",
"No. of times '3' present in h2: 7\n",
"No. of times '7' present in h2: 14\n"
]
}
],
"source": [
"# Example_2\n",
"import random as rd\n",
"\n",
"l = []\n",
"for i in range(100):\n",
" k = rd.randint(0, 9)\n",
" l.append(k)\n",
"print(\"List:\", l)\n",
"\n",
"h2 = histogram(l)\n",
"print(\"\\nHistogram h2:\", h2)\n",
"print(\"No. of times '3' present in h2: %d\" % (h2.get(3)))\n",
"print(\"No. of times '7' present in h2: %d\" % (h2.get(7)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Lambda Statement"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">Lambda functions are:<li>used to create small anonymous functions with <b>lambda</b> keyword <li>defined when the functions are used very less<li>used wherever function objects are needed<li>created with any number of arguments but only one expression</div>"
]
},
{
"cell_type": "code",
"execution_count": 127,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3, 4, 5]\n",
"\n",
"Result using function: 61.0\n",
"Result using lambda expression: 61.0\n"
]
}
],
"source": [
"# Example 1\n",
"a = [1, 2, 3, 4, 5]\n",
"print(\"a: \", a)\n",
"\n",
"\n",
"# some function for calculation\n",
"def expr(x):\n",
" return ((x**x + x) / x) - x # some expression\n",
"\n",
"\n",
"print(\"\\nResult using function:\", expr(4))\n",
"\n",
"# the above function can be illustrated using lambda function\n",
"a = lambda x: ((x**x + x) / x) - x\n",
"print(\"Result using lambda expression:\", a(4))"
]
},
{
"cell_type": "code",
"execution_count": 135,
"metadata": {
"code_folding": [],
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Lambda object: <function <lambda> at 0x0000024AEE6329D0>\n",
"\n",
"Calculating Sum using lambda function: 7\n"
]
}
],
"source": [
"# Example 2\n",
"s = lambda x, y: x + y\n",
"print(\"Lambda object:\", s)\n",
"\n",
"print('\\nCalculating Sum using lambda function:', s(3, 4))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## join()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**join()** is used to join a list of strings using some **string** in between its elements (works opposite to the **split()**)"
]
},
{
"cell_type": "code",
"execution_count": 145,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String: This is a sample text\n",
"After split(): ['This', 'is', 'a', 'sample', 'text']\n",
"\n",
"Joining list by - using join(): This-is-a-sample-text\n",
"\n",
"Joining list by | using join(): This | is | a | sample | text\n",
"\n",
"Joining list by using join(): This is a sample text\n",
"\n",
"Joining list by _ using join(): This_is_a_sample_text\n",
"\n",
"Joining list by ' ' using lambda expression: This is a sample text\n"
]
}
],
"source": [
"s = \"This is a sample text\"\n",
"print(\"String:\", s)\n",
"\n",
"s = s.split()\n",
"print(\"After split():\", s)\n",
"\n",
"a = '-'\n",
"print(f\"\\nJoining list by {a} using join(): {a.join(s)}\")\n",
"\n",
"b = ' | '\n",
"print(f\"\\nJoining list by {b} using join(): {b.join(s)}\")\n",
"\n",
"c = ' ' # empty string with space\n",
"print(f\"\\nJoining list by {c} using join(): {c.join(s)}\")\n",
"\n",
"d = '_'\n",
"print(f\"\\nJoining list by {d} using join(): {d.join(s)}\")\n",
"\n",
"# using lambda\n",
"x = lambda a: ' '.join(a)\n",
"print(\"\\nJoining list by ' ' using lambda expression:\", x(s))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## pow()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The function **pow()** takes two arguments, equivalent to `x^y`. With three arguments it is equivalent to `(x^y)%z`, but may be more efficient for long integers."
]
},
{
"cell_type": "code",
"execution_count": 147,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 ^ 5: 32\n",
"2 ^ 5: 32\n",
"(2 ^ 5) % 3: 2\n"
]
}
],
"source": [
"print(\"2 ^ 5: \", 2**5)\n",
"print(\"2 ^ 5: \", pow(2, 5))\n",
"print(\"(2 ^ 5) % 3: \", pow(2, 5, 3))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## abs()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The function **abs()** returns the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned."
]
},
{
"cell_type": "code",
"execution_count": 149,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"abs(-57): 57\n",
"abs(2.39): 2.39\n",
"abs(12+2j): 12.165525060596439\n"
]
}
],
"source": [
"print(\"abs(-57): \", abs(-57))\n",
"print(\"abs(2.39): \", abs(2.39))\n",
"print(\"abs(12+2j): \", abs(12 + 2j))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## round()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The function **round()** will round a number to a given precision in decimal digits (default 0 digits). It does not convert integers to floats."
]
},
{
"cell_type": "code",
"execution_count": 159,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"round(3.14): 3\n",
"round(3.14,1): 3.1\n",
"round(6.1495,2): 6.15\n",
"\n",
"round(314, -1): 310\n",
"round(314,-2): 300\n",
"\n",
"round(2379,-1): 2380\n",
"round(2379,-2): 2400\n",
"round(2379,-3): 2000\n"
]
}
],
"source": [
"print(\"round(3.14): \", round(3.14))\n",
"print(\"round(3.14,1): \", round(3.14, 1))\n",
"print(\"round(6.1495,2): \", round(6.1495, 2))\n",
"\n",
"print(\"\\nround(314, -1): \", round(314, -1))\n",
"print(\"round(314,-2): \", round(314, -2))\n",
"\n",
"print(\"\\nround(2379,-1): \", round(2379, -1))\n",
"print(\"round(2379,-2): \", round(2379, -2))\n",
"print(\"round(2379,-3): \", round(2379, -3))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## divmod()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**divmod()** takes two arguments and returns a tuple of two values, quotient and remainder "
]
},
{
"cell_type": "code",
"execution_count": 160,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 5\n",
"b: 2\n",
"a//b: 2\n",
"a%b: 1\n",
"\n",
"Quotient using divmod(): 2\n",
"Remainder using divmod(): 1\n"
]
}
],
"source": [
"a = 5\n",
"b = 2\n",
"print(\"a:\", a)\n",
"print(\"b:\", b)\n",
"print(\"a//b:\", a // b) # Quotient\n",
"print(\"a%b:\", a % b) # Remainder\n",
"\n",
"quot, rem = divmod(a, b)\n",
"print(\"\\nQuotient using divmod():\", quot)\n",
"print(\"Remainder using divmod():\", rem)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## zip()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**zip()** is used for packing elements, contains one element from each sequence."
]
},
{
"cell_type": "code",
"execution_count": 161,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x: [('H', '1'), ('e', '2'), ('l', '3'), ('l', '4'), ('o', '5')]\n",
"Type: <class 'zip'>\n"
]
}
],
"source": [
"x = zip(\"Hello\", \"12345\")\n",
"print(\"x: \", list(x)) # result is changed into list\n",
"print(\"Type: \", type(x)) # zip is a class"
]
},
{
"cell_type": "code",
"execution_count": 163,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y: [(1, 'abc'), (2, 'pqr'), (3, 'xyz')]\n"
]
}
],
"source": [
"# contains three elements (shorter length is considered)\n",
"y = list(zip([1, 2, 3, 4], ('abc', 'pqr', 'xyz')))\n",
"print(\"y: \", y)"
]
},
{
"cell_type": "code",
"execution_count": 167,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y: [(1, 'abc'), (2, 'pqr'), (3, 'xyz')]\n",
"\n",
"After unzip, \n",
"a: (1, 2, 3) \n",
"b: ('abc', 'pqr', 'xyz')\n"
]
}
],
"source": [
"# in order to get back the lists, we can unzip the list of tuples using the asterisk\n",
"print(\"y: \", y)\n",
"\n",
"a, b = zip(*y)\n",
"print(\"\\nAfter unzip, \\na: {} \\nb: {}\".format(a, b))"
]
},
{
"cell_type": "code",
"execution_count": 170,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Using zip() on dictionaries:\n",
"d1: {'a': 1, 'b': 2}\n",
"d2: {'c': 4, 'd': 5}\n",
"\n",
"list(zip(d1,d2)): [('a', 'c'), ('b', 'd')]\n",
"list(zip(d2,d1.values())): [('c', 1), ('d', 2)]\n"
]
}
],
"source": [
"# zip() in dictionaries\n",
"print(f\"Using zip() on dictionaries:\")\n",
"\n",
"d1 = {'a': 1, 'b': 2}\n",
"print(f\"d1: {d1}\")\n",
"d2 = {'c': 4, 'd': 5}\n",
"print(f\"d2: {d2}\")\n",
"\n",
"print(f\"\\nlist(zip(d1,d2)): {list(zip(d1,d2))}\")\n",
"print(f\"list(zip(d2,d1.values())): {list(zip(d2,d1.values()))}\")"
]
},
{
"cell_type": "code",
"execution_count": 173,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Concatenating strings with connector using zip(): ['A-a', 'B-b']\n"
]
}
],
"source": [
"# Example: two strings from L1 and L2 concatenated together with a connector between them\n",
"def concatenate(L1, L2, connector):\n",
" return [word1 + connector + word2 for (word1, word2) in zip(L1, L2)]\n",
"\n",
"print(\"Concatenating strings with connector using zip():\",\n",
" concatenate(['A', 'B'], ['a', 'b'], '-'))"
]
},
{
"cell_type": "code",
"execution_count": 174,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
]
},
"execution_count": 174,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Transpose of a matrix\n",
"\n",
"a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
"transpose = [list(i) for i in zip(*a)]\n",
"transpose"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## map()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**map()** is used to apply the function on the specified sequence"
]
},
{
"cell_type": "code",
"execution_count": 180,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"\n",
"Function is applied to all the elements of list using map(): [3, 4, 5, 6, 7, 8, 9, 10, 11]\n",
"Applying Lambda expression to all the elements of list using map(): [3, 4, 5, 6, 7, 8, 9, 10, 11]\n"
]
}
],
"source": [
"a = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"print(\"List:\", a)\n",
"\n",
"# function that adds 2 to each element\n",
"def add_two(x):\n",
" x = x + 2\n",
" return x\n",
"\n",
"print(\"\\nFunction is applied to all the elements of list using map():\",\n",
" list(map(add_two, a)))\n",
"\n",
"# lambda function is mostly integrated in these cases in order to reduce the complexity of the program\n",
"c = list(map(lambda x: x + 2, a))\n",
"print(\"Applying Lambda expression to all the elements of list using map():\", c)"
]
},
{
"cell_type": "code",
"execution_count": 181,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"map() with multiple iterables: [15, 18, 21, 24]\n"
]
}
],
"source": [
"# multiple iterables\n",
"a = [1, 2, 3, 4]\n",
"b = [5, 6, 7, 8]\n",
"c = [9, 10, 11, 12]\n",
"\n",
"print(f\"map() with multiple iterables: {list(map(lambda x,y,z:x+y+z,a,b,c))}\")"
]
},
{
"cell_type": "code",
"execution_count": 184,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Phrase: This is a testing phrase\n",
"Words Length: [4, 2, 1, 7, 6]\n"
]
}
],
"source": [
"# map() for finding the length of each word in the phrase (broken by spaces) and return the values in a list\n",
"def word_lengths(phrase):\n",
" return list(map(len, phrase.split()))\n",
"\n",
"phrase = \"This is a testing phrase\"\n",
"print(\"Phrase:\", phrase)\n",
"print(\"Words Length: \", word_lengths(phrase))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## filter()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**filter()** is used to filter the elements by applying the function on the particular sequence"
]
},
{
"cell_type": "code",
"execution_count": 188,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"Filter elements in list using filter(): [3, 6, 9]\n"
]
}
],
"source": [
"def div_3(x):\n",
" if (x % 3 == 0):\n",
" return x\n",
"\n",
"\n",
"a = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"print(\"a:\", a)\n",
"print(\"Filter elements in list using filter():\", list(filter(div_3, a)))"
]
},
{
"cell_type": "code",
"execution_count": 190,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Words: ['hello', 'are', 'cat', 'dog', 'ham', 'hi', 'go', 'to', 'heart']\n",
"Filtering Words starting with 'h' from the list: ['hello', 'ham', 'hi', 'heart']\n"
]
}
],
"source": [
"def filter_words(word_list, letter):\n",
" return list(filter(lambda word: word[0] == letter, word_list))\n",
"\n",
"\n",
"words = ['hello', 'are', 'cat', 'dog', 'ham', 'hi', 'go', 'to', 'heart']\n",
"print(\"Words:\", words)\n",
"print(\"Filtering Words starting with 'h' from the list:\",\n",
" filter_words(words, 'h'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## reduce()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The function **reduce(function, sequence)** continually applies the function to the sequence. It then returns a single value. \n",
"\n",
"If $seq = [ s1, s2, s3, ... , sn ]$, calling $reduce(function, sequence)$ works like this:\n",
"\n",
"* At first the first two elements of seq will be applied to function, i.e. func(s1,s2). The list on which reduce() works looks now like this: $[ function(s1, s2), s3, ... , sn ]$\n",
"\n",
"\n",
"* In the next step the function will be applied on the previous result and the third element of the list, i.e. $function(function(s1, s2),s3)$. The list looks like this now: $[ function(function(s1, s2),s3), ... , sn ]$\n",
"\n",
"\n",
"* It continues like this until just one element is left and return this element as the result of $reduce()$"
]
},
{
"cell_type": "code",
"execution_count": 191,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"arr: [77, 41, 42, 13]\n",
"Sum of all elements using reduce(): 173\n"
]
}
],
"source": [
"from functools import reduce\n",
"\n",
"arr = [77, 41, 42, 13]\n",
"print('arr:', arr)\n",
"\n",
"# similar to sum()\n",
"print(\"Sum of all elements using reduce(): \", reduce(lambda x, y: x + y, arr))"
]
},
{
"cell_type": "code",
"execution_count": 195,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"arr: [77, 41, 42, 13]\n",
"\n",
"myfunc() result using reduce(): 65\n"
]
}
],
"source": [
"# Example: Get Difference of two elements if the first element is bigger, else add two elements\n",
"def myfunc(a, b):\n",
" return a - b if (a > b) else a + b\n",
"\n",
"\n",
"arr = [77, 41, 42, 13]\n",
"print('arr:', arr)\n",
"\n",
"print(\"\\nmyfunc() result using reduce(): \", reduce(myfunc, arr))"
]
},
{
"cell_type": "code",
"execution_count": 193,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"digits_to_num() result: 34321\n"
]
}
],
"source": [
"# Example: Converting a list of digits into number\n",
"def digits_to_num(digits):\n",
" return reduce(lambda x, y: x * 10 + y, digits)\n",
"\n",
"\n",
"print(\"\\ndigits_to_num() result:\", digits_to_num([3, 4, 3, 2, 1]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## All / Any"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* **all** returns True if all values are True, else returns False\n",
"* **any** returns True if any value is True, else returns False"
]
},
{
"cell_type": "code",
"execution_count": 223,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"all([True,False,False]): False\n",
"any([True,False,False]): True\n"
]
}
],
"source": [
"print('all([True,False,False]):', all([True, False, False]))\n",
"print('any([True,False,False]):', any([True, False, False]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Reading and Writing files "
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>write()</b> method is used to write<li><b>read()</b> method reads from the current position until the end of the file<li><b>readLines()</b> method is for reading all text on file and return a list of lines<li><b>readline()</b> method reads a single line from the current position<li><b>close()</b> method to manually close the file</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* **r**: Opens a file for **input** (reading). If the file does not exist, an **IOError** exception is raised.\n",
"\n",
"\n",
"* **r+**: Opens a file for **input** and **output**. If the file does not exist, causes an **IOError** exception.\n",
"\n",
"\n",
"* **w**: Opens a file for **output** (writing). If the file exists, it is **overwritten**. If the file does not exist, one is **created**.\n",
"\n",
"\n",
"* **w+**: Opens a file for **input** and **output**. If the file exists, it is **overwritten**; otherwise one is **created**.\n",
"\n",
"\n",
"* **a**: **Appends** all output to the end of the file; it **does not overwrite** information currently present. If the indicated file does not exist, it is **created**.\n",
"\n",
"\n",
"* **ab**, **rb**, **r+b**, **wb**, **w+b**: Opens a file for **binary**, non-textual input or output. (Note: these modes are supported only on the Windows and macOS platforms. \\*nix systems don't care about the data type.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python has a **built-in garbage collector**, so we don't really need to manually close our files; once an object is no longer referenced within memory, the object's memory space is automatically reclaimed. This applies to all objects in Python, including files.\n",
"\n",
"However, it's recommended to manually close files in large systems; it won't hurt anything and it's good to get into the habit in case we ever have to work in a language that doesn't have garbage collection. In addition, Python for other platforms, such as **Jython** or **IronPython**, may require us to manually close files to immediately free up resources, rather than waiting for garbage collection. Also, there are times when system operations have problems and a file is left open accidentally, resulting in a potential memory leak.\n",
"\n",
"The location of the file we are working with can be indicated as either an **absolute path** (a specific location on a drive) or a **relative path** (the file location in relation to the current directory); if no path is provided, the current directory is assumed."
]
},
{
"cell_type": "code",
"execution_count": 214,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Test1.txt created using write()\n"
]
}
],
"source": [
"# Creating file Test1.txt\n",
"\n",
"# w represents writing mode, wf is the alias name\n",
"with open('Test1.txt', 'w') as wf:\n",
" # write() is used to write text on file\n",
" wf.write(\"This is a sample test line\")\n",
" wf.write(\"\\nThis is a next line. \")\n",
" wf.write(\"Continuing last line.\")\n",
" print('Test1.txt created using write()')"
]
},
{
"cell_type": "code",
"execution_count": 215,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Reading Test1.txt created using read():\n",
"\n",
" This is a sample test line\n",
"This is a next line. Continuing last line.\n"
]
}
],
"source": [
"# Reading file Test1.txt\n",
"\n",
"# r represents reading mode\n",
"with open('Test1.txt', 'r') as twf:\n",
" # read() is used to read text on file\n",
" print('Reading Test1.txt created using read():\\n\\n', twf.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python treats a file as a **data stream**: each file is read and stored as a sequential flow of **byte**s. Each file has an **end-of-file (EOF) marker** denoting when the last byte of data has been read from it. Frequently, programs will read a file in pieces rather than loading the entire file into memory at one time. When the end-of-file marker is reached, the program knows there is nothing further to read and can continue with whatever processing it needs to do."
]
},
{
"cell_type": "code",
"execution_count": 216,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Appending text in Test1.txt\n",
"\n",
"Reading Test1.txt using readlines():\n",
"\n",
" ['This is a sample test line\\n', 'This is a next line. Continuing last line. This is the appended text.']\n"
]
}
],
"source": [
"# Appending in file Test1.txt\n",
"\n",
"# a represents appending in the existing file\n",
"with open('Test1.txt', 'a') as twf:\n",
" twf.write(\" This is the appended text.\")\n",
" print('Appending text in Test1.txt')\n",
"\n",
"# Reading file Test1.txt\n",
"with open('Test1.txt', 'r') as twf:\n",
" # readlines() is used to read text on file and returns a list of lines\n",
" print('\\nReading Test1.txt using readlines():\\n\\n', twf.readlines())"
]
},
{
"cell_type": "code",
"execution_count": 217,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Copying from one file into another file:\n",
" This is a sample test line\n",
"\n",
"Reading partial characters: This is a next line. Co\n",
"\n",
"Moving pointer in the file: 75\n",
"Reading Line: is the appended text.\n",
"\n",
"Name of the file: Test2.txt\n",
"Mode of the file: r\n"
]
}
],
"source": [
"# copying from one file into another\n",
"with open('Test1.txt', 'r') as rf:\n",
" with open('Test2.txt', 'w') as wf:\n",
" for line in rf:\n",
" wf.write(line)\n",
"\n",
"with open('Test2.txt', 'r') as twf:\n",
" # readline() is used to read the first line\n",
" print(\"Copying from one file into another file:\\n\", twf.readline())\n",
"\n",
" # reading next 23 characters from the last reading position\n",
" print(\"Reading partial characters:\", twf.read(23))\n",
"\n",
" print(\"\\nMoving pointer in the file:\", twf.seek(75))\n",
" print(\"Reading Line:\", twf.read())\n",
"\n",
"print(\"\\nName of the file:\", twf.name) # fetching the name of file\n",
"print(\"Mode of the file:\", twf.mode) # fetching the mode of file\n",
"twf.close() # closing file"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Seeking** is the process of moving a pointer within a file to an arbitrary position. This allows us to get data from anywhere within the file without having to start at the beginning every time.\n",
"\n",
"The **seek()** method can take several arguments. The first argument (**offset**) is the starting position of the pointer. The second, optional, argument is the **seek direction** from where the offset starts. The default value is `0` which indicates an offset relative to the beginning of the file, `1` is relative to the current position within the file, and `2` is relative to the end of the file.\n",
"\n",
"The **tell()** method returns the **current position of the pointer** within the file. This can be useful for **troubleshooting** (to make sure the pointer is actually in the location we think it is) or as a returned value for a function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As a best practice, it is advised that, instead of using `0`, `1`, or `2` for the **offset** starting position, we should import the `os` library and use the values `os.SEEK_SET`, `os.SEEK_CUR`, and `os.SEEK_END`. This is because the `os` library will use whatever values the operating system uses for **seeking**, rather than hardcoded numbers, just in case the OS does something different."
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Error handling"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li>Raise an exception to interrupt program flow<li>Handle an exception to resume control<li>Unhandled exceptions will terminate the program<li>Exception objects contain information about the exceptional event<li>Illustration of <b>try</b> and <b>except</b> blocks<li><b>Finally</b> block always executes in the end</div>"
]
},
{
"cell_type": "code",
"execution_count": 218,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error! Division by Zero is not possible\n",
"Error! Text cannot be converted into Float datatype\n",
"Error! String and Integer cannot be added\n"
]
}
],
"source": [
"# Errors are catched using try & except blocks\n",
"\n",
"# Scenario 1:\n",
"try:\n",
" b = 34 / 0\n",
"except:\n",
" print('Error! Division by Zero is not possible')\n",
"\n",
"# Scenario 2:\n",
"try:\n",
" float(\"Text\")\n",
"except:\n",
" print('Error! Text cannot be converted into Float datatype')\n",
"\n",
"# Scenario 3:\n",
"try:\n",
" 'Text' + 32\n",
"except:\n",
" print('Error! String and Integer cannot be added')"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Built-in Exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Exceptions are events that modify a program's flow, either intentionally or due to errors. Some examples are trying to open a file that doesn't exist, or when the program reaches a marker, such as the completion of a loop. \n",
"\n",
"<table>\n",
" <tr>\n",
" <th>Exception</th>\n",
" <th>Explanation</th>\n",
" </tr>\n",
" <tr>\n",
" <td>KeyboardInterrupt</td>\n",
" <td>Raised when user hits Ctrl-C, the interrupt key</td>\n",
" </tr>\n",
" <tr>\n",
" <td>OverflowError</td>\n",
" <td>Raised when a floating-point expression evaluates to a value that is too large</td>\n",
" </tr>\n",
" <tr>\n",
" <td>ZeroDivisionError</td>\n",
" <td>Raised when attempting to divide by 0</td>\n",
" </tr>\n",
" <tr>\n",
" <td>IOError</td>\n",
" <td>Raised when an I/O operation fails for an I/O-related reason</td>\n",
" </tr>\n",
" <tr>\n",
" <td>IndexError</td>\n",
" <td>Raised when a sequence index is outside the range of valid indexes</td>\n",
" </tr>\n",
" <tr>\n",
" <td>NameError</td>\n",
" <td>Raised when attempting to evaluate an unassigned identifier (name)</td>\n",
" </tr>\n",
" <tr>\n",
" <td>TypeError</td>\n",
" <td>Raised when an operation of function is applied to an object of the wrong type</td>\n",
" </tr>\n",
" <tr>\n",
" <td>ValueError</td>\n",
" <td>Raised when operation or function has an argument of the right type but incorrect value</td>\n",
" </tr>\n",
" <tr>\n",
" <td>KeyError</td>\n",
" <td>Raised when lookup in a mapping fails</td>\n",
" </tr>\n",
" <tr>\n",
" <td>AttributeError</td>\n",
" <td>Raised when calling a non-existent method of a class</td>\n",
" </tr>\n",
"</table>"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"def convert(s):\n",
" '''Convert to an integer'''\n",
" error = 0\n",
" try:\n",
" print(f\"Conversion Succeeded, x={s}\")\n",
" return int(s)\n",
" except (ValueError, TypeError) as e:\n",
" print(f'Conversion Failed: {str(e)}')\n",
" error = 1\n",
" raise # Exceptional conditions can be signaled using raise, without an argument it re-raises the current exception\n",
" finally:\n",
" if error == 0:\n",
" print('Successful !!')\n",
" elif error == 1:\n",
" print(f'Error is due to the wrong input: {s}')"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Conversion Succeeded, x=34\n",
"Successful !!\n"
]
},
{
"data": {
"text/plain": [
"34"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"convert('34')"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Conversion Succeeded, x=34.3\n",
"Successful !!\n"
]
},
{
"data": {
"text/plain": [
"34"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"convert(34.3)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Conversion Succeeded, x=37.5\n",
"Conversion Failed: invalid literal for int() with base 10: '37.5'\n",
"Error is due to the wrong input: 37.5\n"
]
},
{
"ename": "ValueError",
"evalue": "invalid literal for int() with base 10: '37.5'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-51-420cf37228e6>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mconvert\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"37.5\"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# Throws ValueError\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32m<ipython-input-48-e310ef28c8f9>\u001b[0m in \u001b[0;36mconvert\u001b[1;34m(s)\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"Conversion Succeeded, x={s}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mValueError\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf'Conversion Failed: {str(e)}'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: '37.5'"
]
}
],
"source": [
"convert(\"37.5\") # Throws ValueError"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Conversion Succeeded, x=[34, 45]\n",
"Conversion Failed: int() argument must be a string, a bytes-like object or a number, not 'list'\n",
"Error is due to the wrong input: [34, 45]\n"
]
},
{
"ename": "TypeError",
"evalue": "int() argument must be a string, a bytes-like object or a number, not 'list'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-52-5449839815b9>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mconvert\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m34\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m45\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# Throws TypeError\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32m<ipython-input-48-e310ef28c8f9>\u001b[0m in \u001b[0;36mconvert\u001b[1;34m(s)\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"Conversion Succeeded, x={s}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32mexcept\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mValueError\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf'Conversion Failed: {str(e)}'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: int() argument must be a string, a bytes-like object or a number, not 'list'"
]
}
],
"source": [
"convert([34, 45]) # Throws TypeError"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exception class hierarchy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When an exception occurs, it starts at the innermost level possible (a child) and travels upward (through the parents), waiting to be caught. This means a couple of things to a programmer:\n",
"\n",
"* If we don't know what exception may occur, we can always just catch a higher-level exception. For example, if we didn't know that **ZeroDivisionError** was its own exception, we could have used the **ArithmeticError** for the exception and caught that. **ZeroDivisionError** is a child of **ArithmeticError**, which in turn is a child of **Exception**, which in turn is a child of **BaseException**, which is the default class that all other exceptions derive from.\n",
"\n",
"\n",
"* Multiple exceptions can be treated the same way. Suppose we plan on using **ZeroDivisionError** and we want to include **FloatingPointError**. If we wanted to have the same action taken for both errors, simply catch the parent exception, **ArithmeticError**. That way, when either a floating-point or a zero-division error occurs, we don't have to have a separate case for each one. Naturally, if we have a need or desire to catch each one separately, perhaps because we want different actions to be taken, then writing exceptions for each case is fine. Also, catching the parent exception means all children exceptions of that parent, even ones we didn't intend to catch.\n",
"\n",
"\n",
"The following exceptions list shows the hierarchy of exceptions from the Python Library Reference:\n",
"```python\n",
"BaseException \n",
" +-- SystemExit \n",
" +-- KeyboardInterrupt \n",
" +-- GeneratorExit \n",
" +-- Exception \n",
" +-- StopIteration \n",
" +-- StopAsyncIteration \n",
" +-- ArithmeticError \n",
" | +-- FloatingPointError \n",
" | +-- OverflowError \n",
" | +-- ZeroDivisionError \n",
" +-- AssertionError \n",
" +-- AttributeError \n",
" +-- BufferError \n",
" +-- EOFError \n",
" +-- ImportError \n",
" | +-- ModuleNotFoundError \n",
" +-- LookupError \n",
" | +-- IndexError \n",
" | +-- KeyError \n",
" +-- MemoryError \n",
" +-- NameError \n",
" | +-- UnboundLocalError \n",
" +-- OSError \n",
" | +-- BlockingIOError \n",
" | +-- ChildProcessError \n",
" | +-- ConnectionError \n",
" | | +-- BrokenPipeError \n",
" | | +-- ConnectionAbortedError \n",
" | | +-- ConnectionRefusedError \n",
" | | +-- ConnectionResetError \n",
" | +-- FileExistsError \n",
" | +-- FileNotFoundError \n",
" | +-- InterruptedError \n",
" | +-- IsADirectoryError \n",
" | +-- NotADirectoryError \n",
" | +-- PermissionError \n",
" | +-- ProcessLookupError \n",
" | +-- TimeoutError \n",
" +-- ReferenceError \n",
" +-- RuntimeError \n",
" | +-- NotImplementedError \n",
" | +-- RecursionError \n",
" +-- SyntaxError \n",
" | +-- IndentationError \n",
" | +-- TabError \n",
" +-- SystemError \n",
" +-- TypeError \n",
" +-- ValueError \n",
" | +-- UnicodeError \n",
" | +-- UnicodeDecodeError \n",
" | +-- UnicodeEncodeError \n",
" | +-- UnicodeTranslateError \n",
" +-- Warning \n",
" +-- DeprecationWarning \n",
" +-- PendingDeprecationWarning \n",
" +-- RuntimeWarning \n",
" +-- SyntaxWarning \n",
" +-- UserWarning \n",
" +-- FutureWarning \n",
" +-- ImportWarning \n",
" +-- UnicodeWarning \n",
" +-- BytesWarning \n",
" +-- ResourceWarning\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### User-Defined Exception"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Making our own exceptions involves object-oriented programming. To make a custom exception, simply inherit the base exception and define what it will do. The following example gives an example of creating a custom exception:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.7320508075688772\n"
]
},
{
"ename": "NegativeNumberError",
"evalue": "Square root of negative number not permitted",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNegativeNumberError\u001b[0m Traceback (most recent call last)",
"Input \u001b[1;32mIn [6]\u001b[0m, in \u001b[0;36m<cell line: 14>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m math\u001b[38;5;241m.\u001b[39msqrt(number)\n\u001b[0;32m 13\u001b[0m \u001b[38;5;28mprint\u001b[39m(squareRoot(\u001b[38;5;241m3\u001b[39m))\n\u001b[1;32m---> 14\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msquareRoot\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m-\u001b[39;49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m)\u001b[49m)\n",
"Input \u001b[1;32mIn [6]\u001b[0m, in \u001b[0;36msquareRoot\u001b[1;34m(number)\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[38;5;124;03m\"\"\"Computes square root of number. Raises NegativeNumberError if number is less than 0.\"\"\"\u001b[39;00m \n\u001b[0;32m 9\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m number \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m---> 10\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m NegativeNumberError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mSquare root of negative number not permitted\u001b[39m\u001b[38;5;124m\"\u001b[39m) \n\u001b[0;32m 11\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m math\u001b[38;5;241m.\u001b[39msqrt(number)\n",
"\u001b[1;31mNegativeNumberError\u001b[0m: Square root of negative number not permitted"
]
}
],
"source": [
"import math\n",
"\n",
"class NegativeNumberError(ValueError): \n",
" \"\"\"Attempted improper operation on negative number.\"\"\" \n",
" pass\n",
"\n",
"def squareRoot(number): \n",
" \"\"\"Computes square root of number. Raises NegativeNumberError if number is less than 0.\"\"\" \n",
" if number < 0:\n",
" raise NegativeNumberError(\"Square root of negative number not permitted\") \n",
" return math.sqrt(number)\n",
" \n",
"print(squareRoot(3))\n",
"print(squareRoot(-3))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Iterator"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* **Iterable objects** (list, tuple, etc.) can be passed to the built-in **iter()** to get an iterator.\n",
"* Iterator objects can be passed to the built-in **next()** to fetch the next item."
]
},
{
"cell_type": "code",
"execution_count": 224,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Iterable List: ['Cow', 'Hen', 'Dog', 'Cat']\n",
"Iterator: <list_iterator object at 0x0000024AEE8484F0>\n",
"\n",
"Cow\n",
"Hen\n",
"Dog\n",
"Cat\n"
]
}
],
"source": [
"iterable = ['Cow', 'Hen', 'Dog', 'Cat']\n",
"iterator = iter(iterable)\n",
"print('Iterable List: ', iterable)\n",
"print('Iterator:', iterator) # object\n",
"print()\n",
"while 1:\n",
" try:\n",
" print(next(iterator))\n",
" except StopIteration as e:\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Generators"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"* **specify iterable sequences:** all generators are iterators\n",
"* **are lazily evaluated:** the next value in the sequence is computed on demand\n",
"* **can model infinite sequences:** such as data streams with no definite end\n",
"* **are composable into pipelines:** for natural stream processing\n",
"* Generators adapt the Just in Time Computations.\n",
"* Generator functions contains atleast one use of the **yield** keyword.\n",
"* Each call to a generator function creates a new generator object.\n",
"* These are generally used for infinite (or large) sequences, sensor readings, mathematical series, massive files, etc"
]
},
{
"cell_type": "code",
"execution_count": 180,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Generator: <generator object testgen at 0x000001FF1FFC5890>\n",
"\n",
"1\n",
"2\n",
"3\n"
]
}
],
"source": [
"def testgen():\n",
" yield 1\n",
" yield 2\n",
" yield 3\n",
"\n",
"\n",
"g = testgen()\n",
"print('Generator:', g) # object\n",
"print()\n",
"\n",
"# works similar to iterator\n",
"print(next(g)) \n",
"\n",
"# printing remaining elements\n",
"for each in g: \n",
" print(each)"
]
},
{
"cell_type": "code",
"execution_count": 181,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"def distinct(iterable):\n",
" ''' Return unique items by eliminating duplicates\n",
" \n",
" Args:\n",
" iterable: The source series\n",
" \n",
" Yields:\n",
" Unique elements in order from 'iterable'\n",
" '''\n",
" seen = set()\n",
" for item in iterable:\n",
" if item in seen:\n",
" continue\n",
" yield item\n",
" seen.add(item)"
]
},
{
"cell_type": "code",
"execution_count": 182,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"items = [3, 1, 4, 1, 1, 2, 5, 1, 3, 6, 1, 6, 1, 7, 3, 1, 3, 2, 4]"
]
},
{
"cell_type": "code",
"execution_count": 183,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"<generator object distinct at 0x000001FF201DD890>"
]
},
"execution_count": 183,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"distinct(items)"
]
},
{
"cell_type": "code",
"execution_count": 184,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 4, 2, 5, 6, 7]"
]
},
"execution_count": 184,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"distinct_items = list(distinct(items))\n",
"distinct_items"
]
},
{
"cell_type": "code",
"execution_count": 185,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"def take(count, iterable):\n",
" ''' Takes item from the front of an iterable\n",
" \n",
" Args:\n",
" count: The maximum number of items to retrieve\n",
" iterable: The source series\n",
" \n",
" Yields:\n",
" At most 'count' items from an 'iterable'\n",
" '''\n",
" counter = 0\n",
" for item in iterable:\n",
" if counter == count:\n",
" return\n",
" counter += 1\n",
" yield item"
]
},
{
"cell_type": "code",
"execution_count": 186,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"<generator object take at 0x000001FF1F9483C0>"
]
},
"execution_count": 186,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n_unique_items = take(5, distinct_items)\n",
"n_unique_items"
]
},
{
"cell_type": "code",
"execution_count": 187,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 4, 2, 5]"
]
},
"execution_count": 187,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(n_unique_items)"
]
},
{
"cell_type": "code",
"execution_count": 188,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 4, 2]"
]
},
"execution_count": 188,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Defining a pipeline by using defined distinct() and take()\n",
"\n",
"def run_pipeline(n, items): \n",
" return [item for item in take(n, distinct(items))]\n",
"\n",
"pipe = run_pipeline(4, items)\n",
"pipe"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The **next()** will yield the next number from the iterable."
]
},
{
"cell_type": "code",
"execution_count": 212,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"def run_pipeline(n, items):\n",
" for item in take(n, distinct(items)):\n",
" yield item "
]
},
{
"cell_type": "code",
"execution_count": 214,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 1 4 2 \n"
]
}
],
"source": [
"pipe = run_pipeline(4, items)\n",
"\n",
"while 1:\n",
" try:\n",
" print(next(pipe), end = ' ')\n",
" except StopIteration as e:\n",
" print(e)\n",
" break"
]
},
{
"cell_type": "code",
"execution_count": 215,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "StopIteration",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-215-e491198df0d4>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mpipe\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mStopIteration\u001b[0m: "
]
}
],
"source": [
"next(pipe)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Since there are no items left, the iteration stops with the **StopIteration error**. "
]
},
{
"cell_type": "code",
"execution_count": 219,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: <generator object <genexpr> at 0x000001FF1FD42F90>\n",
"Class of Model: <class 'generator'>\n",
"Sum of model: 333332833333500000\n"
]
}
],
"source": [
"# Defining model specifications\n",
"\n",
"# Tuple is used instead of list to create a generator object\n",
"squares = (x * x for x in range(1, int(10e5)))\n",
"\n",
"# returns generator object, saves memory by just defining and not running it\n",
"print('Model: ', squares)\n",
"print('Class of Model: ', type(squares))\n",
"print('Sum of model: ', sum(squares))"
]
},
{
"cell_type": "code",
"execution_count": 217,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: [1, 2, 3]\n",
"b: [4, 5, 6]\n",
"\n",
"Chain Object: <itertools.chain object at 0x000001FF1FB1ACA0>\n"
]
},
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6]"
]
},
"execution_count": 217,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = [1, 2, 3]\n",
"b = [4, 5, 6]\n",
"print('a:',a)\n",
"print('b:',b)\n",
"\n",
"from itertools import chain\n",
"\n",
"c = chain(a, b) # joining two lists\n",
"print('\\nChain Object:', c) # object\n",
"list(c)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Decorator"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"A **decorator** is any callable Python object that is used to modify a function or a class. It **takes a function, adds some functionality, and returns** it. Decorators are a very powerful and useful tool in Python since it allows programmers to modify/control the behavior of function or class.\n",
"\n",
"In Decorators, functions are passed as an argument into another function and then called inside the **wrapper function**.\n",
"Decorators are usually called before the definition of a function we want to decorate.\n",
"\n",
"There are two different kinds of decorators in Python: **Function decorators** and **Class decorators**.\n",
"\n",
"When using Multiple Decorators to a single function, the decorators will be applied in the order they’ve been called.\n",
"By recalling that decorator function, we can re-use the decorator.\n"
]
},
{
"cell_type": "code",
"execution_count": 232,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Before calling sqr\n",
"25\n",
"After calling sqr\n"
]
}
],
"source": [
"#Decorators\n",
"def test_decorator(func):\n",
"\n",
" def function_wrapper(x):\n",
" print(\"Before calling \" + func.__name__)\n",
" res = func(x)\n",
" print(res)\n",
" print(\"After calling \" + func.__name__)\n",
"\n",
" return function_wrapper\n",
"\n",
"\n",
"@test_decorator\n",
"def sqr(n):\n",
" return n**2\n",
"\n",
"\n",
"sqr(5)"
]
},
{
"cell_type": "code",
"execution_count": 234,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"['testing', 'multiple', 'decorators']"
]
},
"execution_count": 234,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiple Decorators\n",
"def lowercase_decorator(function):\n",
"\n",
" def wrapper():\n",
" func = function()\n",
" make_lowercase = func.lower()\n",
" return make_lowercase\n",
"\n",
" return wrapper\n",
"\n",
"\n",
"def split_string(function):\n",
"\n",
" def wrapper():\n",
" func = function()\n",
" split_string = func.split()\n",
" return split_string\n",
"\n",
" return wrapper\n",
"\n",
"\n",
"@split_string\n",
"@lowercase_decorator\n",
"def test_func():\n",
" return 'TESTING MULTIPLE DECORATORS'\n",
"\n",
"\n",
"test_func()"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Memoization using Decorators"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**Memoization** is a technique which allows us to optimize a Python function by caching its output based on the parameters we supply to it. Once we memoize a function, it will only compute its output once for each set of parameters we call it with. \n",
"\n",
"Every call after the first will be quickly retrieved from a **cache**.\n",
"\n",
"If we want to speed up the parts in our program that are expensive, memoization can be a great technique to use.\n",
"There are several approaches to Memoization:\n",
"* Using global\n",
"* Using objects\n",
"* Using default parameter\n",
"* Using a Callable Class"
]
},
{
"cell_type": "code",
"execution_count": 235,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6765\n"
]
}
],
"source": [
"#fibonacci series using Memoization through decorators\n",
"def memoization_func(t):\n",
" dict_one = {}\n",
"\n",
" def h(z):\n",
" if z not in dict_one:\n",
" dict_one[z] = t(z)\n",
" return dict_one[z]\n",
"\n",
" return h\n",
"\n",
"\n",
"@memoization_func\n",
"def fib(n):\n",
" if n == 0:\n",
" return 0\n",
" elif n == 1:\n",
" return 1\n",
" else:\n",
" return fib(n - 1) + fib(n - 2)\n",
"\n",
"\n",
"print(fib(20))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Objects and Classes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* The **class** statement creates a class object and gives it a name, as well as creating a new namespace.\n",
"* Variable assignments and methods within the class create class **attributes**. These attributes are accessed by qualifying the name using dot syntax: `ClassName.Attribute`.\n",
"* Class attributes export the state of an object and its associated behavior. These attributes are shared by all instances of a class.\n",
"* Calling a class creates a new **instance** of the class. This is where the multiple copies part comes in.\n",
"* Each instance gets (\"inherits\") the default attributes of its class, while also getting its own namespace. This prevents instance objects from overlapping and confusing the program.\n",
"* Using the term **self** identifies a particular instance, allowing for per-instance attributes. This allows items such as variables to be associated with a particular instance."
]
},
{
"cell_type": "code",
"execution_count": 236,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['__add__',\n",
" '__class__',\n",
" '__class_getitem__',\n",
" '__contains__',\n",
" '__delattr__',\n",
" '__delitem__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__getitem__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__iadd__',\n",
" '__imul__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__iter__',\n",
" '__le__',\n",
" '__len__',\n",
" '__lt__',\n",
" '__mul__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__reversed__',\n",
" '__rmul__',\n",
" '__setattr__',\n",
" '__setitem__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" 'append',\n",
" 'clear',\n",
" 'copy',\n",
" 'count',\n",
" 'extend',\n",
" 'index',\n",
" 'insert',\n",
" 'pop',\n",
" 'remove',\n",
" 'reverse',\n",
" 'sort']"
]
},
"execution_count": 236,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = [1, 2, 3, 4, 5]\n",
"dir(a) # returns the list of all Python's objects classes"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### Encapsulation"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The idea of **encapsulation** is to have methods and variables within the bounds of a given unit. In the case of Python, this unit is called a **class** and the members of a class become locally bound to that class. These members have a defined **scope**, such as **global scope** or **local scope**.\n",
"\n",
"**Attributes** refer to **variables** declared in a class, while **behaviors** are associated with the **methods** in the class.\n",
"\n",
"Encapsulation is also used for hiding data and its internal representation. **Access modifiers** represented by keywords such as **public**, **private** and **protected** are used for information hiding. \n",
"\n",
"The use of *single and double underscore*s for this purpose in Python is a substitute for this practice. For example:"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><b>self method</b> is used to refer to the parameters of the instance of a class</div>"
]
},
{
"cell_type": "code",
"execution_count": 238,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"class Jamwine:\n",
" \n",
" # __init__ is a special method used to create an instance\n",
" def __init__(self):\n",
" # Data Attributes for initializing objects\n",
" self._a = 2. # Protected member ‘a’\n",
" self.__b = 5.2 # Private member ‘b’"
]
},
{
"cell_type": "code",
"execution_count": 239,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<__main__.Jamwine object at 0x000001FF1FB10520>\n"
]
}
],
"source": [
"# Object created for class Jamwine\n",
"jw = Jamwine()\n",
"print(jw)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"self.\\_a is a protected member and can be accessed by the class and its subclasses."
]
},
{
"cell_type": "code",
"execution_count": 240,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.0\n"
]
}
],
"source": [
"# Accessing jw attributes\n",
"print(jw._a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Private members in Python are conventionally used with preceding double underscores: \\_\\_. \n",
"\n",
"self.\\_\\_b is a private member of the class Alpha and can only be accessed from within the class Jamwine."
]
},
{
"cell_type": "code",
"execution_count": 241,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'Jamwine' object has no attribute '__b'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-241-e43198752831>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mjw\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__b\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m: 'Jamwine' object has no attribute '__b'"
]
}
],
"source": [
"print(jw.__b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**jw.\\_a** is accessible while **jw.\\_\\_b** is not accessible directly."
]
},
{
"cell_type": "code",
"execution_count": 242,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"['_Jamwine__b',\n",
" '__class__',\n",
" '__delattr__',\n",
" '__dict__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__le__',\n",
" '__lt__',\n",
" '__module__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" '__weakref__',\n",
" '_a']"
]
},
"execution_count": 242,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dir(jw)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Within `jw` object: **\\_a** is available, however **\\_\\_b** is not available directly, it can be accessed from class as **\\_Jamwine\\_\\_b**."
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"It should be noted that these private and protected members can still be accessed from outside of the class by using public methods to access them or by a practice known as **name mangling**. Name mangling is the use of two leading underscores and one trailing underscore, for example:"
]
},
{
"cell_type": "code",
"execution_count": 245,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"5.2"
]
},
"execution_count": 245,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Syntax: object._Class__attribute\n",
"jw._Jamwine__b"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### Special Methods"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\"><li><b>__init__</b><li><b>__str__</b><li><b>__name__</b></div>\n",
"\n",
"> **\\_\\_init\\_\\_** is a special method used to create an instance\n",
"\n",
"\n",
"> **\\_\\_str\\_\\_** is a special method used to return a string representation of an object\n",
"\n",
"\n",
"> Before executing code in a module (file), Python will define a few special variables\n",
">* If the Python interpreter is running the file as the main program, it sets the special **\\_\\_name\\_\\_** variable to have a value `__main__`\n",
">* If the file is being imported from another module, **\\_\\_name\\_\\_** will be set to that **module’s (file’s) name**\n",
"\n",
"> To direct the Python interpreter when it first reads a file, add the following conditional (to the bottom) of our script:\n",
">\n",
">`if __name__ == \"__main__\":\n",
"> main()`\n",
"> * This will run the main function, if the file is loaded as the main program"
]
},
{
"cell_type": "code",
"execution_count": 240,
"metadata": {
"hidden": true,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Name is: James\n",
"Age is: 24\n",
"City is: Dubai\n",
"\n",
"b.name: Jack\n",
"c.city: Delhi\n",
"d: | Jim | 21 | California |\n",
"\n",
"__main__\n"
]
}
],
"source": [
"class Student():\n",
"\n",
" def __init__(self, name, age, city):\n",
" self.name = name\n",
" self.age = age\n",
" self.city = city\n",
"\n",
" def details(self):\n",
" print(\"Name is: \", self.name)\n",
" print(\"Age is: \", self.age)\n",
" print(\"City is: \", self.city)\n",
"\n",
" def __str__(self):\n",
" return \"| %s | %s | %s |\" % (self.name, self.age, self.city)\n",
"\n",
"\n",
"a = Student(\"James\", 24, \"Dubai\")\n",
"b = Student(\"Jack\", 23, \"New York\")\n",
"c = Student(\"Julia\", 24, \"Delhi\")\n",
"d = Student(\"Jim\", 21, \"California\")\n",
"\n",
"a.details()\n",
"print(\"\\nb.name:\", b.name)\n",
"print(\"c.city:\", c.city)\n",
"print(\"d:\", d)\n",
"\n",
"# Special method __name__ evaluates to '__main__' or the actual module name, depending on how the enclosing module is being used\n",
"print()\n",
"print(__name__)"
]
},
{
"cell_type": "code",
"execution_count": 256,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"<__main__.M at 0x1ff1f615dc0>"
]
},
"execution_count": 256,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class M():\n",
"\n",
" def abc(self):\n",
" print('Public method!')\n",
" \n",
" def _xyz(self):\n",
" print(\"Protected method!\")\n",
"\n",
" def __pqr(self): \n",
" print(\"Private method!\")\n",
"\n",
"m = M()\n",
"m"
]
},
{
"cell_type": "code",
"execution_count": 257,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Public method!\n"
]
}
],
"source": [
"m.abc()"
]
},
{
"cell_type": "code",
"execution_count": 258,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Protected method\n"
]
}
],
"source": [
"m._xyz()"
]
},
{
"cell_type": "code",
"execution_count": 259,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'M' object has no attribute '__pqr'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-259-7d1c3ff30916>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mm\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__pqr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m: 'M' object has no attribute '__pqr'"
]
}
],
"source": [
"m.__pqr() # cannot be accessed directly"
]
},
{
"cell_type": "code",
"execution_count": 261,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Private method\n"
]
}
],
"source": [
"m._M__pqr() # name mangling"
]
},
{
"cell_type": "code",
"execution_count": 271,
"metadata": {
"hidden": true,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Public method!\n",
"Public method!\n",
"Protected method\n",
"Private method\n"
]
}
],
"source": [
"# Example of Inheritance\n",
"\n",
"class N(M):\n",
"\n",
" def mno(self):\n",
" print('Public method!')\n",
"\n",
"\n",
"n = N()\n",
"n.mno()\n",
"\n",
"# Inherited from M()\n",
"n.abc()\n",
"n._xyz()\n",
"n._M__pqr()"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### Inheritance"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"As the structure of inheritance gets more complicated, Python adheres to something called the **Method Resolution Order (MRO)** that determines the flow of execution. MRO is a set of rules, or an algorithm, that Python uses to implement **monotonicity**, which refers to the order or sequence in which the interpreter will look for the variables and functions to implement. This also helps in determining the scope of the different members of the given class."
]
},
{
"cell_type": "code",
"execution_count": 274,
"metadata": {
"hidden": true,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Jon.gender: male\n",
"Jon.eyes: 2\n",
"\n",
"Jon.nose: 1\n",
"\n",
"Jon.get_legs(): 2\n",
"Jon.get_legs: <bound method Human.get_legs of <__main__.man object at 0x000001FF1F6FF2B0>>\n",
"Jon.get_ears: 2\n",
"\n",
"Jeny.gender: female\n",
"Jeny.hands: 2\n"
]
}
],
"source": [
"class Human(): # defining class Human\n",
" # attributes\n",
" legs = 2\n",
" ears = 2\n",
" hands = 2\n",
" eyes = 2\n",
"\n",
" # function (callable)\n",
" def get_legs(self):\n",
" return self.legs\n",
"\n",
" @property\n",
" def get_ears(self): # property (not a function, hence not callable)\n",
" return self.ears\n",
"\n",
"\n",
"# defining class man, Human is inherited by defining inside parenthesis\n",
"class man(Human):\n",
" gender = 'male'\n",
"\n",
"\n",
"# defining class woman, Human is the parent class\n",
"class woman(Human):\n",
" gender = 'female'\n",
"\n",
"\n",
"# object created\n",
"Jon = man()\n",
"print(\"Jon.gender:\", Jon.gender)\n",
"print(\"Jon.eyes:\", Jon.eyes)\n",
"\n",
"Jon.nose = 1\n",
"print(\"\\nJon.nose:\", Jon.nose)\n",
"\n",
"# parenthesis is required when we are calling the function\n",
"print(\"\\nJon.get_legs():\", Jon.get_legs())\n",
"\n",
"# parenthesis is omitted, bound method message appears depicting the function\n",
"print(\"Jon.get_legs:\", Jon.get_legs)\n",
"\n",
"# although parenthesis is omitted, bound method message would not appear as '@property' is defined above the method which makes it a property\n",
"print(\"Jon.get_ears:\", Jon.get_ears)\n",
"\n",
"Jeny = woman()\n",
"print(\"\\nJeny.gender:\", Jeny.gender)\n",
"print(\"Jeny.hands:\", Jeny.hands)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### mro()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**mro()** stands for **Method Resolution Order**. It returns a **list** of types the class is derived from, in the order they are searched for methods.\n",
"\n",
"**mro()** and **\\_\\_mro\\_\\_** work only on new style classes. Python normally uses a **depth-first order** when searching inheriting classes, but when two classes inherit from the same class, Python removes the first mention of that class from the MRO."
]
},
{
"cell_type": "code",
"execution_count": 317,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"# Example for Inheritance\n",
"\n",
"class A:\n",
" def a(self):\n",
" return \"Function inside A\"\n",
"\n",
"class B:\n",
" def a(self):\n",
" return \"Function inside B\""
]
},
{
"cell_type": "code",
"execution_count": 318,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Function inside A\n"
]
}
],
"source": [
"# Class C inherits from classes A and B\n",
"class C(A, B):\n",
" pass\n",
"\n",
"c = C()\n",
"print(c.a()) # a() is called from class A as A is inherited first"
]
},
{
"cell_type": "code",
"execution_count": 361,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[__main__.C, __main__.A, __main__.B, object]"
]
},
"execution_count": 361,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"C.mro()"
]
},
{
"cell_type": "code",
"execution_count": 321,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Function inside B\n"
]
}
],
"source": [
"# Class D inherits from classes B and A\n",
"class D(B, A):\n",
" pass\n",
"\n",
"d = D()\n",
"print(d.a()) # a() is called from class B as B is inherited first"
]
},
{
"cell_type": "code",
"execution_count": 364,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"(__main__.D, __main__.B, __main__.A, object)"
]
},
"execution_count": 364,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"D.__mro__"
]
},
{
"cell_type": "code",
"execution_count": 322,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Function inside A\n"
]
}
],
"source": [
"# Class E inherits from classes C and B\n",
"class E(C, B):\n",
" pass\n",
"\n",
"e = E()\n",
"print(e.a()) # a() is called from class C, which again was referred from class A"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Since there was no value present inside `class C` either, the function call above would go to `A`. That is because `class C` will point to `class A`as having higher precedence while inheriting."
]
},
{
"cell_type": "code",
"execution_count": 358,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"[__main__.E, __main__.C, __main__.A, __main__.B, object]"
]
},
"execution_count": 358,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"E.mro()"
]
},
{
"cell_type": "code",
"execution_count": 329,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "TypeError",
"evalue": "Cannot create a consistent method resolution\norder (MRO) for bases B, C",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-329-2737dc05c68f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Class F inherits from classes B and C\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;32mclass\u001b[0m \u001b[0mF\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mB\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mC\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;32mpass\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mF\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: Cannot create a consistent method resolution\norder (MRO) for bases B, C"
]
}
],
"source": [
"# Class F inherits from classes B and C\n",
"class F(B, C):\n",
" pass\n",
"\n",
"f = F()\n",
"print(f.a()) # this throws an error"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"`Class C` is its immediate superclass, but since this is **multiple inheritance**, the rules are more complicated and it also has to check the classes passed to it for precedence.\n",
"\n",
"In this particular case, `class F` is unable to resolve the order that should be followed, while resolving the value for the variable in cases where the variable is not present in the class of the given object.\n",
"\n",
"It results in a **TypeError** because it's unable to create **method resolution order (MRO)**. MRO is Python’s way of resolving the order of precedence of classes while dealing with inheritance."
]
},
{
"cell_type": "code",
"execution_count": 359,
"metadata": {
"hidden": true
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'F' 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-359-1e151cdffe94>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mF\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmro\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mNameError\u001b[0m: name 'F' is not defined"
]
}
],
"source": [
"F.mro() # throws error because class F was not defined due to TypeError"
]
},
{
"cell_type": "code",
"execution_count": 357,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Function inside B\n"
]
}
],
"source": [
"# Class G inherits from classes D, B and A\n",
"class G(D, B, A):\n",
" pass\n",
"\n",
"g = G()\n",
"print(g.a()) # the precedence order of inheritance (D, B, A) is appropriate: a() will called from class B"
]
},
{
"cell_type": "code",
"execution_count": 365,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"(__main__.G, __main__.D, __main__.B, __main__.A, object)"
]
},
"execution_count": 365,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"G.__mro__"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"More OOPS Examples: https://github.com/udacity/DSND_Term2/tree/master/lessons/ObjectOrientedProgramming/JupyterNotebooks\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### issubclass()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"Two classes are passed as arguments to this function and a Boolean result is returned"
]
},
{
"cell_type": "code",
"execution_count": 284,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"issubclass(man, Human): True\n",
"issubclass(woman, Human): True\n",
"issubclass(Human, woman): False\n",
"issubclass(Human, man): False\n",
"issubclass(man, man): True\n",
"issubclass(man, woman): False\n"
]
}
],
"source": [
"print(\"issubclass(man, Human): \", issubclass(man, Human))\n",
"print(\"issubclass(woman, Human): \", issubclass(woman, Human))\n",
"print(\"issubclass(Human, woman): \", issubclass(Human, woman))\n",
"print(\"issubclass(Human, man): \", issubclass(Human, man))\n",
"print(\"issubclass(man, man): \", issubclass(man, man))\n",
"print(\"issubclass(man, woman): \", issubclass(man, woman))"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**isinstance()** determines if some object is an instance of some class"
]
},
{
"cell_type": "code",
"execution_count": 289,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"isinstance(Jon, man): True\n",
"isinstance(Jon, woman): False\n",
"\n",
"isinstance(Jeny, man): False\n",
"isinstance(Jeny, woman): True\n",
"\n",
"isinstance(Jon, Human): True\n",
"isinstance(Jeny, Human): True\n"
]
}
],
"source": [
"print(\"isinstance(Jon, man): \", isinstance(Jon, man))\n",
"print(\"isinstance(Jon, woman): \", isinstance(Jon, woman))\n",
"\n",
"print(\"\\nisinstance(Jeny, man): \", isinstance(Jeny, man))\n",
"print(\"isinstance(Jeny, woman): \", isinstance(Jeny, woman))\n",
"\n",
"print(\"\\nisinstance(Jon, Human): \", isinstance(Jon, Human))\n",
"print(\"isinstance(Jeny, Human): \", isinstance(Jeny, Human))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### super()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"The **super()** is a built-in function that can be called inside the derived class and gives access to the methods and variables of the parent classes or sibling classes. **Sibling classes** are the classes that share the same parent class. \n",
"\n",
"When we call the super() function, we get an object that represents the parent class in return."
]
},
{
"cell_type": "code",
"execution_count": 291,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"class Fruit():\n",
" def __init__(self, fruit):\n",
" print('Fruit type: ', fruit)\n",
"\n",
"class FruitFlavourWithoutSuper(Fruit):\n",
" def __init__(self):\n",
" print('Apple is sweet')\n",
" \n",
"class FruitFlavourWithSuper(Fruit):\n",
" def __init__(self):\n",
" super().__init__('Orange')\n",
" print('Orange is sweet')"
]
},
{
"cell_type": "code",
"execution_count": 292,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Apple is sweet\n"
]
}
],
"source": [
"apple = FruitFlavourWithoutSuper()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"When we initialize the child class, we don’t initialize the base class with it. super() function helps us to achieve this and add the initialization of base class with the derived class."
]
},
{
"cell_type": "code",
"execution_count": 293,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Fruit type: Orange\n",
"Orange is sweet\n"
]
}
],
"source": [
"orange = FruitFlavourWithSuper()"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### Polymorphism"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**Polymorphism** refers to something that can have *many forms*, (in this case - a given **object**). Everything in Python is inherently an object, it can be an operator, method or any object of some class. For example:\n"
]
},
{
"cell_type": "code",
"execution_count": 247,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"xyzxyzxyzxyzxyz 15 [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]\n"
]
}
],
"source": [
"a = \"xyz\"\n",
"new_a = a * 5\n",
"\n",
"b = 3\n",
"new_b = b * 5\n",
"\n",
"c = [1,2,3]\n",
"new_c = c * 5\n",
"\n",
"print(new_a, new_b, new_c)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"In this example, the same operation is performed on a string, integer and a list. And the result behaves differently in all three cases."
]
},
{
"cell_type": "code",
"execution_count": 248,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"xyz xyzxyzxyz\n",
"3 9\n",
"[1, 2, 3] [1, 2, 3, 1, 2, 3, 1, 2, 3]\n"
]
}
],
"source": [
"def thrice(obj):\n",
" return obj*3\n",
"\n",
"print(a, thrice(a))\n",
"print(b, thrice(b))\n",
"print(c, thrice(c))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"### Abstaction"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**Abstraction** can be seen both as a means for hiding important information as well as unnecessary information in a block of code. The core of abstraction in Python is the implementation of something called `abstract classes and methods`, which can be implemented by inheriting from something called the **abc module**. \n",
"\n",
"**abc** here stands for **abstract base class**, and its simplest implementation can be done by first importing it and using it as a parent class which is imported in some class that has to be abstract."
]
},
{
"cell_type": "code",
"execution_count": 304,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"from abc import ABC, abstractmethod\n",
"\n",
"# Class Bank\n",
"class Bank(ABC):\n",
" \n",
" def __init__(self, bal):\n",
" self.bal = bal\n",
" \n",
" # Define a function basicinfo()\n",
" def basicinfo(self):\n",
" print(\"Banking details\")\n",
"\n",
" # Define an abstract function withdraw()\n",
" @abstractmethod\n",
" def withdraw(self):\n",
" pass\n",
" \n",
"# Class Swiss\n",
"class Swiss(Bank):\n",
" \n",
" def __init__(self, bal):\n",
" super().__init__(bal)\n",
" \n",
" # Define a function basicinfo()\n",
" def basicinfo(self):\n",
" print(\"This is the Swiss Bank\")\n",
"\n",
" # Define a function withdraw()\n",
" def withdraw(self, bal, amount):\n",
" bal = bal - amount\n",
" print(\"Withdraw amount: \", amount)\n",
" print(\"New balance: \", bal)"
]
},
{
"cell_type": "code",
"execution_count": 305,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is the Swiss Bank\n",
"Withdraw amount: 20\n",
"New balance: 980\n"
]
}
],
"source": [
"# Driver Code\n",
"s = Swiss(1000)\n",
"s.basicinfo()\n",
"s.withdraw(1000, 20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `@property`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A **property** decorator is a way to create methods that can be accessed like **attribute**s. It allows us to define methods that look like regular instance variables, but which execute custom code behind the scenes when accessed, set, or deleted. This can be useful in situations where we want to add additional logic or validation to the way an attribute is accessed or manipulated."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Properties** are found in other languages as **getters** and **setters**. As those terms indicate, they are used to get data and set (modify) data. For example:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
" def __init__(self, width, height):\n",
" self._width = width\n",
" self._height = height\n",
" \n",
" @property\n",
" def width(self):\n",
" return self._width\n",
"\n",
" @width.setter\n",
" def width(self, value):\n",
" if value <= 0:\n",
" raise ValueError(\"Width must be positive\")\n",
" else:\n",
" self._width = value\n",
"\n",
" @property\n",
" def height(self):\n",
" return self._height\n",
" \n",
" @height.setter\n",
" def height(self, value):\n",
" if value <= 0:\n",
" raise ValueError(\"Height must be positive\")\n",
" else:\n",
" self._height = value\n",
"\n",
" def area(self):\n",
" return self.width * self.height"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above code, we have defined a `Rectangle` class with `width` and `height` attributes that are decorated with the **@property** decorator. We have also defined setter methods for each attribute using the `@width.setter` and `@height.setter` decorators.\n",
"\n",
"When we set the `width` or `height` attribute, the corresponding setter method is automatically called, which checks that the new value is positive. If it is not, a `ValueError` is raised. When we get the `width` or `height` attribute, the corresponding getter method is automatically called, which simply returns the stored value.\n",
"\n",
"Now we can create a `Rectangle` object and set its `width` and `height` attributes, and the setter methods will automatically be called to validate the input:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12\n",
"20\n"
]
},
{
"ename": "ValueError",
"evalue": "Width must be positive",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"Input \u001b[1;32mIn [10]\u001b[0m, in \u001b[0;36m<cell line: 5>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 3\u001b[0m r\u001b[38;5;241m.\u001b[39mwidth \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m5\u001b[39m \u001b[38;5;66;03m# Setter method called\u001b[39;00m\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(r\u001b[38;5;241m.\u001b[39marea()) \u001b[38;5;66;03m# Output: 20\u001b[39;00m\n\u001b[1;32m----> 5\u001b[0m \u001b[43mr\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwidth\u001b[49m \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m2\u001b[39m\n",
"Input \u001b[1;32mIn [9]\u001b[0m, in \u001b[0;36mRectangle.width\u001b[1;34m(self, value)\u001b[0m\n\u001b[0;32m 10\u001b[0m \u001b[38;5;129m@width\u001b[39m\u001b[38;5;241m.\u001b[39msetter\n\u001b[0;32m 11\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mwidth\u001b[39m(\u001b[38;5;28mself\u001b[39m, value):\n\u001b[0;32m 12\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m value \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m---> 13\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mWidth must be positive\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 14\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 15\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_width \u001b[38;5;241m=\u001b[39m value\n",
"\u001b[1;31mValueError\u001b[0m: Width must be positive"
]
}
],
"source": [
"r = Rectangle(3, 4)\n",
"print(r.area()) # Output: 12\n",
"r.width = 5 # Setter method called\n",
"print(r.area()) # Output: 20\n",
"r.width = -2 # ValueError raised by setter method"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Accessing the height attribute directly\n",
"r.height"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `@staticmethod`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **@staticmethod** decorator is used to define a **static** method inside a class. A static method is a method that belongs to the class rather than an instance of the class. This means that it can be called on the class itself, rather than on an instance of the class. For example:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"class MathUtils:\n",
" @staticmethod\n",
" def add_numbers(a, b):\n",
" return a + b\n",
" \n",
" @staticmethod\n",
" def multiply_numbers(a, b):\n",
" return a * b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To use these static methods, we can call them on the class itself, rather than on an instance of the class:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n",
"12\n"
]
}
],
"source": [
"print(MathUtils.add_numbers(3, 4)) # Output: 7\n",
"print(MathUtils.multiply_numbers(3, 4)) # Output: 12"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above code, we call the add_numbers and multiply_numbers static methods on the MathUtils class directly, passing in the necessary arguments.\n",
"\n",
"Note that static methods do not have access to instance-specific data or methods, as they are not bound to any particular instance of the class. They can only access class-level data and methods."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `@classmethod`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **@classmethod** decorator is used to define a class method inside a class. A class method is a method that belongs to the class itself, rather than an instance of the class. It receives the class itself as the first argument instead of an instance of the class. For example:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"class Person:\n",
" num_people = 0\n",
" \n",
" def __init__(self, name):\n",
" self.name = name\n",
" Person.num_people += 1\n",
" \n",
" @classmethod\n",
" def get_num_people(cls):\n",
" return cls.num_people"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above code, we have defined a `Person` class with a class-level variable `num_people` that keeps track of the number of Person objects that have been created. We have also defined a class method `get_num_people` using the `@classmethod` decorator. This method takes the class itself as its first argument, conventionally named **cls**, and returns the value of the `num_people` class-level variable.\n",
"\n",
"To use the `get_num_people` class method, we can call it on the class itself, rather than on an instance of the class:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"p1 = Person(\"Alice\")\n",
"p2 = Person(\"Bob\")\n",
"print(Person.get_num_people()) # Output: 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above code, we create two Person objects `p1` and `p2`, and then call the `get_num_people` class method on the `Person` class itself to get the number of Person objects that have been created.\n",
"\n",
"Note that class methods have access to the class-level data and methods, but not to instance-specific data or methods, as they are not bound to any particular instance of the class."
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Modules, libraries and packages"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**Modules** and **packages** can easily be confused because of their similarities, but there are a few differences. **Modules are similar to files**, while **packages are like directories** that contain different files. Modules are generally written in a single file, but that's more of a practice than a definition. \n",
"\n",
"Packages are essentially a type of module. Any module that contains the **\\_\\_path\\_\\_** definition is a **package**. Packages, when viewed as a directory, can contain sub-packages and other modules. Modules, on the other hand, can contain classes, functions and data members just like any other Python file. \n",
"\n",
"**Library** is a term that's used interchangeably with imported packages. But in general practice, it refers to a **collection of packages**.\n",
"\n",
"**Third-party package** add-ons of Python can be found in the **Python Package Index**. To install packages that aren't a part of the standard library programmers use **pip (package installer for Python)**. It is installed with Python by default. For example: `pip install \"SomeProject\"`"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"### Subpackages"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"If we are to assume that packages are similar to a folder or directory in our operating system, then the **package can also contain other directories**. Packages, both built-in and user-defined, can contain other folders within them that need to be accessed. These are named **sub-packages**. We use `dot-notation` to access sub-packages within a package during `import`. \n",
"\n",
"For example, in a package such as `matplotlib`, the contents that are used most commonly are present inside the subpackage `pyplot`. Pyplot eventually may consist of various functions and attributes. The code for importing a sub-package is:\n",
"`import matplotlib.pyplot`. To make it even more convenient, it is often imported using an **alias**.\n",
"`import matplotlib.pyplot as plt`"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true
},
"source": [
"## Miscellaneous"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### \\*args & \\*\\*kwargs"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**\\*args** and **\\*\\*kwargs** are used in function definitions that allows to pass an `unspecified number of arguments` to a function.\n",
"\n",
"\\*args is used to send a `non-keyworded variable length` argument list to the function.\n",
"\n",
"\\*\\*kwargs allows to pass `keyworded variable length` of arguments to a function.\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 143,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"def get_quantity(apples, bananas, *args, **kwargs):\n",
" print('Number of apples: ',apples)\n",
" print('Number of bananas: ', bananas)\n",
" result = apples + bananas\n",
" \n",
" # *args is the list of extra arguments\n",
" if args:\n",
" other_fruits = 0\n",
" print('\\nOther fruits (args): ', *args) \n",
" other_fruits = sum([arg for arg in args])\n",
" print('Total other fruits: ', other_fruits)\n",
" result += other_fruits\n",
" \n",
" # *kwargs is the dictionary of extra arguments\n",
" if kwargs:\n",
" extra_fruits = 0\n",
" for k, v in kwargs.items():\n",
" print(f'Number of {k}: {v}')\n",
" extra_fruits += v\n",
" print('Total extra fruits: ', extra_fruits)\n",
" result += extra_fruits\n",
" \n",
" print(\"\\nTotal number of fruits: \", result)"
]
},
{
"cell_type": "code",
"execution_count": 144,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of apples: 2\n",
"Number of bananas: 3\n",
"\n",
"Total number of fruits: 5\n"
]
}
],
"source": [
"get_quantity(2, 3)"
]
},
{
"cell_type": "code",
"execution_count": 145,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of apples: 2\n",
"Number of bananas: 3\n",
"\n",
"Other fruits (args): 4 5\n",
"Total other fruits: 9\n",
"\n",
"Total number of fruits: 14\n"
]
}
],
"source": [
"get_quantity(2, 3, 4, 5)"
]
},
{
"cell_type": "code",
"execution_count": 146,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of apples: 2\n",
"Number of bananas: 3\n",
"Number of grapes: 4\n",
"Number of oranges: 5\n",
"Total extra fruits: 9\n",
"\n",
"Total number of fruits: 14\n"
]
}
],
"source": [
"extra_fruits = {'grapes': 4, 'oranges': 5}\n",
"get_quantity(2, 3, **extra_fruits)"
]
},
{
"cell_type": "code",
"execution_count": 147,
"metadata": {
"hidden": true,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of apples: 2\n",
"Number of bananas: 3\n",
"\n",
"Other fruits (args): 7 4 1\n",
"Total other fruits: 12\n",
"Number of grapes: 4\n",
"Number of oranges: 5\n",
"Number of peaches: 2\n",
"Total extra fruits: 11\n",
"\n",
"Total number of fruits: 28\n"
]
}
],
"source": [
"other_fruits = (7, 4, 1)\n",
"extra_fruits = {'grapes': 4, 'oranges': 5, 'peaches': 2}\n",
"\n",
"get_quantity(2, 3, *other_fruits, **extra_fruits)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### `_` in Python"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a: 12\n",
"d: [11, True]\n"
]
}
],
"source": [
"a, _, _, d = (\"12\", \"Repeat\", 20, [11, True])\n",
"print(\"a:\", a)\n",
"print(\"d:\", d)"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {
"hidden": true
},
"outputs": [
{
"data": {
"text/plain": [
"20"
]
},
"execution_count": 91,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# _ storing invaluable information\n",
"_"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"<div class=\"alert alert-info\">\n",
"<li><b>_</b> or <b>underscore</b> is a special variable in Python, which stores the most recent output value of the interpreter.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n",
"24\n"
]
}
],
"source": [
"# Restores previous calculation\n",
"print(_)\n",
"\n",
"# _ can be used with other expressions and operators as well\n",
"print(_ + 4)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### XOR `^`"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0^0: 0\n",
"0^1: 1\n",
"1^0: 1\n",
"1^1: 0\n"
]
}
],
"source": [
"print('0^0:',0^0)\n",
"print('0^1:',0^1)\n",
"print('1^0:',1^0)\n",
"print('1^1:',1^1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### ord()"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**ord()** is used to convert a character to its ASCII value"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ASCII value of a:97\n",
"ASCII value of b:98\n",
"ASCII value of c:99\n",
"ASCII value of d:100\n",
"ASCII value of e:101\n",
"ASCII value of f:102\n",
"ASCII value of g:103\n",
"ASCII value of h:104\n",
"ASCII value of i:105\n",
"ASCII value of j:106\n",
"ASCII value of k:107\n",
"ASCII value of l:108\n",
"ASCII value of m:109\n",
"ASCII value of n:110\n",
"ASCII value of o:111\n",
"ASCII value of p:112\n",
"ASCII value of q:113\n",
"ASCII value of r:114\n",
"ASCII value of s:115\n",
"ASCII value of t:116\n",
"ASCII value of u:117\n",
"ASCII value of v:118\n",
"ASCII value of w:119\n",
"ASCII value of x:120\n",
"ASCII value of y:121\n",
"ASCII value of z:122\n",
"ASCII value of A:65\n",
"ASCII value of B:66\n",
"ASCII value of C:67\n",
"ASCII value of D:68\n",
"ASCII value of E:69\n",
"ASCII value of F:70\n",
"ASCII value of G:71\n",
"ASCII value of H:72\n",
"ASCII value of I:73\n",
"ASCII value of J:74\n",
"ASCII value of K:75\n",
"ASCII value of L:76\n",
"ASCII value of M:77\n",
"ASCII value of N:78\n",
"ASCII value of O:79\n",
"ASCII value of P:80\n",
"ASCII value of Q:81\n",
"ASCII value of R:82\n",
"ASCII value of S:83\n",
"ASCII value of T:84\n",
"ASCII value of U:85\n",
"ASCII value of V:86\n",
"ASCII value of W:87\n",
"ASCII value of X:88\n",
"ASCII value of Y:89\n",
"ASCII value of Z:90\n"
]
}
],
"source": [
"import string\n",
"for ch in string.ascii_letters:\n",
" print(f\"ASCII value of {ch}:{ord(ch)}\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ASCII value of !:33\n",
"ASCII value of \":34\n",
"ASCII value of #:35\n",
"ASCII value of $:36\n",
"ASCII value of %:37\n",
"ASCII value of &:38\n",
"ASCII value of ':39\n",
"ASCII value of (:40\n",
"ASCII value of ):41\n",
"ASCII value of *:42\n",
"ASCII value of +:43\n",
"ASCII value of ,:44\n",
"ASCII value of -:45\n",
"ASCII value of .:46\n",
"ASCII value of /:47\n",
"ASCII value of ::58\n",
"ASCII value of ;:59\n",
"ASCII value of <:60\n",
"ASCII value of =:61\n",
"ASCII value of >:62\n",
"ASCII value of ?:63\n",
"ASCII value of @:64\n",
"ASCII value of [:91\n",
"ASCII value of \\:92\n",
"ASCII value of ]:93\n",
"ASCII value of ^:94\n",
"ASCII value of _:95\n",
"ASCII value of `:96\n",
"ASCII value of {:123\n",
"ASCII value of |:124\n",
"ASCII value of }:125\n",
"ASCII value of ~:126\n"
]
}
],
"source": [
"import string\n",
"for ch in string.punctuation:\n",
" print(f\"ASCII value of {ch}:{ord(ch)}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Color Text in Python"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[34mSome Colored text\u001b[0m\n"
]
}
],
"source": [
"from termcolor import colored\n",
"print(colored(\"Some Colored text\",\"blue\"))"
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Enum in Python"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"JANUARY\n",
"2\n"
]
}
],
"source": [
"from enum import Enum\n",
"\n",
"class Month(Enum):\n",
" JANUARY = 1\n",
" FEBRUARY = 2\n",
" MARCH = 3\n",
" \n",
"print(Month.JANUARY.name)\n",
"print(Month.FE`BRUARY.value)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"### nonlocal & global"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**nonlocal** and **global** are keywords used to declare variables that are defined outside of the current function scope.\n",
"\n",
"* The **nonlocal** keyword allows a nested function to modify a variable that is defined in its enclosing function but not in the global scope.\n",
"\n",
"* The **global** keyword allows a function to access and modify a variable that is defined in the global scope."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n"
]
}
],
"source": [
"# nonlocal Example\n",
"def outer():\n",
" x = 10\n",
" def inner():\n",
" nonlocal x\n",
" x = 20\n",
" inner()\n",
" print(x)\n",
"\n",
"outer()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example, `x` is defined in the `outer()`, and the `inner()` modifies the value of `x` using the **nonlocal** keyword. When the `outer()` is called, it prints the updated value of `x`, which is `20`."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n"
]
}
],
"source": [
"# global Example\n",
"x = 10\n",
"\n",
"def my_function():\n",
" global x\n",
" x = 20\n",
"\n",
"my_function()\n",
"print(x)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example, `x` is defined in the global scope, and the `my_function()` modifies the value of `x` using the **global** keyword. When the `my_function()` is called, it updates the value of `x` to `20`, and when `print(x)` is called, it outputs the updated value of `x`.\n",
"\n",
"Note: It's generally considered a good practice to avoid using the **global** keyword whenever possible because it can make the code harder to understand and maintain."
]
},
{
"cell_type": "markdown",
"metadata": {
"heading_collapsed": true,
"hidden": true
},
"source": [
"### Python DeBugger (PDB)"
]
},
{
"cell_type": "markdown",
"metadata": {
"hidden": true
},
"source": [
"**PDB** is a standard command-line debugger to find errors in our code. It includes features to let us pause our program, look at the values of variables, and watch program execution step-by-step, so we can understand what our program actually does and find bugs in the logic.\n",
"* PDB's **where** command shows the current call stack\n",
"* PDB's **next** command lets execution continue to the next line of code\n",
"* PDB's **continue** command lets program execution continue indefinitely, or until it is stopped with control-c\n",
"* PDB's **list** command shows the source code at the current location\n",
"* PDB's **return** command resumes execution until the end of the current execution"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"# Used for detecting error in code (for debugging purposes)\n",
"import pdb\n",
"\n",
"x = [3, 1, 2]\n",
"y = 6\n",
"z = 7\n",
"\n",
"result = y + z\n",
"print(result)\n",
"\n",
"# Set a trace using Python Debugger\n",
"pdb.set_trace()\n",
"\n",
"result2 = y + x # Error Here\n",
"print(result2)"
]
}
],
"metadata": {
"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.9.7"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {
"height": "calc(100% - 180px)",
"left": "10px",
"top": "150px",
"width": "341px"
},
"toc_section_display": true,
"toc_window_display": true
},
"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
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment