<jupyter_start><jupyter_text>Python IntroductionPython is a widely used high-level programming language for general-purpose programming, created by <NAME> and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly braces or keywords), and a syntax which allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable  writing clear programs on both a small and large scale.Python features a dynamic type system and automatic memory management and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library.Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation. HistoryPython was conceived in the late 1980s, and its implementation began in December 1989 by <NAME> at Centrum Wiskunde & Informatica (CWI) in the Netherlands as a successor to the ABC language (itself inspired by SETL) capable of exception handling and interfacing with the operating system Amoeba. Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, benevolent dictator for life (BDFL).About the origin of Python, Van Rossum wrote in 1996: `Over six years ago, in December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus).` Python 2.0 was released on 16 October 2000 and had many major new features, including a cycle-detecting garbage collector and support for Unicode. With this release the development process was changed and became more transparent and community-backed.Python 3.0 (which early in its development was commonly referred to as Python 3000 or py3k), a major, backwards-incompatible release, was released on 3 December 2008 after a long period of testing. Many of its major features have been backported to the backwards-compatible Python 2.6.x and 2.7.x version series.The End Of Life date (EOL, sunset date) for Python 2.7 was initially set at 2015, then postponed to 2020 out of concern that a large body of existing code cannot easily be forward-ported to Python 3. In January 2017 Google announced work on a Python 2.7 to Go transcompiler, which The Register speculated was in response to Python 2.7's planned end-of-life but Google cited performance under concurrent workloads as their only motivation.https://en.wikipedia.org/wiki/Python_(programming_language)  The Zen of Python- Beautiful is better than ugly.- Explicit is better than implicit.- Simple is better than complex.- Complex is better than complicated.- Flat is better than nested.- Sparse is better than dense.- Readability counts.- Special cases aren't special enough to break the rules.- Although practicality beats purity.- Errors should never pass silently.- Unless explicitly silenced.- In the face of ambiguity, refuse the temptation to guess.- There should be one-- and preferably only one --obvious way to do it.- Although that way may not be obvious at first unless you're Dutch.- Now is better than never.- Although never is often better than *right* now.- If the implementation is hard to explain, it's a bad idea.- If the implementation is easy to explain, it may be a good idea.- Namespaces are one honking great idea -- let's do more of those!https://www.python.org/dev/peps/pep-0020/  Installing Python3 On Mac Installing `brew````bash$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"  /dev/null``` Using `brew` installing Python3 locally```bash$ brew  install python3``` To find the path for `python3````bash$ which python3/usr/local/bin/python3``` On WindowsSorry, can't say much as I am not a windows user.https://docs.python.org/3/using/windows.html  On linux `pip``pip` is a package management system used to install and manage software packages written in `Python`. Many packages can be found in the `Python Package Index (PyPI)`.https://en.wikipedia.org/wiki/Pip_(package_manager)https://pypi.python.org/pypi/pip Ubuntu`Ubuntu 16.04` ships with both `Python3` and `Python2`. By default `pip` for Python2 is installed but not for Python3.Now we need to install `pip3` for `Python3`. ```bashsudo apt-get install -y python3-pip``` Installing `Python3` `virtualenv````bashsudo pip install virtualenv``` If required upgrade `pip````bashsudo pip install --upgrade pip``` `Python3 virtualenv````bashmkdir sample_project_python3cd sample_project_python3virtualenv .venv``` `Python2 virtualenv````bashmkdir sample_project_python2cd sample_project_python2virtualenv -p /usr/bin/python2 .venv``` CentOS / Amazon AMI```bashsudo -i yum install python36 python36-pippip-3.6 install virtualenvpip install --upgrade pip``` Python virtualenv installation```bash$ pip3 install virtualenv``` Advantages of virtualenv- Isolated Python runtime environments without modifying the root or system python installation.- Eash while deploying several python applications and have different settings.- Helpful when runtime dependencies differ between frameworks or libraries in various applications.- `virtualenv` is very useful in a more dynamic development environment. Creating VirtualenvSteps to create `virtualenv````bash$ mkdir sample_project$ cd sample_project/$ virtualenv .venv$ ls -lrthatotal 0drwxr-xr-x+ 35 username  CORP\Domain Users   1.2K Apr  6 10:49 ..drwxr-xr-x   3 username  CORP\Domain Users   102B Apr  6 10:50 .drwxr-xr-x   7 username  CORP\Domain Users   238B Apr  6 10:50 .venv``` Activating the Virtualenv```bash$ source .venv/bin/activate(.venv)$ ```We can install libararies only to this environment without modifying the actual system python installation using `pip` To start `python` interactive shell```bash(.venv)$ pythonPython 3.6.1 (default, Apr  4 2017, 09:40:51) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>``` How to properly Quit `python` interactive shell- You can either use exit() or Ctrl-D (i.e. EOF) to exit.- The brackets behind the exit function are crucial.- exit without brackets won't work in `python3` How to deactivate the `virtualenv` Just by running the command `deactivate` we can come out the `virtualenv````bash(.venv)$ deactivate$ ``` Going forward we are going to use only `Python3`- End Of Life for `Python2.7` is on April 12th, 2020- Security patches - Not to invest time on code portability and re-writing the existing code- More here on https://pythonclock.org/  Interactive shell Continued Primitive data types|Variable type|Example|Comment||:-----------:|:-------:|:-------------||`bool`|`True/False`| boolean true/false values||`int` `long`| 99999999999| Numbers/Integers (forget about the range of integers in `Python`)  Note: `long` wont see long as type in `python`||`float`| 0.99999999999| Decimals/Not whole integers||`str`| `"Hello World!"`, `'Hello World!'`, `'''Hello World!'''`, `"""Hello World!"""`| Any text||`None`| `None`| To create empty variable without any meaningful value|<jupyter_code>True
False
print(1 == 2)
'Hello World'
3
3.141
None<jupyter_output><empty_output><jupyter_text>Different ways to define strings<jupyter_code>print("Hello \"World!") # Simple Hello World
print(r'Hello \'World!') # Notice we use single quote to wrap the string.
print('''Hello \'World!''') # Notice we use three single quotes to wrap the string.
print("Hello \\ World!")
print("""Hello \" World!""") # Notice we use three double quotes to wrap the string.<jupyter_output><empty_output><jupyter_text>All primitive data types can be stored in a variable using an assignment operator: `=`  Boolean Variables<jupyter_code>flag = True
type(flag)
flag = False
type(flag)
flag = 1
type(flag)
flag = 'Hello World!'
type(flag)<jupyter_output><empty_output><jupyter_text>Integer/Float Vairables<jupyter_code>a = 5
type(a)
b = 10
type(b)
a + b
a / b # Difference between python2 and python3
c = a / b
type(c)<jupyter_output><empty_output><jupyter_text>**Note**: Variable `a` and `b` both are of type `int` result in variable `c` is of type `float`. This is new in `Python3`<jupyter_code>c = b % a
c
type(c)
a = 2
b = 5
a ** b # a^b => 2^5
pow(a, b)<jupyter_output><empty_output><jupyter_text>**Note:** All the Variables are case sensitive in `Python`<jupyter_code>A # Upper case a<jupyter_output><empty_output><jupyter_text>**Note:** `Traceback` are exceptions in `Python`. This is `NameError` exception is because since variable `A` is not found.  String Variables<jupyter_code>a = "Hello World!"
type(a)
b = input()
type(b)
b = int(b)
type(b)
a = "Hello"

a + " " + b
a + ' ' + b<jupyter_output><empty_output><jupyter_text>**Note:** String concatenation `+` creates new string. To make new string when we know the format of the log. It is better to use String format.<jupyter_code>c = '%s %s' % (a, b)
print(c)
a = 5
'Value of a is %d' % a 
a = 3.141
"Value of a is %.2f" % a
"Value of a is %9.2f" % a
"Value of a is %09.2f" % a<jupyter_output><empty_output><jupyter_text>Multiplication on stringsEssentially a multiple concatenation<jupyter_code>"-" * 4
a = "サブブ"
type(a)
a = u"サブブ"
type(a)<jupyter_output><empty_output><jupyter_text>Simple Python ScriptLet's create file `simple.py` with the following code```python!/usr/bin/env python FileName: simple.pyprint("Hello World!")``` To run the Python script```bash$ python simple.py``` To run the Python script as standalone. File has to be made executable by the following commandsFor example:```bash$ chmod +x scriptname``````bash$ chmod 755 scriptname```In our `simple.py````bash$ ls -lrth-rw-r--r--  1 username  1912965087    45B Apr  6 18:42 simple.py$ chmod +x simple.py$ ls -lrth -rwxr-xr-x  1 username  1912965087    45B Apr  6 18:42 simple.py$ ./simple.py``` Python internals Comiple code PVM (Python Virtual Machine)```bash$ ipython Python 3.6.1 (default, Apr  4 2017, 09:40:51) Type "copyright", "credits" or "license" for more information.IPython 5.3.0 -- An enhanced Interactive Python.?         -> Introduction and overview of IPython's features.%quickref -> Quick reference.help      -> Python's own help system.object?   -> Details about 'object', use 'object??' for extra details.In [1]: import py_compileIn [2]: py_compile.compile('simple.py')Out[2]: '__pycache__/simple.cpython-36.pyc'$ ls -lrth *-rwxr-xr-x  1 username  1912965087    45B Apr  6 18:42 simple.py__pycache__:-rw-r--r--  1 username  1912965087   118B Apr  6 18:54 simple.cpython-36.pyc```Using shell: ```bash$ python -m py_compile my_first_simple_script.py```- Developer don't have to and shouldn't bother about compiling Python code. - The compilation is hidden from the user for a good reason. Some newbies to Python wonder sometimes where these ominous files with the `.pyc` suffix might come from.- If Python has write-access for the directory where the Python program resides, it will store the compiled byte code in a file that ends with a `.pyc` suffix. - If Python has no write access, the program will work anyway. The byte code will be produced but discarded when the program exits.- Whenever a Python program is called, Python will check, if there exists a compiled version with the `.pyc` suffix. This file has to be newer than the file with the `.py` suffix. - If such a file exists, Python will load the byte code, which will speed up the start up time of the script. - If there exists no byte code version, Python will create the byte code before it starts the execution of the program. Execution of a Python program means execution of the byte code on the Python Virtual Machine (PVM).  Byte codeEvery time a Python script is executed, byte code is created. If a Python script is imported as a module, the byte code will be stored in the corresponding .pyc file. This won't create a Byte code.```bash$ python simple.py``````bash$ pythonPython 3.6.1 (default, Apr  4 2017, 09:40:51) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import simpleHello World!>>> (.venv) $ ls -lrth *-rwxr-xr-x  1 username  1912965087    45B Apr  6 18:42 simple.py__pycache__:total 8-rw-r--r--  1 username  1912965087   150B Apr  6 19:29 simple.cpython-36.pyc```  Structuring with Indentation BlockA block is a group of statements in a program or script. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. A language, which allows grouping with blocks, is called a block structured language. Generally, blocks can contain blocks as well, so we get a nested block structure. A block in a script or program functions as a mean to group statements to be treated as if they were one statement. In many cases, it also serves as a way to limit the lexical scope of variables and functions IndentationPython uses a different principle. Python programs get structured through indentation, i.e. code blocks are defined by their indentation. Okay that's what we expect from any program code, isn't it? Yes, but in the case of Python it's a language requirement not a matter of style. This principle makes it easier to read and understand other people's Python code.Following is an example.Loops and Conditional statements and function end with a colon "`:`".<jupyter_code># Python structures by colons and indentation. Here is a small example to print Pyramid
def print_pyramid(n):
    for each_line in range(0,n):
        for j in range(0,n-each_line):
            print(' ', end='', flush=True)
        for k in range(0, each_line):
            print('* ', end='', flush=True)
        print()
    print('Pyramid Printing completed!')

print_pyramid(10)<jupyter_output><empty_output><jupyter_text>More on `Python` VariablesGood news! There is no declaration of variables required in Python.**Another remarkable aspect of Python**: Not only the value of a variable may change during program execution but the type as well. You can assign an integer value to a variable, use it as an integer for a while and then assign a string to the same variable.  Valid Variable NamesThe naming of variables follows the more general concept of an identifier. A Python identifier is a name used to identify a variable, function, class, module or other object.- Uppercase letters "`A`" through "`Z`", the lowercase letters "`a`" through "`z`".- The underscore `_`.- Except for the first character, the digits 0 through 9.- Python 3.x is based on Unicode. This means that variable names and identifier names can additionally contain Unicode characters as well.- Identifiers are unlimited in length.- Case is very important (significant). Python KeywordsNo identifier can have the same name as one of the Python keywords, although they are obeying the above naming conventions: ```pythonand, as, assert, break, class, continue, def, del, elif, else,except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield```There is no need to learn them by heart. You can get the list of Python keywords in the interactive shell by using help. You type in help() in the interactive, but please don't forget the parenthesis:**Note:** Enter `keywords`<jupyter_code>help()
pi = 3             # data type is implicitly set to integer
pi = 3 + 0.141     # data type is changed to float
pi = "pi"          # and now it will be a string  
# A new object, which can be of any type, will be assigned to it. 
# Or the type of a variable can change during the execution of a script.<jupyter_output><empty_output><jupyter_text>**Note:** Python automatically takes care of the physical representation for the different data types, i.e. an integer values will be stored in a different memory location than a float or a string. Object ReferencesWe want to take a closer look on variables now. Python variables are references to objects, but the actual data is contained in the objectsAs variables are pointing to objects and objects can be of arbitrary data type, variables cannot have types associated with them. This is a huge difference to C, C++ or Java, where a variable is associated with a fixed data type. This association can't be changed as long as the program is running in C, C++ or Java. To demonstrate<jupyter_code>x = 42
y = x
print(x)
print(y)
y = 60
print(y)
print(x)<jupyter_output><empty_output><jupyter_text>`id` Function<jupyter_code>x = 42
id(x)
y = x
id(x), id(y)
y = 78
id(x), id(y)
a = (2+2)/4
b = 1 * 1
c = 6-5
print(type(a), type(b), type(c))
id(a), id(b), id(c)<jupyter_output><empty_output><jupyter_text>Naming Conventions `CamelCase` vs `camel_case`The Style Guide for Python Code recommends underscore notation for variable names as well as function names. Python preferred is `camel_case`https://www.python.org/dev/peps/pep-0008/function-names Strings in PythonA string in Python consists of a series or sequence of characters - letters, numbers, and special characters. Strings can be subscripted or indexed. Similar to C, the first character of a string has the index 0.|`0`|`1`|`2`|`3`|`4`|`5`|`6`|`7`|`8`|`9`|`10`|`11`||:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:||H|e|l|l|o| |W|o|r|l|d|!||-12|-11|-10|-9|-8|-7|-6|-5|-4|-3|-2|-1|<jupyter_code>a = 'Hello World!'
a[0]
a[6]<jupyter_output><empty_output><jupyter_text>Length of the string<jupyter_code>len(a)<jupyter_output><empty_output><jupyter_text>Last Character can be accessed like this<jupyter_code>a[len(a)-1]<jupyter_output><empty_output><jupyter_text>There is an easier way in Python. The last character can be accessed with -1, the second to last with -2 and so on<jupyter_code>a[-1]
a[-2]<jupyter_output><empty_output><jupyter_text>SlicingSubstrings can be created with the slice or slicing notation.|`0`|`1`|`2`|`3`|`4`|`5`|`6`|`7`|`8`|`9`|`10`|`11`||:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:||H|e|l|l|o| |W|o|r|l|d|!|<jupyter_code>a[3:7]<jupyter_output><empty_output><jupyter_text>Immutable StringsLike strings in Java and unlike C or C++, Python strings cannot be changed. Trying to change an indexed position will raise an error:<jupyter_code>a[5] = '.'<jupyter_output><empty_output><jupyter_text>A String PeculiarityThis holds true for `objects` too.<jupyter_code>a = 'HelloWorld'
b = 'HelloWorld'
print(a == b)
print(a is b)
print(id(a), id(b))
a = 'Hello World'
b = 'Hello World'
print(a == b)
print(a is b)
print(id(a), id(b))
a = "Baden-WÃ¼rttemberg"
b = "Baden-WÃ¼rttemberg"
print(a == b)
print(a is b)
print(id(a), id(b))
a = None
print(a is None)
print(a == None)
a = ''
print(a == '')
print(a is '')<jupyter_output><empty_output><jupyter_text>Escape Sequences in Strings|Escape Sequence|Meaning Notes||:-:|:-||\newline|Ignored||\\|Backslash (\)||\'|Single quote (')||\"|Double quote (")||\a|ASCII Bell (BEL)||\b|ASCII Backspace (BS)||\f|ASCII Formfeed (FF)||\n|ASCII Linefeed (LF)||\N{name}|Character named name in the Unicode database (Unicode only)||\r|ASCII Carriage Return (CR)||\t|ASCII Horizontal Tab (TAB)||\uxxxx|Character with 16-bit hex value xxxx (Unicode only)||\Uxxxxxxxx|Character with 32-bit hex value xxxxxxxx (Unicode only)||\v|ASCII Vertical Tab (VT)||\ooo|Character with octal value ooo||\xhh|Character with hex value hh|  Byte StringsPython 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. Every string or text in Python 3 is Unicode, but encoded Unicode is represented as binary data. The type used to hold text is `str`, the type used to hold data is bytes. It's not possible to mix text and data in Python 3; it will raise `TypeError`. While a string object holds a sequence of characters (in Unicode), a bytes object holds a sequence of bytes, out of the range `0 .. 255`, representing the ASCII values. Defining bytes objects and casting them into strings:<jupyter_code>x = b"Hallo"
print(x)
type(x)
t = str(x)
print(t)
t
u = t.encode("UTF-8")
print(u)
u
a = 'srinu 姓'
print(type(a))
print(type(a.encode('UTF-8')))
a.encode('UTF-8')
x = b"Hola \xe5\xa7\x93"
print(type(x))
# Convert byte string to UTF-8
x.decode("utf-8")
type(x.decode('utf-8'))<jupyter_output><empty_output><jupyter_text>Some good practices**In** `list` **:**  `append` **vs** `+`<jupyter_code>import timeit
timeit.timeit('''a = []
for i in range(0, 1000):
    a += [i]''', number=10000)
a = [None]
for i in range(0,10):
    a[0] = i

print(a)
timeit.timeit('''a = []
for i in range(0, 1000):
    a.append(i)''', number=10000)<jupyter_output><empty_output><jupyter_text>**In** `str` **:**  `join` **vs** `+`<jupyter_code>import timeit
timeit.timeit('''a = ''
for i in range(0, 100):
    a += str(i) + ' ' ''', number=1000)
a = []
for i in range(0, 10):
    a.append(str(i))
print(a)
print('$$$'.join(a))
import timeit
timeit.timeit('''a = [str(i) for i in range(0, 100)]
''.join(a)''', number=1000)<jupyter_output><empty_output><jupyter_text>`Console Outputs` **:**  `print` **vs** `stdout` and `stderr`<jupyter_code>import timeit
timeit.timeit('print("Hello")', number=10)
import sys
import timeit
timeit.timeit('sys.stdout.write("Hello\\n")', number=10)
import sys
import timeit
timeit.timeit('sys.stderr.write("Hello\\n")', number=10)
sys.stdout.write('Started\n')
try:
    print(1/0)
    sys.stdout.write('Done')
except Exception:
    sys.stderr.write('Error')
sys.stdout.write('Completed')<jupyter_output><empty_output><jupyter_text>Data Types we mainly use in our daily code- `int`- `str`- `float`- `list`- `tuple`- `dict`- `set`- `None`There are other like:- `frozenset`- `complex`  `float`<jupyter_code>a = 5.222222222222222222222222222222222222111111111111111111111
a
len(str(a))
a = 5897248172984712897498127498712984719828749827497298729874498274719274918274129748912374.1
a
type(a)<jupyter_output><empty_output><jupyter_text>`list`<jupyter_code>a = [] # Empty list
b = list() # Empty list
print(a, b)
a = [1, 2, 3]
b = [40, 5, 6]
a + b
a, b
a.extend(b)
a, b
a.append(7)
a
a.index(1)
a, a.index(40)
a.append(40)
a.index(9)
a.remove(40)
b = [50 for i in range(10)]
print(b)
while True:
    if 50 in b:
        b.remove(50)
    else:
        break
print(b)
a
a.insert(0, 0)
a
a.insert(0, 999)
a
a.insert(3, 300)
a
a.clear()
a
a = [999, 0, 1, 300, 2, 3, 4, 5, 6]
c = a.sort()
a, c
a.reverse()
a
a.pop() # pops the last element
a
a.pop(2) # By Specifying the index
a
a = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4]
a.count(1)
a.count(2)
a.count(3)
a.count(4)
a.remove(1)
a<jupyter_output><empty_output><jupyter_text>`dict`<jupyter_code>a = {} # Empty Dict
b = dict() # Empty Dict
print(a, b)
each = 'one'
a[each] = 1
a
b = {'two': 2, 'five': 5}
b
a + b
# a = {'two': 2000}
a.update(b)
a, b
a.get('one')
a['one']
a['three']
a.get('three', 3)
print(a)
a.clear()
a
a = {'one': (1,2), 'two': 2, 'three': 3}
a.keys()
a.get('one')
a.values()
a.items()
a.pop('one')
a
a.popitem()
a.setdefault('four', 4)
a
a.setdefault('four', 40)
a<jupyter_output><empty_output><jupyter_text>`set`<jupyter_code>a = {} # Empty Set
b = set() # Empty set
print(a, b)
a = set([1, 1, 2, 2, 3, 3, 4, 4])
a
b = set([5, 6, 7, 8])
a + b
a.update(b)
a
a = set([1, 1, 2, 2, 3, 3, 4, 4])
b = set([4, 5, 6, 7, 8])
a.union(b)
a
b
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a.intersection(b)
a.difference(b)
a.symmetric_difference(b)
a.discard(1)
a
a.issubset(b)
a = {1, 2, 3, 4}
b = {1, 2, 3, 4, 5, 6}
a.issubset(b)
a = {1, 2, 3, 4}
b = {1, 2, 3, 4, 5, 6}
b.issuperset(a)
a = {1, 2, 3, 4}
b = {1, 2, 3, 4, 5, 6}
b.difference_update(a)
a, b
a = {1, 2, 3, 4}
b = {1, 2, 3, 4, 5, 6}
a - b
b - a<jupyter_output><empty_output><jupyter_text>`tuple`<jupyter_code>a = () # Empty tuple
b = tuple() # Empty Tuple
print(a, b)
1, 2
a = 1, 2
a
b = 3, 4
b
a + b
a.index(2)
c = a + b
print(c)
c.index(3)
c
a_list = [1, 2, 3, 4]
a_tuple = (1, 2, 3, 4)
a_list[0] = 999
a_list
a_tuple[0]  = 999<jupyter_output><empty_output><jupyter_text>`if` conditioins<jupyter_code>if True:
    print('This is boolean True')
if False:
    print('This is boolean False')
if not False:
    print('This is boolean False')
if None:
    print('This is None')
if not None:
    print('This is None')<jupyter_output><empty_output><jupyter_text>Introduction of `else` and `elif`<jupyter_code># Find if the number is even 
a = 6
if (a % 2) == 0:
    print('a is even %s' % a)
else:
    print('a is odd %s' % a)
a = 10000  # Introduced conversion of string to int
if a < 0:
    print('a is negative number')
elif 0 <= a <= 100: # (0 <= a) and (a <=100)
    print('a is in range 0 to 100')
else:
    print('a is not in range 0 to 100')<jupyter_output><empty_output><jupyter_text>more on `if`<jupyter_code>if 1:
    print('This is 1. Valid True')
if 0:
    print('This is 0. Valid False')
if not 0:
    print('This is 0. Valid False')
# Re writing. Find if the number is even 
a = 11
if not (a % 2): # (a % 2) == 0
    print('a is even %s' % a)
else:
    print('a is odd %s' % a)
'Success' if True else 'Fail' # Single liner if 
'Success' if False else 'Fail'
a = 11
b = 'Odd' if a % 2 else 'Even'
print('a is %s number: %s' % (b, a))<jupyter_output><empty_output><jupyter_text>`try` `except` block<jupyter_code># Re writing. Find if the number is even 
try:
    a = 'hello'
    if not (a % 2):
        print('a is even %s' % a)
    else:
        print('a is odd %s' % a)
except Exception as err:
    print('a is not a valid integer %s' % (err,))
a = ['a', 'apple', '', 1, 0, -1, None, {}, [], set(), (), {'a': 1}, {1}, [1], (1,), [None], (None, )]
for each in a:
    print(type(each), end ='; ')
    if each:
        print('This is valid True %s' % str(each))
    else:
        print('This is valid False %s' % str(each))<jupyter_output><empty_output><jupyter_text>Already introduced `for`<jupyter_code># List
a = [1, 2, 3, 4, 5] 
for each in a:
    print(each)
# Tuple
a = (1, 2, 3, 4, 5)
for each in a:
    print(each)
# Set
a = {1, 2, 3, 4, 5}
for each in a:
    print(each)
# Dict: only Keys
a = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for each in a:
    print(each)
# Dict: only Values
a = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for each in a.values():
    print(each)
# Dict: key, value in tuple
a = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for each in a.items():
    print(each) # Here each is a tuple
# Dict: key and value individually
a = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for k, v in a.items():
    print(k, v)<jupyter_output><empty_output><jupyter_text>Mapping `list`s<jupyter_code># Mapping two lists
a = ['one', 'two', 'three', 'four', 'five']
b = [1, 2, 3, 4]
for each in zip(b, a):
    print(each)
# Mapping two lists and converting them to a dictionary
dict(zip(b, a))<jupyter_output><empty_output><jupyter_text>Exercises<jupyter_code># To print all the odd numbers from 0 to 100 into a list
odd_number_list = []
for each in range(0, 100):
    if (each%2 != 0):
        odd_number_list.append(each)
print(odd_number_list)
# To print all the odd numbers from 0 to 100 into a list
odd_number_list = []
for each in range(0, 100):
    if (each%2):
        odd_number_list.append(each)
print(odd_number_list)
a = []
for each in range(0, 100):
    a.append(each)
print(a)<jupyter_output><empty_output><jupyter_text>`list` comprehension<jupyter_code># Make a list that contains values from 0 to 100
a = [number for number in range(0, 100)]
print(a)
# Make a list that contains all the odd numbers from 0 to 100
a=[number for number in range(0, 100) if number%2]
print(a)
# All elements divisible by 3
a=[number for number in range(0, 100) if not number%3]
print(a)
# print square of all the elements from 0, 10
a = [number*number for number in range(0, 10)]
print(a)
def square(x):
    return x*x
a = [square(x) for x in range(5)]
print(a)
# print squareroot of all the elements from 0, 10
import math
a = [math.sqrt(number) for number in range(0, 10)]
print(a)<jupyter_output><empty_output><jupyter_text>Introduction to methods<jupyter_code>def method():
    a = 1 +2
    b = 3 +4
    pass

print(a , b)
print(method())
def method():
    return 
method()
def square(n):
    return n*n
square(10)
def compare(a, b):
    return a <= b
compare(20, 30)
var = ('prefix-set FAILOVER_v4 '
    '0.0.0.0/0 le 32 \n'
       'end-set \n'
       '! \n')
print(var)
def char_counter(input_str):
    counter_dict = dict()
    for each in input_str:
        counter_dict.setdefault(each, 0)
        counter_dict[each] += 1
    return counter_dict
print(char_counter('hello Srinu'))
a = input()
print(a)
print(type(a))
a = int(a)
print(a)
print(type(a))
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7 
0
def test():
    max_int = int(input())
    a = []
    for each in range(0, max_num):
        a.append(each)
    print(a)
print('0 1 2 3')
c = ' '.join(['0', '1', '2', '3'])
type(c)
def test(max_int):                     # O(n*n)
    a = ''
    for each in range(0, max_int+1):   # O(n)
        for i in range(0, each+1):     # O(n)
            a += str(i)
            a += ' '
        a += '\n'
    return a
print(test(5))
10 in  [4, 3, 2, 7, 8, 2, 1, 3]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12873870859819336, 'fraction_numerical': 0.03653395784543326, 'mean_word_length': 4.429791099000909, 'pattern_counts': {'":': 0, '<': 161, '<?xml version=': 0, '>': 169, 'https://': 8, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 6, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '38', 'dir': 'jupyter-structured-clean-dedup', 'id': '145331', 'license': 'MIT', 'n_tokens_mistral': 10867, 'n_tokens_neox': 9837, 'n_words': 3943, 'path': '00-PythonLearning/00-PythonIntroduction.ipynb', 'repo_name': 'spendyala/deeplearning-docker', 'size': '29910'}