<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Esther Wavinya</title>
    <description>The latest articles on DEV Community by Esther Wavinya (@estherwavinya).</description>
    <link>https://dev.to/estherwavinya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F322752%2F5bf61aaf-58ca-4c56-877a-50364a2f3e80.jpeg</url>
      <title>DEV Community: Esther Wavinya</title>
      <link>https://dev.to/estherwavinya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/estherwavinya"/>
    <language>en</language>
    <item>
      <title>Why Geospatial Technology</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Sun, 07 Jun 2020 10:37:47 +0000</pubDate>
      <link>https://dev.to/estherwavinya/why-geospatial-technology-38g2</link>
      <guid>https://dev.to/estherwavinya/why-geospatial-technology-38g2</guid>
      <description>&lt;p&gt;Geospatial technology is an emerging field of study that includes Geographic Information System (GIS), Remote Sensing (RS) and Global Positioning System (GPS). &lt;/p&gt;

&lt;p&gt;Here is the link to the article in my medium account &lt;a href="https://link.medium.com/EyYnQhhy76" rel="noopener noreferrer"&gt;Why Geospatial Technology&lt;/a&gt;&lt;/p&gt;

</description>
      <category>gis</category>
      <category>qgis</category>
      <category>arcgis</category>
      <category>datascience</category>
    </item>
    <item>
      <title>Python Frameworks and libraries</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Sun, 07 Jun 2020 09:48:54 +0000</pubDate>
      <link>https://dev.to/estherwavinya/python-frameworks-and-libraries-24di</link>
      <guid>https://dev.to/estherwavinya/python-frameworks-and-libraries-24di</guid>
      <description>&lt;p&gt;I wrote the article in my medium account. The link is &lt;a href="https://link.medium.com/jRssHCew76" rel="noopener noreferrer"&gt;What I should have known about Python&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codenewbie</category>
      <category>beginners</category>
      <category>writing</category>
    </item>
    <item>
      <title>Functional Programming</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Mon, 11 May 2020 08:16:23 +0000</pubDate>
      <link>https://dev.to/estherwavinya/functional-programming-2lm8</link>
      <guid>https://dev.to/estherwavinya/functional-programming-2lm8</guid>
      <description>&lt;p&gt;&lt;strong&gt;6. Functional Programming&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;6.1. Recursion&lt;/strong&gt;&lt;br&gt;
Defining solution of a problem in terms of the same problem, typically of smaller size, is called recursion. Recursion makes it possible to express solution of a problem very concisely and elegantly.&lt;/p&gt;

&lt;p&gt;A function is called recursive if it makes call to itself. Typically, a recursive function will have a terminating condition and one or more recursive calls to itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6.1.1. Example: Computing Exponent&lt;/strong&gt;&lt;br&gt;
Mathematically we can define exponent of a number in terms of its smaller power.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def exp(x, n):
    """
    Computes the result of x raised to the power of n.

        &amp;gt;&amp;gt;&amp;gt; exp(2, 3)
        8
        &amp;gt;&amp;gt;&amp;gt; exp(3, 2)
        9
    """
    if n == 0:
        return 1
    else:
        return x * exp(x, n-1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets look at the execution pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exp(2, 4)
+-- 2 * exp(2, 3)
|       +-- 2 * exp(2, 2)
|       |       +-- 2 * exp(2, 1)
|       |       |       +-- 2 * exp(2, 0)
|       |       |       |       +-- 1
|       |       |       +-- 2 * 1
|       |       |       +-- 2
|       |       +-- 2 * 2
|       |       +-- 4
|       +-- 2 * 4
|       +-- 8
+-- 2 * 8
+-- 16
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Number of calls to the above &lt;code&gt;exp&lt;/code&gt; function is proportional to size of the problem, which is &lt;code&gt;n&lt;/code&gt; here.&lt;/p&gt;

&lt;p&gt;We can compute exponent in fewer steps if we use successive squaring.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def fast_exp(x, n):
    if n == 0:
        return 1
    elif n % 2 == 0:
        return fast_exp(x*x, n/2))
    else:
        return x * fast_exp(x, n-1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets look at the execution pattern now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fast_exp(2, 10)
+-- fast_exp(4, 5) # 2 * 2
|   +-- 4 * fast_exp(4, 4)
|   |       +-- fast_exp(16, 2) # 4 * 4
|   |       |   +-- fast_exp(256, 1) # 16 * 16
|   |       |   |   +-- 256 * fast_exp(256, 0)
|   |       |   |             +-- 1
|   |       |   |   +-- 256 * 1
|   |       |   |   +-- 256
|   |       |   +-- 256
|   |       +-- 256
|   +-- 4 * 256
|   +-- 1024
+-- 1024
1024
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; Implement a function &lt;code&gt;product&lt;/code&gt; to multiply 2 numbers recursively using + and - operators only.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6.1.2. Example: Flatten a list&lt;/strong&gt;&lt;br&gt;
Supposed you have a nested list and want to flatten it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def flatten_list(a, result=None):
    """Flattens a nested list.

        &amp;gt;&amp;gt;&amp;gt; flatten_list([ [1, 2, [3, 4] ], [5, 6], 7])
        [1, 2, 3, 4, 5, 6, 7]
    """
    if result is None:
        result = []

    for x in a:
        if isinstance(x, list):
            flatten_list(x, result)
        else:
            result.append(x)

    return result
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; Write a function &lt;code&gt;flatten_dict&lt;/code&gt; to flatten a nested dictionary by joining the keys with . character.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; flatten_dict({'a': 1, 'b': {'x': 2, 'y': 3}, 'c': 4})
{'a': 1, 'b.x': 2, 'b.y': 3, 'c': 4}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; Write a function &lt;code&gt;unflatten_dict&lt;/code&gt; to do reverse of flatten_dict.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; unflatten_dict({'a': 1, 'b.x': 2, 'b.y': 3, 'c': 4})
{'a': 1, 'b': {'x': 2, 'y': 3}, 'c': 4}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; Write a function &lt;code&gt;treemap&lt;/code&gt; to map a function over nested list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; treemap(lambda x: x*x, [1, 2, [3, 4, [5]]])
[1, 4, [9, 16, [25]]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 5:&lt;/strong&gt; Write a function &lt;code&gt;tree_reverse&lt;/code&gt; to reverse elements of a nested-list recursively.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; tree_reverse([[1, 2], [3, [4, 5]], 6])
[6, [[5, 4], 3], [2, 1]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6.1.3. Example: JSON Encode&lt;/strong&gt;&lt;br&gt;
Lets look at more commonly used example of serializing a python datastructure into &lt;code&gt;JSON (JavaScript Object Notation)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here is an example of JSON record.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "name": "Advanced Python Training",
    "date": "October 13, 2012",
    "completed": false,
    "instructor": {
        "name": "Anand Chitipothu",
        "website": "http://anandology.com/"
    },
    "participants": [
        {
            "name": "Participant 1",
            "email": "email1@example.com"
        },
        {
            "name": "Participant 2",
            "email": "email2@example.com"
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It looks very much like Python dictionaries and lists. There are some differences though. Strings are always enclosed in double quotes, booleans are represented as &lt;code&gt;true&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The standard library module json provides functionality to work in JSON. Lets try to implement it now as it is very good example of use of recursion.&lt;/p&gt;

&lt;p&gt;For simplicity, lets assume that strings will not have any special characters and can have space, tab and newline characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def json_encode(data):
    if isinstance(data, bool):
        if data:
            return "true"
        else:
            return "false"
    elif isinstance(data, (int, float)):
        return str(data)
    elif isinstance(data, str):
        return '"' + escape_string(data) + '"'
    elif isinstance(data, list):
        return "[" + ", ".join(json_encode(d) for d in data) + "]"
    else:
        raise TypeError("%s is not JSON serializable" % repr(data))

def escape_string(s):
    """Escapes double-quote, tab and new line characters in a string."""
    s = s.replace('"', '\\"')
    s = s.replace("\t", "\\t")
    s = s.replace("\n", "\\n")
    return s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This handles booleans, integers, strings, floats and lists, but doesn’t handle dictionaries yet. That is left an exercise to the readers.&lt;/p&gt;

&lt;p&gt;If you notice the block of code that is handling lists, we are calling json_encode recursively for each element of the list, that is required because each element can be of any type, even a list or a dictionary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 6:&lt;/strong&gt; Complete the above implementation of &lt;code&gt;json_encode&lt;/code&gt; by handling the case of dictionaries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 7:&lt;/strong&gt; Implement a program &lt;code&gt;dirtree.py&lt;/code&gt; that takes a directory as argument and prints all the files in that directory recursively as a tree.&lt;/p&gt;

&lt;p&gt;Hint: Use &lt;code&gt;os.listdir&lt;/code&gt; and &lt;code&gt;os.path.isdir&lt;/code&gt; funtions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python dirtree.py foo/
foo/
|-- a.txt
|-- b.txt
|-- bar/
|   |-- p.txt
|   `-- q.txt
`-- c.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 8:&lt;/strong&gt; Write a function count_change to count the number of ways to change any given amount. Available coins are also passed as argument to the function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; count_change(10, [1, 5])
3
&amp;gt;&amp;gt;&amp;gt; count_change(10, [1, 2])
6
&amp;gt;&amp;gt;&amp;gt; count_change(100, [1, 5, 10, 25, 50])
292
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 9:&lt;/strong&gt; Write a function permute to compute all possible permutations of elements of a given list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; permute([1, 2, 3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6.2. Higher Order Functions &amp;amp; Decorators&lt;/strong&gt;&lt;br&gt;
In Python, functions are first-class objects. They can be passed as arguments to other functions and a new functions can be returned from a function call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6.2.1. Example: Tracing Function Calls&lt;/strong&gt;&lt;br&gt;
For example, consider the following fib function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def fib(n):
    if n is 0 or n is 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suppose we want to trace all the calls to the fib function. We can write a higher order function to return a new function, which prints whenever fib function is called.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def trace(f):
    def g(x):
        print(f.__name__, x)
        value = f(x)
        print('return', repr(value))
        return value
    return g

fib = trace(fib)
print(fib(3))
This produces the following output.

fib 3
fib 2
fib 1
return 1
fib 0
return 1
return 2
fib 1
return 1
return 3
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Noticed that the trick here is at &lt;code&gt;fib = trace(fib)&lt;/code&gt;. We have replaced the function &lt;code&gt;fib&lt;/code&gt; with a new function, so whenever that function is called recursively, it is the our new function, which prints the trace before calling the orginal function.&lt;/p&gt;

&lt;p&gt;To make the output more readable, let us indent the function calls.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def trace(f):
    f.indent = 0
    def g(x):
        print('|  ' * f.indent + '|--', f.__name__, x)
        f.indent += 1
        value = f(x)
        print('|  ' * f.indent + '|--', 'return', repr(value))
        f.indent -= 1
        return value
    return g

fib = trace(fib)
print(fib(4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This produces the following output.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python fib.py
|-- fib 4
|  |-- fib 3
|  |  |-- fib 2
|  |  |  |-- fib 1
|  |  |  |  |-- return 1
|  |  |  |-- fib 0
|  |  |  |  |-- return 1
|  |  |  |-- return 2
|  |  |-- fib 1
|  |  |  |-- return 1
|  |  |-- return 3
|  |-- fib 2
|  |  |-- fib 1
|  |  |  |-- return 1
|  |  |-- fib 0
|  |  |  |-- return 1
|  |  |-- return 2
|  |-- return 5
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This pattern is so useful that python has special syntax for specifying this concisely.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@trace
def fib(n):
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is equivalant of adding &lt;code&gt;fib = trace(fib)&lt;/code&gt; after the function definition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6.2.2. Example: Memoize&lt;/strong&gt;&lt;br&gt;
In the above example, it is clear that number of function calls are growing exponentially with the size of input and there is lot of redundant computation that is done.&lt;/p&gt;

&lt;p&gt;Suppose we want to get rid of the redundant computation by caching the result of fib when it is called for the first time and reuse it when it is needed next time. Doing this is very popular in functional programming world and it is called &lt;code&gt;memoize&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def memoize(f):
    cache = {}
    def g(x):
        if x not in cache:
            cache[x] = f(x)
        return cache[x]
    return g

fib = trace(fib)
fib = memoize(fib)
print(fib(4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you notice, after &lt;code&gt;memoize&lt;/code&gt;, growth of &lt;code&gt;fib&lt;/code&gt; has become linear.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|-- fib 4
|  |-- fib 3
|  |  |-- fib 2
|  |  |  |-- fib 1
|  |  |  |  |-- return 1
|  |  |  |-- fib 0
|  |  |  |  |-- return 1
|  |  |  |-- return 2
|  |  |-- return 3
|  |-- return 5
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 10:&lt;/strong&gt; Write a function profile, which takes a function as argument and returns a new function, which behaves exactly similar to the given function, except that it prints the time consumed in executing it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; fib = profile(fib)
&amp;gt;&amp;gt;&amp;gt; fib(20)
time taken: 0.1 sec
10946
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 11:&lt;/strong&gt; Write a function &lt;code&gt;vectorize&lt;/code&gt; which takes a function f and return a new function, which takes a list as argument and calls f for every element and returns the result as a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; def square(x): return x * x
...
&amp;gt;&amp;gt;&amp;gt; f = vectorize(square)
&amp;gt;&amp;gt;&amp;gt; f([1, 2, 3])
[1, 4, 9]
&amp;gt;&amp;gt;&amp;gt; g = vectorize(len)
&amp;gt;&amp;gt;&amp;gt; g(["hello", "world"])
[5, 5]
&amp;gt;&amp;gt;&amp;gt; g([[1, 2], [2, 3, 4]])
[2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6.2.3. Example: unixcommand decorator&lt;/strong&gt;&lt;br&gt;
Many unix commands have a typical pattern. They accept multiple filenames as arguments, does some processing and prints the lines back. Some examples of such commands are cat and grep.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def unixcommand(f):
    def g(filenames):
        printlines(out for line in readlines(filenames)
                           for out in f(line))
    return g
Lets see how to use it.

@unixcommand
def cat(line):
    yield line

@unixcommand
def lowercase(line):
    yield line.lower()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6.3. exec &amp;amp; eval&lt;/strong&gt;&lt;br&gt;
Python privides the whole interpreter as a built-in function. You can pass a string and ask it is execute that piece of code at run time.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; exec("x = 1")
&amp;gt;&amp;gt;&amp;gt; x
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By default exec works in the current environment, so it updated the globals in the above example. It is also possible to specify an environment to exec.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; env = {'a' : 42}
&amp;gt;&amp;gt;&amp;gt; exec('x = a+1', env)
&amp;gt;&amp;gt;&amp;gt; print(env['x'])
43
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is also possible to create functions or classes dynamically using exec, though it is usually not a good idea.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; code = 'def add_%d(x): return x + %d'
&amp;gt;&amp;gt;&amp;gt; for i in range(1, 5):
...     exec(code % (i, i))
...
&amp;gt;&amp;gt;&amp;gt; add_1(3)
4
&amp;gt;&amp;gt;&amp;gt; add_3(3)
6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;eval&lt;/code&gt; is like &lt;code&gt;exec&lt;/code&gt; but it takes an expression and returns its value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; eval("2+3")
5
&amp;gt;&amp;gt;&amp;gt; a = 2
&amp;gt;&amp;gt;&amp;gt; eval("a * a")
4
&amp;gt;&amp;gt;&amp;gt; env = {'x' : 42}
&amp;gt;&amp;gt;&amp;gt; eval('x+1', env)
43
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
    <item>
      <title>Iterators &amp; Generators</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Wed, 06 May 2020 15:15:39 +0000</pubDate>
      <link>https://dev.to/estherwavinya/iterators-generators-1ghk</link>
      <guid>https://dev.to/estherwavinya/iterators-generators-1ghk</guid>
      <description>&lt;p&gt;&lt;strong&gt;5. Iterators &amp;amp; Generators&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;5.1. Iterators&lt;/strong&gt;&lt;br&gt;
We use &lt;code&gt;for&lt;/code&gt; statement for looping over a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for i in [1, 2, 3, 4]:
...     print(i)
...
1
2
3
4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we use it with a string, it loops over its characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for c in "python":
...     print(c)
...
p
y
t
h
o
n
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we use it with a dictionary, it loops over its keys.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for k in {"x": 1, "y": 2}:
...     print(k)
...
y
x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we use it with a file, it loops over lines of the file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for line in open("a.txt"):
...     print(line, end="")
...
first line
second line
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So there are many types of objects which can be used with a for loop. These are called &lt;code&gt;iterable objects&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are many functions which consume these iterables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; ",".join(["a", "b", "c"])
'a,b,c'
&amp;gt;&amp;gt;&amp;gt; ",".join({"x": 1, "y": 2})
'y,x'
&amp;gt;&amp;gt;&amp;gt; list("python")
['p', 'y', 't', 'h', 'o', 'n']
&amp;gt;&amp;gt;&amp;gt; list({"x": 1, "y": 2})
['y', 'x']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5.1.1. The Iteration Protocol&lt;/strong&gt;&lt;br&gt;
The built-in function &lt;code&gt;iter&lt;/code&gt; takes an iterable object and returns an iterator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = iter([1, 2, 3])
&amp;gt;&amp;gt;&amp;gt; x
&amp;lt;listiterator object at 0x1004ca850&amp;gt;
&amp;gt;&amp;gt;&amp;gt; next(x)
1
&amp;gt;&amp;gt;&amp;gt; next(x)
2
&amp;gt;&amp;gt;&amp;gt; next(x)
3
&amp;gt;&amp;gt;&amp;gt; next(x)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
StopIteration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each time we call the &lt;code&gt;next&lt;/code&gt; method on the iterator gives us the next element. If there are no more elements, it raises a &lt;em&gt;StopIteration&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Iterators are implemented as classes. Here is an iterator that works like built-in &lt;code&gt;range&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class yrange:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i &amp;lt; self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;__iter__&lt;/code&gt; method is what makes an object iterable. Behind the scenes, the iter function calls &lt;code&gt;__iter__&lt;/code&gt; method on the given object.&lt;/p&gt;

&lt;p&gt;The return value of &lt;code&gt;__iter__&lt;/code&gt; is an iterator. It should have a &lt;code&gt;__next__&lt;/code&gt; method and raise &lt;code&gt;StopIteration&lt;/code&gt; when there are no more elements.&lt;/p&gt;

&lt;p&gt;Lets try it out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; y = yrange(3)
&amp;gt;&amp;gt;&amp;gt; next(y)
0
&amp;gt;&amp;gt;&amp;gt; next(y)
1
&amp;gt;&amp;gt;&amp;gt; next(y)
2
&amp;gt;&amp;gt;&amp;gt; next(y)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
  File "&amp;lt;stdin&amp;gt;", line 14, in __next__
StopIteration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Many built-in functions accept iterators as arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; list(yrange(5))
[0, 1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; sum(yrange(5))
10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above case, both the iterable and iterator are the same object. Notice that the &lt;code&gt;__iter__&lt;/code&gt; method returned self. It need not be the case always.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class zrange:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return zrange_iter(self.n)

class zrange_iter:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        # Iterators are iterables too.
        # Adding this functions to make them so.
        return self

    def __next__(self):
        if self.i &amp;lt; self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If both iteratable and iterator are the same object, it is consumed in a single iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; y = yrange(5)
&amp;gt;&amp;gt;&amp;gt; list(y)
[0, 1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; list(y)
[]
&amp;gt;&amp;gt;&amp;gt; z = zrange(5)
&amp;gt;&amp;gt;&amp;gt; list(z)
[0, 1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; list(z)
[0, 1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; Write an iterator class &lt;code&gt;reverse_iter&lt;/code&gt;, that takes a list and iterates it from the reverse direction. ::&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; it = reverse_iter([1, 2, 3, 4])
&amp;gt;&amp;gt;&amp;gt; next(it)
4
&amp;gt;&amp;gt;&amp;gt; next(it)
3
&amp;gt;&amp;gt;&amp;gt; next(it)
2
&amp;gt;&amp;gt;&amp;gt; next(it)
1
&amp;gt;&amp;gt;&amp;gt; next(it)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
StopIteration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5.2. Generators&lt;/strong&gt;&lt;br&gt;
Generators simplifies creation of iterators. A generator is a function that produces a sequence of results instead of a single value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def yrange(n):
    i = 0
    while i &amp;lt; n:
        yield i
        i += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each time the &lt;code&gt;yield&lt;/code&gt; statement is executed the function generates a new value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; y = yrange(3)
&amp;gt;&amp;gt;&amp;gt; y
&amp;lt;generator object yrange at 0x401f30&amp;gt;
&amp;gt;&amp;gt;&amp;gt; next(y)
0
&amp;gt;&amp;gt;&amp;gt; next(y)
1
&amp;gt;&amp;gt;&amp;gt; next(y)
2
&amp;gt;&amp;gt;&amp;gt; next(y)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
StopIteration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So a generator is also an iterator. You don’t have to worry about the iterator protocol.&lt;/p&gt;

&lt;p&gt;The word “generator” is confusingly used to mean both the function that generates and what it generates. In this chapter, I’ll use the word “generator” to mean the genearted object and “generator function” to mean the function that generates it.&lt;/p&gt;

&lt;p&gt;Can you think about how it is working internally?&lt;/p&gt;

&lt;p&gt;When a generator function is called, it returns a generator object without even beginning execution of the function. When &lt;code&gt;next&lt;/code&gt; method is called for the first time, the function starts executing until it reaches &lt;code&gt;yield&lt;/code&gt; statement. The yielded value is returned by the &lt;code&gt;next&lt;/code&gt; call.&lt;/p&gt;

&lt;p&gt;The following example demonstrates the interplay between &lt;code&gt;yield&lt;/code&gt; and call to &lt;code&gt;__next__&lt;/code&gt; method on generator object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; def foo():
...     print("begin")
...     for i in range(3):
...         print("before yield", i)
...         yield i
...         print("after yield", i)
...     print("end")
...
&amp;gt;&amp;gt;&amp;gt; f = foo()
&amp;gt;&amp;gt;&amp;gt; next(f)
begin
before yield 0
0
&amp;gt;&amp;gt;&amp;gt; next(f)
after yield 0
before yield 1
1
&amp;gt;&amp;gt;&amp;gt; next(f)
after yield 1
before yield 2
2
&amp;gt;&amp;gt;&amp;gt; next(f)
after yield 2
end
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
StopIteration
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets see an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def integers():
    """Infinite sequence of integers."""
    i = 1
    while True:
        yield i
        i = i + 1

def squares():
    for i in integers():
        yield i * i

def take(n, seq):
    """Returns first n values from the given sequence."""
    seq = iter(seq)
    result = []
    try:
        for i in range(n):
            result.append(next(seq))
    except StopIteration:
        pass
    return result

print(take(5, squares())) # prints [1, 4, 9, 16, 25]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5.3. Generator Expressions&lt;/strong&gt;&lt;br&gt;
Generator Expressions are generator version of list comprehensions. They look like list comprehensions, but returns a generator back instead of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = (x*x for x in range(10))
&amp;gt;&amp;gt;&amp;gt; a
&amp;lt;generator object &amp;lt;genexpr&amp;gt; at 0x401f08&amp;gt;
&amp;gt;&amp;gt;&amp;gt; sum(a)
285
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use the generator expressions as arguments to various functions that consume iterators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; sum((x*x for x in range(10)))
285
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When there is only one argument to the calling function, the parenthesis around generator expression can be omitted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; sum(x*x for x in range(10))
285
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another fun example:&lt;/p&gt;

&lt;p&gt;Lets say we want to find first 10 (or any n) pythogorian triplets. A triplet &lt;code&gt;(x, y, z)&lt;/code&gt; is called pythogorian triplet if &lt;code&gt;x*x + y*y == z*z&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It is easy to solve this problem if we know till what value of z to test for. But we want to find first n pythogorian triplets.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; pyt = ((x, y, z) for z in integers() for y in range(1, z) for x in range(1, y) if x*x + y*y == z*z)
&amp;gt;&amp;gt;&amp;gt; take(10, pyt)
[(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17), (12, 16, 20), (15, 20, 25), (7, 24, 25), (10, 24, 26), (20, 21, 29)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5.3.1. Example: Reading multiple files&lt;/strong&gt;&lt;br&gt;
Lets say we want to write a program that takes a list of filenames as arguments and prints contents of all those files, like &lt;code&gt;cat&lt;/code&gt; command in unix.&lt;/p&gt;

&lt;p&gt;The traditional way to implement it is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def cat(filenames):
    for f in filenames:
        for line in open(f):
            print(line, end="")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, lets say we want to print only the line which has a particular substring, like &lt;code&gt;grep&lt;/code&gt; command in unix.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def grep(pattern, filenames):
    for f in filenames:
        for line in open(f):
            if pattern in line:
                print(line, end="")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both these programs have lots of code in common. It is hard to move the common part to a function. But with generators makes it possible to do it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def readfiles(filenames):
    for f in filenames:
        for line in open(f):
            yield line

def grep(pattern, lines):
    return (line for line in lines if pattern in line)

def printlines(lines):
    for line in lines:
        print(line, end="")

def main(pattern, filenames):
    lines = readfiles(filenames)
    lines = grep(pattern, lines)
    printlines(lines)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code is much simpler now with each function doing one small thing. We can move all these functions into a separate module and reuse it in other programs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; Write a program that takes one or more filenames as arguments and prints all the lines which are longer than 40 characters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; Write a function &lt;code&gt;findfiles&lt;/code&gt; that recursively descends the directory tree for the specified directory and generates paths of all the files in the tree.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; Write a function to compute the number of python files (.py extension) in a specified directory recursively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 5:&lt;/strong&gt; Write a function to compute the total number of lines of code in all python files in the specified directory recursively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 6:&lt;/strong&gt; Write a function to compute the total number of lines of code, ignoring empty and comment lines, in all python files in the specified directory recursively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 7:&lt;/strong&gt; Write a program &lt;code&gt;split.py&lt;/code&gt;, that takes an integer n and a filename as command line arguments and splits the file into multiple small files with each having n lines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5.4. Itertools&lt;/strong&gt;&lt;br&gt;
The itertools module in the standard library provides lot of intersting tools to work with iterators.&lt;/p&gt;

&lt;p&gt;Lets look at some of the interesting functions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;chain&lt;/code&gt; – chains multiple iterators together.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; it1 = iter([1, 2, 3])
&amp;gt;&amp;gt;&amp;gt; it2 = iter([4, 5, 6])
&amp;gt;&amp;gt;&amp;gt; itertools.chain(it1, it2)
[1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;izip&lt;/code&gt; – iterable version of zip&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for x, y in itertools.izip(["a", "b", "c"], [1, 2, 3]):
...     print(x, y)
...
a 1
b 2
c 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 8:&lt;/strong&gt; Write a function &lt;code&gt;peep&lt;/code&gt;, that takes an iterator as argument and returns the first element and an equivalant iterator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; it = iter(range(5))
&amp;gt;&amp;gt;&amp;gt; x, it1 = peep(it)
&amp;gt;&amp;gt;&amp;gt; print(x, list(it1))
0 [0, 1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 9:&lt;/strong&gt; The built-in function enumerate takes an iteratable and returns an iterator over pairs (index, value) for each value in the source.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; list(enumerate(["a", "b", "c"])
[(0, "a"), (1, "b"), (2, "c")]
&amp;gt;&amp;gt;&amp;gt; for i, c in enumerate(["a", "b", "c"]):
...     print(i, c)
...
0 a
1 b
2 c
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
    <item>
      <title>Object Oriented Programming</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Wed, 06 May 2020 14:55:36 +0000</pubDate>
      <link>https://dev.to/estherwavinya/object-oriented-programming-2pko</link>
      <guid>https://dev.to/estherwavinya/object-oriented-programming-2pko</guid>
      <description>&lt;p&gt;&lt;strong&gt;4. Object Oriented Programming&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;4.1. State&lt;/strong&gt;&lt;br&gt;
Suppose we want to model a bank account with support for &lt;code&gt;deposit&lt;/code&gt; and &lt;code&gt;withdraw&lt;/code&gt; operations. One way to do that is by using global state as shown in the following example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;balance = 0

def deposit(amount):
    global balance
    balance += amount
    return balance

def withdraw(amount):
    global balance
    balance -= amount
    return balance
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example is good enough only if we want to have just a single account. Things start getting complicated if want to model multiple accounts.&lt;/p&gt;

&lt;p&gt;We can solve the problem by making the state local, probably by using a dictionary to store the state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def make_account():
    return {'balance': 0}

def deposit(account, amount):
    account['balance'] += amount
    return account['balance']

def withdraw(account, amount):
    account['balance'] -= amount
    return account['balance']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this it is possible to work with multiple accounts at the same time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = make_account()
&amp;gt;&amp;gt;&amp;gt; b = make_account()
&amp;gt;&amp;gt;&amp;gt; deposit(a, 100)
100
&amp;gt;&amp;gt;&amp;gt; deposit(b, 50)
50
&amp;gt;&amp;gt;&amp;gt; withdraw(b, 10)
40
&amp;gt;&amp;gt;&amp;gt; withdraw(a, 10)
90
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4.2. Classes and Objects&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class BankAccount:
    def __init__(self):
        self.balance = 0

    def withdraw(self, amount):
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

&amp;gt;&amp;gt;&amp;gt; a = BankAccount()
&amp;gt;&amp;gt;&amp;gt; b = BankAccount()
&amp;gt;&amp;gt;&amp;gt; a.deposit(100)
100
&amp;gt;&amp;gt;&amp;gt; b.deposit(50)
50
&amp;gt;&amp;gt;&amp;gt; b.withdraw(10)
40
&amp;gt;&amp;gt;&amp;gt; a.withdraw(10)
90
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4.3. Inheritance&lt;/strong&gt;&lt;br&gt;
Let us try to create a little more sophisticated account type where the account holder has to maintain a pre-determined minimum balance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
        BankAccount.__init__(self)
        self.minimum_balance = minimum_balance

    def withdraw(self, amount):
        if self.balance - amount &amp;lt; self.minimum_balance:
            print('Sorry, minimum balance must be maintained.')
        else:
            BankAccount.withdraw(self, amount)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; What will the output of the following program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class A:
    def f(self):
        return self.g()

    def g(self):
        return 'A'

class B(A):
    def g(self):
        return 'B'

a = A()
b = B()
print(a.f(), b.f())
print(a.g(), b.g())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example: Drawing Shapes&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Canvas:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.data = [[' '] * width for i in range(height)]

    def setpixel(self, row, col):
        self.data[row][col] = '*'

    def getpixel(self, row, col):
        return self.data[row][col]

    def display(self):
        print("\n".join(["".join(row) for row in self.data]))

class Shape:
    def paint(self, canvas): pass

class Rectangle(Shape):
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    def hline(self, x, y, w):
        pass

    def vline(self, x, y, h):
        pass

    def paint(self, canvas):
        hline(self.x, self.y, self.w)
        hline(self.x, self.y + self.h, self.w)
        vline(self.x, self.y, self.h)
        vline(self.x + self.w, self.y, self.h)

class Square(Rectangle):
    def __init__(self, x, y, size):
        Rectangle.__init__(self, x, y, size, size)

class CompoundShape(Shape):
    def __init__(self, shapes):
        self.shapes = shapes

    def paint(self, canvas):
        for s in self.shapes:
            s.paint(canvas)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4.4. Special Class Methods&lt;/strong&gt;&lt;br&gt;
In Python, a class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.&lt;/p&gt;

&lt;p&gt;For example, the + operator invokes &lt;code&gt;__add__&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a, b = 1, 2
&amp;gt;&amp;gt;&amp;gt; a + b
3
&amp;gt;&amp;gt;&amp;gt; a.__add__(b)
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just like &lt;code&gt;__add__&lt;/code&gt; is called for &lt;code&gt;+&lt;/code&gt; operator, &lt;code&gt;__sub__&lt;/code&gt;, &lt;code&gt;__mul__&lt;/code&gt; and &lt;code&gt;__div__&lt;/code&gt; methods are called for &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;*&lt;/code&gt;, and &lt;code&gt;/&lt;/code&gt; operators.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Rational Numbers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose we want to do arithmetic with rational numbers. We want to be able to add, subtract, multiply, and divide them and to test whether two rational numbers are equal.&lt;/p&gt;

&lt;p&gt;We can add, subtract, multiply, divide, and test equality by using the following relations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;n1/d1 + n2/d2 = (n1*d2 + n2*d1)/(d1*d2)
n1/d1 - n2/d2 = (n1*d2 - n2*d1)/(d1*d2)
n1/d1 * n2/d2 = (n1*n2)/(d1*d2)
(n1/d1) / (n2/d2) = (n1*d2)/(d1*n2)

n1/d1 == n2/d2 if and only if n1*d2 == n2*d1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets write the rational number class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class RationalNumber:
    """
    Rational Numbers with support for arthmetic operations.

        &amp;gt;&amp;gt;&amp;gt; a = RationalNumber(1, 2)
        &amp;gt;&amp;gt;&amp;gt; b = RationalNumber(1, 3)
        &amp;gt;&amp;gt;&amp;gt; a + b
        5/6
        &amp;gt;&amp;gt;&amp;gt; a - b
        1/6
        &amp;gt;&amp;gt;&amp;gt; a * b
        1/6
        &amp;gt;&amp;gt;&amp;gt; a/b
        3/2
    """
    def __init__(self, numerator, denominator=1):
        self.n = numerator
        self.d = denominator

    def __add__(self, other):
        if not isinstance(other, RationalNumber):
            other = RationalNumber(other)

        n = self.n * other.d + self.d * other.n
        d = self.d * other.d
        return RationalNumber(n, d)

    def __sub__(self, other):
        if not isinstance(other, RationalNumber):
            other = RationalNumber(other)

        n1, d1 = self.n, self.d
        n2, d2 = other.n, other.d
        return RationalNumber(n1*d2 - n2*d1, d1*d2)

    def __mul__(self, other):
        if not isinstance(other, RationalNumber):
            other = RationalNumber(other)

        n1, d1 = self.n, self.d
        n2, d2 = other.n, other.d
        return RationalNumber(n1*n2, d1*d2)

    def __div__(self, other):
        if not isinstance(other, RationalNumber):
            other = RationalNumber(other)

        n1, d1 = self.n, self.d
        n2, d2 = other.n, other.d
        return RationalNumber(n1*d2, d1*n2)

    def __str__(self):
        return "%s/%s" % (self.n, self.d)

    __repr__ = __str__
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4.5. Errors and Exceptions&lt;/strong&gt;&lt;br&gt;
We’ve already seen exceptions in various places. Python gives &lt;code&gt;NameError&lt;/code&gt; when we try to use a variable that is not defined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; foo
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
NameError: name 'foo' is not defined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;try adding a string to an integer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; "foo" + 2
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
TypeError: cannot concatenate 'str' and 'int' objects
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;try dividing a number by 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 2/0
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
ZeroDivisionError: integer division or modulo by zero
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or, try opening a file that is not there:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; open("not-there.txt")
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
IOError: [Errno 2] No such file or directory: 'not-there.txt'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python raises exception in case errors. We can write programs to handle such errors. We too can raise exceptions when an error case in encountered.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Exceptions&lt;/code&gt; are handled by using the try-except statements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def main():
    filename = sys.argv[1]
    try:
        for row in parse_csv(filename):
            print row
    except IOError:
        print("The given file doesn't exist: ", filename, file=sys.stderr)
        sys.exit(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example prints an error message and exits with an error status when an IOError is encountered.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;except&lt;/em&gt; statement can be written in multiple ways:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# catch all exceptions
try:
    ...
except:

# catch just one exception
try:
    ...
except IOError:
    ...

# catch one exception, but provide the exception object
try:
    ...
except IOError as e:
    ...

# catch more than one exception
try:
    ...
except (IOError, ValueError) as e:
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is possible to have more than one except statements with one try.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    ...
except IOError as e:
    print("Unable to open the file (%s): %s" % (str(e), filename), file=sys.stderr)
    sys.exit(1)
except FormatError as e:
    print("File is badly formatted (%s): %s" % (str(e), filename), file=sys.stderr)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;try&lt;/em&gt; statement can have an optional &lt;em&gt;else&lt;/em&gt; clause, which is executed only if no exception is raised in the try-block.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    ...
except IOError as e:
    print("Unable to open the file (%s): %s" % (str(e), filename), file=sys.stderr)
    sys.exit(1)
else:
    print("successfully opened the file", filename)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There can be an optional &lt;em&gt;else&lt;/em&gt; clause with a try statement, which is executed irrespective of whether or not exception has occured.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    ...
except IOError as e:
    print("Unable to open the file (%s): %s" % (str(e), filename), file=sys.stderr)
    sys.exit(1)
finally:
    delete_temp_files()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Exception is raised using the raised keyword.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;raise Exception("error message")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All the exceptions are extended from the built-in &lt;em&gt;Exception&lt;/em&gt; class.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;class ParseError(Exception):&lt;/code&gt;&lt;br&gt;
pass&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    print "a"
except:
    print "b"
else:
    print "c"
finally:
    print "d"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    print("a")
    raise Exception("doom")
except:
    print("b")
else:
    print("c")
finally:
    print("d")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def f():
    try:
        print("a")
        return
    except:
        print("b")
    else:
        print("c")
    finally:
        print("d")

f()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
    <item>
      <title>Modules</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Wed, 06 May 2020 13:55:34 +0000</pubDate>
      <link>https://dev.to/estherwavinya/modules-4mb1</link>
      <guid>https://dev.to/estherwavinya/modules-4mb1</guid>
      <description>&lt;p&gt;&lt;strong&gt;3. Modules&lt;/strong&gt;&lt;br&gt;
Modules are reusable libraries of code in Python. Python comes with many standard library modules.&lt;br&gt;
A module is imported using the &lt;code&gt;import&lt;/code&gt; statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import time
&amp;gt;&amp;gt;&amp;gt; print(time.asctime())
'Fri Mar 30 12:59:21 2012'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we’ve imported the time module and called the &lt;code&gt;asctime&lt;/code&gt; function from that module, which returns current time as a string.&lt;/p&gt;

&lt;p&gt;There is also another way to use the import statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; from time import asctime
&amp;gt;&amp;gt;&amp;gt; asctime()
'WED May 06 16:50:37 2020'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we just imported the &lt;code&gt;asctime&lt;/code&gt; function from the time module.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;pydoc&lt;/code&gt; command provides help on any module or a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pydoc time
Help on module time:

NAME
    time - This module provides various functions to manipulate time values.
...

$ pydoc time.asctime
Help on built-in function asctime in time:

time.asctime = asctime(...)
    asctime([tuple]) -&amp;gt; string
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On Windows, the &lt;code&gt;pydoc&lt;/code&gt; command is not available. The work-around is to use, the built-in help function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; help('time')
Help on module time:

NAME
    time - This module provides various functions to manipulate time values.
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Writing our own modules is very simple.&lt;/p&gt;

&lt;p&gt;For example, create a file called &lt;em&gt;num.py&lt;/em&gt; with the following content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def square(x):
    return x * x

def cube(x):
    return x * x * x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now open Python interpreter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import num
&amp;gt;&amp;gt;&amp;gt; num.square(3)
9
&amp;gt;&amp;gt;&amp;gt; num.cube(3)
27
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's all we’ve written a python library.&lt;/p&gt;

&lt;p&gt;Try &lt;em&gt;pydoc num&lt;/em&gt; (&lt;em&gt;pydoc.bat numbers&lt;/em&gt; on Windows) to see documentation for this numbers modules. It won’t have any documentation as we haven’t provided anything yet.&lt;/p&gt;

&lt;p&gt;In Python, it is possible to associate documentation for each module, function using docstrings. &lt;em&gt;Docstrings&lt;/em&gt; are strings written at the top of the module or at the beginning of a function.&lt;/p&gt;

&lt;p&gt;Lets try to document our &lt;code&gt;num&lt;/code&gt; module by changing the contents of &lt;em&gt;num.py&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""The num module provides utilties to work on numbers.

Current it provides square and cube.
"""

def square(x):
    """Computes square of a number."""
    return x * x

def cube(x):
    """Computes cube of a number."""
    return x * x
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The pydoc command will now show us the doumentation nicely formatted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Help on module num:

NAME
    num - The num module provides utilties to work on numbers.

FILE
    /Users/anand/num.py

DESCRIPTION
    Current it provides square and cube.

FUNCTIONS
    cube(x)
        Computes cube of a number.

    square(x)
        Computes square of a number.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Under the hood, python stores the documentation as a special field called &lt;em&gt;&lt;strong&gt;doc&lt;/strong&gt;&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; import os
&amp;gt;&amp;gt;&amp;gt; print(os.getcwd.__doc__)
getcwd() -&amp;gt; path

Return a string representing the current working directory.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3.1. Standard Library&lt;/strong&gt;&lt;br&gt;
Python comes with many standard library modules. Lets look at some of the most commonly used ones.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.1.1. os module&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;os&lt;/code&gt; and &lt;code&gt;os.path&lt;/code&gt; modules provides functionality to work with files, directories etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; Write a program to list all files in the given directory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; Write a program &lt;code&gt;extcount.py&lt;/code&gt; to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python extcount.py src/
14 py
4 txt
1 csv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; Write a program to list all the files in the given directory along with their length and last modification time. The output should contain one line for each file containing filename, length and modification date separated by tabs.&lt;/p&gt;

&lt;p&gt;Hint: see help for &lt;code&gt;os.stat&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; Write a program to print directory tree. The program should take path of a directory as argument and print all the files in it recursively as a tree.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python dirtree.py foo
foo
|-- a.txt
|-- b.txt
|-- code
|   |-- a.py
|   |-- b.py
|   |-- docs
|   |   |-- a.txt
|   |   \-- b.txt
|   \-- x.py
\-- z.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3.1.2. urllib module&lt;/strong&gt;&lt;br&gt;
The &lt;em&gt;urllib&lt;/em&gt; module provides functionality to download webpages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; from urllib.request import urlopen
&amp;gt;&amp;gt;&amp;gt; response = urlopen("http://python.org/")
&amp;gt;&amp;gt;&amp;gt; print(response.headers)
Date: Fri, 30 Mar 2012 09:24:55 GMT
Server: Apache/2.2.16 (Debian)
Last-Modified: Fri, 30 Mar 2012 08:42:25 GMT
ETag: "105800d-4b7b-4bc71d1db9e40"
Accept-Ranges: bytes
Content-Length: 19323
Connection: close
Content-Type: text/html
X-Pad: avoid browser bug

&amp;gt;&amp;gt;&amp;gt; response.header['Content-Type']
'text/html'

&amp;gt;&amp;gt;&amp;gt; content = request.read()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 5:&lt;/strong&gt; Write a program wget.py to download a given URL. The program should accept a URL as argument, download it and save it with the basename of the URL. If the URL ends with a /, consider the basename as index.html.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python wget.py http://docs.python.org/tutorial/interpreter.html
saving http://docs.python.org/tutorial/interpreter.html as interpreter.html.

$ python wget.py http://docs.python.org/tutorial/
saving http://docs.python.org/tutorial/ as index.html.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3.1.3. re module&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Problem 6:&lt;/strong&gt; Write a program &lt;em&gt;antihtml.py&lt;/em&gt; that takes a URL as argument, downloads the html from web and print it after stripping html tags.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python antihtml.py index.html
...
The Python interpreter is usually installed as /usr/local/bin/python on
those machines where it is available; putting /usr/local/bin in your
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 7:&lt;/strong&gt; Write a function &lt;em&gt;make_slug&lt;/em&gt; that takes a name converts it into a slug. A &lt;code&gt;slug&lt;/code&gt; is a string where spaces and special characters are replaced by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphens at the beginning and end of the slug.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; make_slug("hello world")
'hello-world'
&amp;gt;&amp;gt;&amp;gt; make_slug("hello  world!")
'hello-world'
&amp;gt;&amp;gt;&amp;gt; make_slug(" --hello-  world--")
'hello-world'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 8:&lt;/strong&gt; Write a program &lt;em&gt;links.py&lt;/em&gt; that takes URL of a webpage as argument and prints all the URLs linked from that webpage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 9:&lt;/strong&gt; Write a regular expression to validate a phone number.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.1.4. json module&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Problem 10:&lt;/strong&gt; Write a program &lt;em&gt;myip.py&lt;/em&gt; to print the external IP address of the machine. Use the response from &lt;code&gt;http://httpbin.org/&lt;/code&gt; get and read the IP address from there. The program should print only the IP address and nothing else.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.1.5. zipfile module&lt;/strong&gt;&lt;br&gt;
The &lt;em&gt;zipfile&lt;/em&gt; module provides interface to read and write zip files.&lt;/p&gt;

&lt;p&gt;Here are some examples to demonstate the power of &lt;em&gt;zipfile&lt;/em&gt; module.&lt;/p&gt;

&lt;p&gt;The following example prints names of all the files in a zip archive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import zipfile
z = zipfile.ZipFile("a.zip")
for name in z.namelist():
    print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following example prints each file in the zip archive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import zipfile
z = zipfile.ZipFile("a.zip")
for name in z.namelist():
    print()
    print("FILE:", name)
    print()
    print(z.read(name))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 11:&lt;/strong&gt; Write a python program &lt;em&gt;zip.py&lt;/em&gt; to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python zip.py foo.zip file1.txt file2.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 12:&lt;/strong&gt; Write a program &lt;em&gt;mydoc.py&lt;/em&gt; to implement the functionality of pydoc. The program should take the module name as argument and print documentation for the module and each of the functions defined in that module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python mydoc.py os
Help on module os:

DESCRIPTION

os - OS routines for Mac, NT, or Posix depending on what system we're on.
...

FUNCTIONS

getcwd()
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hints:&lt;br&gt;
-The dir function to get all entries of a module&lt;/p&gt;

&lt;p&gt;-The inspect.isfunction function can be used to test if given object is a function&lt;/p&gt;

&lt;p&gt;-x.&lt;strong&gt;doc&lt;/strong&gt; gives the docstring for x.&lt;/p&gt;

&lt;p&gt;-The &lt;strong&gt;import&lt;/strong&gt; function can be used to import a module by name&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.2. Installing third-party modules&lt;/strong&gt;&lt;br&gt;
PyPI, The Python Package Index maintains the list of Python packages available. The third-party module developers usually register at PyPI and uploads their packages there.&lt;/p&gt;

&lt;p&gt;The standard way to installing a python module is using &lt;code&gt;pip&lt;/code&gt; or &lt;code&gt;easy_install&lt;/code&gt;. Pip is more modern and preferred.&lt;/p&gt;

&lt;p&gt;Lets start with installing &lt;code&gt;easy_install&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Download the easy_install install script &lt;em&gt;ez_setup.py&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Run it using Python.&lt;/p&gt;

&lt;p&gt;That will install &lt;code&gt;easy_install&lt;/code&gt;, the script used to install third-party python packages.&lt;/p&gt;

&lt;p&gt;Before installing new packages, lets understand how to manage virtual environments for installing python packages.&lt;/p&gt;

&lt;p&gt;Earlier the only way of installing python packages was system wide. When used this way, packages installed for one project can conflict with other and create trouble. So people invented a way to create isolated Python environment to install packages. This tool is called &lt;code&gt;virtualenv&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To install &lt;code&gt;virtualenv&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ easy_install virtualenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Installing virtualenv also installs the &lt;em&gt;pip&lt;/em&gt; command, a better replace for &lt;em&gt;easy_install&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Once it is installed, create a new virtual env by running the &lt;code&gt;virtualenv&lt;/code&gt; command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ virtualenv testenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to switch to that env.&lt;/p&gt;

&lt;p&gt;On UNIX/Mac OS X:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ source testenv/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On Windows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; testenv\Scripts\activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the virtualenv &lt;em&gt;testenv&lt;/em&gt; is activated.&lt;/p&gt;

&lt;p&gt;Now all the packages installed will be limited to this virtualenv. Lets try to install a third-party package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pip install tablib
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This installs a third-party library called &lt;code&gt;tablib&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;tablib&lt;/code&gt; library is a small little library to work with tabular data and write csv and Excel files.&lt;/p&gt;

&lt;p&gt;Here is a simple example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# create a dataset
data = tablib.Dataset()

# Add rows
data.append(["A", 1])
data.append(["B", 2])
data.append(["C", 3])

# save as csv
with open('test.csv', 'wb') as f:
    f.write(data.csv)

# save as Excel
with open('test.xls', 'wb') as f:
    f.write(data.xls)

# save as Excel 07+
with open('test.xlsx', 'wb') as f:
    f.write(data.xlsx)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is even possible to create multi-sheet excel files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sheet1 = tablib.Dataset()
sheet1.append(["A1", 1])
sheet1.append(["A2", 2])

sheet2 = tablib.Dataset()
sheet2.append(["B1", 1])
sheet2.append(["B2", 2])


book = tablib.Databook([data1, data2])
with open('book.xlsx', 'wb') as f:
    f.write(book.xlsx)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 13:&lt;/strong&gt; Write a program &lt;code&gt;csv2xls.py&lt;/code&gt; that reads a csv file and exports it as Excel file. The program should take two arguments. The name of the csv file to read as first argument and the name of the Excel file to write as the second argument.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 14:&lt;/strong&gt; Create a new virtualenv and install BeautifulSoup. BeautifulSoup is very good library for parsing HTML. Try using it to extract all HTML links from a webpage.&lt;/p&gt;

&lt;p&gt;Read the &lt;a href="https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html" rel="noopener noreferrer"&gt;BeautifulSoup documentation&lt;/a&gt; to get started.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
    <item>
      <title>Working with Data</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Wed, 06 May 2020 13:08:53 +0000</pubDate>
      <link>https://dev.to/estherwavinya/working-with-data-5ec0</link>
      <guid>https://dev.to/estherwavinya/working-with-data-5ec0</guid>
      <description>&lt;p&gt;&lt;strong&gt;2. Working with Data&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;2.1. Lists&lt;/strong&gt;&lt;br&gt;
We’ve already seen quick introduction to lists in the previous article.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; [1, 2, 3, 4]
[1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; ["hello", "world"]
["hello", "world"]
&amp;gt;&amp;gt;&amp;gt; [0, 1.5, "hello"]
[0, 1.5, "hello"]
&amp;gt;&amp;gt;&amp;gt; [0, 1.5, "hello"]
[0, 1.5, "hello"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A List can contain another list as member.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [1, 2]
&amp;gt;&amp;gt;&amp;gt; b = [1.5, 2, a]
&amp;gt;&amp;gt;&amp;gt; b
[1.5, 2, [1, 2]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;range&lt;/code&gt; can be used to create a sequence of consecutive integers.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;range&lt;/code&gt; function returns a special range object that behaves like a list. To get a real list from it, you can use the list function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = range(1, 4)
&amp;gt;&amp;gt;&amp;gt; x
range(1, 4)
&amp;gt;&amp;gt;&amp;gt; x[0]
1
&amp;gt;&amp;gt;&amp;gt; len(x)
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;len&lt;/code&gt; can be used to find the length of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; len(a)
4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;+&lt;/code&gt; and &lt;code&gt;*&lt;/code&gt; operators work even on lists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [1, 2, 3]
&amp;gt;&amp;gt;&amp;gt; b = [4, 5]
&amp;gt;&amp;gt;&amp;gt; a + b
[1, 2, 3, 4, 5]
&amp;gt;&amp;gt;&amp;gt; b * 3
[4, 5, 4, 5, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;List can be indexed to get individual entries. Value of index can go from 0 to (length of list - 1).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2]
&amp;gt;&amp;gt;&amp;gt; x[0]
1
&amp;gt;&amp;gt;&amp;gt; x[1]
2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a wrong index is used, python gives an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; x[6]
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in ?
IndexError: list index out of range
Negative indices can be used to index the list from right.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; x[-1]
4
&amp;gt;&amp;gt;&amp;gt; x [-2]
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use list slicing to get part of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; x[0:2]
[1, 2]
&amp;gt;&amp;gt;&amp;gt; x[1:4]
[2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even negative indices can be used in slicing. For example, the following examples strips the last element from the list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x[0:-1]
[1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the list being sliced.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; a[:2]
[1, 2]
&amp;gt;&amp;gt;&amp;gt; a[2:]
[3, 4]
&amp;gt;&amp;gt;&amp;gt; a[:]
[1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An optional third index can be used to specify the increment, which defaults to 1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = range(10)
&amp;gt;&amp;gt;&amp;gt; x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
&amp;gt;&amp;gt;&amp;gt; x[0:6:2]
[0, 2, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can reverse a list, just by providing -1 for increment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;List members can be modified by assignment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; x[1] = 5
&amp;gt;&amp;gt;&amp;gt; x
[1, 5, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Presence of a key in a list can be tested using &lt;code&gt;in&lt;/code&gt; operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; 2 in x
True
&amp;gt;&amp;gt;&amp;gt; 10 in x
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Values can be appended to a list by calling &lt;code&gt;append&lt;/code&gt; method on list. A method is just like a function, but it is associated with an object and can access that object when it is called. We will learn more about methods when we study classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [1, 2]
&amp;gt;&amp;gt;&amp;gt; a.append(3)
&amp;gt;&amp;gt;&amp;gt; a
[1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = [0, 1, [2]]
x[2][0] = 3
print(x)
x[2].append(4)
print(x)
x[2] = 2
print(x)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.1.1. The for Statement&lt;/strong&gt;&lt;br&gt;
Python provides &lt;code&gt;for&lt;/code&gt; statement to iterate over a list. A &lt;code&gt;for&lt;/code&gt; statement executes the specified block of code for every element in a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for x in [1, 2, 3, 4]:
    print(x)

for i  in range(10):
   print(i, i*i, i*i*i)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;zip&lt;/code&gt; takes two lists and returns list of pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; zip(["a", "b", "c"], [1, 2, 3])
[('a', 1), ('b', 2), ('c', 3)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is handy when we want to iterate over two lists together.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ["a", "b", "c"]
values = [1, 2, 3]
for name, value in zip(names, values):
    print(name, value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; Python has a built-in function sum to find &lt;code&gt;sum&lt;/code&gt; of all elements of a list. Provide an implementation for &lt;code&gt;sum&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; sum([1, 2, 3])
&amp;gt;&amp;gt;&amp;gt; 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; What happens when the above &lt;code&gt;sum&lt;/code&gt; function is called with a list of strings? Can you make your &lt;code&gt;sum&lt;/code&gt; function work for a list of strings as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; sum(["hello", "world"])
"helloworld"
&amp;gt;&amp;gt;&amp;gt; sum(["aa", "bb", "cc"])
"aabbcc"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; Implement a function &lt;code&gt;product&lt;/code&gt;, to compute product of a list of numbers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; product([1, 2, 3])
6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 5:&lt;/strong&gt; Write a function &lt;code&gt;factorial&lt;/code&gt; to compute factorial of a number. Can you use the &lt;code&gt;product&lt;/code&gt; function defined in the previous example to compute factorial?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; factorial(4)
24
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 6:&lt;/strong&gt; Write a function &lt;code&gt;reverse&lt;/code&gt; to reverse a list. Can you do this without using list slicing?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; reverse([1, 2, 3, 4])
[4, 3, 2, 1]
&amp;gt;&amp;gt;&amp;gt; reverse(reverse([1, 2, 3, 4]))
[1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 7:&lt;/strong&gt; Python has built-in functions &lt;code&gt;min&lt;/code&gt; and &lt;code&gt;max&lt;/code&gt; to compute minimum and maximum of a given list. Provide an implementation for these functions. What happens when you call your &lt;code&gt;min&lt;/code&gt; and &lt;code&gt;max&lt;/code&gt; functions with a list of strings?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 8:&lt;/strong&gt; Cumulative sum of a list &lt;code&gt;[a, b, c, ...]&lt;/code&gt; is defined as &lt;code&gt;[a, a+b, a+b+c, ...]&lt;/code&gt;. Write a function &lt;code&gt;cumulative_sum&lt;/code&gt; to compute cumulative sum of a list. Does your implementation work for a list of strings?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; cumulative_sum([1, 2, 3, 4])
[1, 3, 6, 10]
&amp;gt;&amp;gt;&amp;gt; cumulative_sum([4, 3, 2, 1])
[4, 7, 9, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 9:&lt;/strong&gt; Write a function &lt;code&gt;cumulative_product&lt;/code&gt; to compute cumulative product of a list of numbers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; cumulative_product([1, 2, 3, 4])
[1, 2, 6, 24]
&amp;gt;&amp;gt;&amp;gt; cumulative_product([4, 3, 2, 1])
[4, 12, 24, 24]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 10:&lt;/strong&gt; Write a function &lt;code&gt;unique&lt;/code&gt; to find all the unique elements of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; unique([1, 2, 1, 3, 2, 5])
[1, 2, 3, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 11:&lt;/strong&gt; Write a function &lt;code&gt;dups&lt;/code&gt; to find all duplicates in the list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; dups([1, 2, 1, 3, 2, 5])
[1, 2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 12:&lt;/strong&gt; Write a function &lt;code&gt;group(list, size)&lt;/code&gt; that take a list and splits into smaller lists of given size.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
&amp;gt;&amp;gt;&amp;gt; group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.1.2. Sorting Lists&lt;/strong&gt;&lt;br&gt;
The sort method sorts a list in place.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [2, 10, 4, 3, 7]
&amp;gt;&amp;gt;&amp;gt; a.sort()
&amp;gt;&amp;gt;&amp;gt; a
[2, 3, 4, 7 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function sorted returns a new &lt;code&gt;sorted&lt;/code&gt; list without modifying the source list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [4, 3, 5, 9, 2]
&amp;gt;&amp;gt;&amp;gt; sorted(a)
[2, 3, 4, 5, 9]
&amp;gt;&amp;gt;&amp;gt; a
[4, 3, 5, 9, 2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The behavior of &lt;code&gt;sort&lt;/code&gt; method and &lt;code&gt;sorted&lt;/code&gt; function is exactly same except that sorted returns a new list instead of modifying the given list.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;sort&lt;/code&gt; method works even when the list has different types of objects and even lists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = ["hello", 1, "world", 45, 2]
&amp;gt;&amp;gt;&amp;gt; a.sort()
&amp;gt;&amp;gt;&amp;gt; a
[1, 2, 45, 'hello', 'world']
&amp;gt;&amp;gt;&amp;gt; a = [[2, 3], [1, 6]]
&amp;gt;&amp;gt;&amp;gt; a.sort()
&amp;gt;&amp;gt;&amp;gt; a
[[1, 6], [2, 3]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can optionally specify a function as sort key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = [[2, 3], [4, 6], [6, 1]]
&amp;gt;&amp;gt;&amp;gt; a.sort(key=lambda x: x[1])
&amp;gt;&amp;gt;&amp;gt; a
[[6, 1], [2, 3],  [4 6]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sorts all the elements of the list based on the value of second element of each entry.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 13:&lt;/strong&gt; Write a function &lt;code&gt;lensort&lt;/code&gt; to sort a list of strings based on length.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; lensort(['python', 'perl', 'java', 'c', 'haskell', 'ruby'])
['c', 'perl', 'java', 'ruby', 'python', 'haskell']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 14:&lt;/strong&gt; Improve the unique function written in previous problems to take an optional key function as argument and use the return value of the key function to check for uniqueness.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; unique(["python", "java", "Python", "Java"], key=lambda s: s.lower())
["python", "java"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.2. Tuples&lt;/strong&gt;&lt;br&gt;
Tuple is a sequence type just like &lt;code&gt;list&lt;/code&gt;, but it is immutable. A tuple consists of a number of values separated by commas.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = (1, 2, 3)
&amp;gt;&amp;gt;&amp;gt; a[0]
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The enclosing braces are optional.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = 1, 2, 3
&amp;gt;&amp;gt;&amp;gt; a[0]
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;len&lt;/code&gt; and slicing works on tuples too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; len(a)
3
&amp;gt;&amp;gt;&amp;gt; a[1:]
2, 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since parenthesis are also used for grouping, tuples with a single value are represented with an additional comma.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = (1)
&amp;gt;&amp;gt; a
1
&amp;gt;&amp;gt;&amp;gt; b = (1,)
&amp;gt;&amp;gt;&amp;gt; b
(1,)
&amp;gt;&amp;gt;&amp;gt; b[0]
1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.3. Sets&lt;/strong&gt;&lt;br&gt;
Sets are unordered collection of unique elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = set([3, 1, 2, 1])
set([1, 2, 3])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python 2.7 introduced a new way of writing sets.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = {3, 1, 2, 1}
set([1, 2, 3])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;New elements can be added to a set using the add method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = set([1, 2, 3])
&amp;gt;&amp;gt;&amp;gt; x.add(4)
&amp;gt;&amp;gt;&amp;gt; x
set([1, 2, 3, 4])
```


Just like lists, the existence of an element can be checked using the `in` operator. However, this operation is faster in sets compared to lists.


```
&amp;gt;&amp;gt;&amp;gt; x = set([1, 2, 3])
&amp;gt;&amp;gt;&amp;gt; 1 in x
True
&amp;gt;&amp;gt;&amp;gt; 5 in x
False
```


**Problem 15:** Reimplement the `unique` function implemented in the earlier examples using sets.

**2.4. Strings**
Strings also behave like lists in many ways. Length of a string can be found using built-in function `len`.


```
&amp;gt;&amp;gt;&amp;gt; len("abrakadabra")
11
```


Indexing and slicing on strings behave similar to that of lists.


```
&amp;gt;&amp;gt;&amp;gt; a = "helloworld"
&amp;gt;&amp;gt;&amp;gt; a[1]
'e'
&amp;gt;&amp;gt;&amp;gt; a[-2]
'l'
&amp;gt;&amp;gt;&amp;gt; a[1:5]
"ello"
&amp;gt;&amp;gt;&amp;gt; a[:5]
"hello"
&amp;gt;&amp;gt;&amp;gt; a[5:]
"world"
&amp;gt;&amp;gt;&amp;gt; a[-2:]
'ld'
&amp;gt;&amp;gt;&amp;gt; a[:-2]
'hellowor'
&amp;gt;&amp;gt;&amp;gt; a[::-1]
'dlrowolleh'
```


The `in` operator can be used to check if a string is present in another string.


```
&amp;gt;&amp;gt;&amp;gt; 'hell' in 'hello'
True
&amp;gt;&amp;gt;&amp;gt; 'full' in 'hello'
False
&amp;gt;&amp;gt;&amp;gt; 'el' in 'hello'
True
```


There are many useful methods on strings.

The `split` method splits a string using a delimiter. If no delimiter is specified, it uses any whitespace char as delimiter.


```
&amp;gt;&amp;gt;&amp;gt; "hello world".split()
['hello', 'world']
&amp;gt;&amp;gt;&amp;gt; "a,b,c".split(',')
['a', 'b', 'c']
```


The `join` method joins a list of strings.


```
&amp;gt;&amp;gt;&amp;gt; " ".join(['hello', 'world'])
'hello world'
&amp;gt;&amp;gt;&amp;gt; ','.join(['a', 'b', 'c'])
```


The `strip` method returns a copy of the given string with leading and trailing whitespace removed. Optionally a string can be passed as argument to remove characters from that string instead of whitespace.


```
&amp;gt;&amp;gt;&amp;gt; ' hello world\n'.strip()
'hello world'
&amp;gt;&amp;gt;&amp;gt; 'abcdefgh'.strip('abdh')
'cdefg'
```


Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.


```
&amp;gt;&amp;gt;&amp;gt; a = 'hello'
&amp;gt;&amp;gt;&amp;gt; b = 'python'
&amp;gt;&amp;gt;&amp;gt; "%s %s" % (a, b)
'hello python'
&amp;gt;&amp;gt;&amp;gt; 'Chapter %d: %s' % (2, 'Data Structures')
```


**2.5. Working With Files**
Python provides a built-in function `open` to open a file, which returns a file object.


```
f = open('foo.txt', 'r') # open a file in read mode
f = open('foo.txt', 'w') # open a file in write mode
f = open('foo.txt', 'a') # open a file in append mode
```


The second argument to `open` is optional, which defaults to `'r'` when not specified.

Unix does not distinguish binary files from text files but windows does. On windows `'rb'`, `'wb'`, `'ab'` should be used to open a binary file in read, write and append mode respectively.

Easiest way to read contents of a file is by using the `read` method.


```
&amp;gt;&amp;gt;&amp;gt; open('foo.txt').read()
'first line\nsecond line\nlast line\n'
```


Contents of a file can be read line-wise using `readline` and `readlines` methods. The `readline` method returns empty string when there is nothing more to read in a file.


```
&amp;gt;&amp;gt;&amp;gt; open('foo.txt').readlines()
['first line\n', 'second line\n', 'last line\n']
&amp;gt;&amp;gt;&amp;gt; f = open('foo.txt')
&amp;gt;&amp;gt;&amp;gt; f.readline()
'first line\n'
&amp;gt;&amp;gt;&amp;gt; f.readline()
'second line\n'
&amp;gt;&amp;gt;&amp;gt; f.readline()
'last line\n'
&amp;gt;&amp;gt;&amp;gt; f.readline()
''
```


The `write` method is used to write data to a file opened in write or append mode.


```
&amp;gt;&amp;gt;&amp;gt; f = open('foo.txt', 'w')
&amp;gt;&amp;gt;&amp;gt; f.write('a\nb\nc')
&amp;gt;&amp;gt;&amp;gt; f.close()

&amp;gt;&amp;gt;&amp;gt; f.open('foo.txt', 'a')
&amp;gt;&amp;gt;&amp;gt; f.write('d\n')
&amp;gt;&amp;gt;&amp;gt; f.close()
```


The `writelines` method is convenient to use when the data is available as a list of lines.


```
&amp;gt;&amp;gt;&amp;gt; f = open('foo.txt')
&amp;gt;&amp;gt;&amp;gt; f.writelines(['a\n', 'b\n', 'c\n'])
&amp;gt;&amp;gt;&amp;gt; f.close()
```


**2.5.1. Example: Word Count**
Lets try to compute the number of characters, words and lines in a file.

Number of characters in a file is same as the length of its contents.


```
def charcount(filename):
    return len(open(filename).read())
```


Number of words in a file can be found by splitting the contents of the file.


```
def wordcount(filename):
    return len(open(filename).read().split())
```


Number of lines in a file can be found from readlines method.


```
def linecount(filename):
    return len(open(filename).readlines())
```


**Problem 17:** Write a program `reverse.py` to print lines of a file in reverse order.


```
$ cat she.txt
She sells seashells on the seashore;
The shells that she sells are seashells I'm sure.
So if she sells seashells on the seashore,
I'm sure that the shells are seashore shells.

$ python reverse.py she.txt
I'm sure that the shells are seashore shells.
So if she sells seashells on the seashore,
The shells that she sells are seashells I'm sure.
She sells seashells on the seashore;
```


**Problem 18:** Write a program to print each line of a file in reverse order.

**Problem 19:** Implement unix commands `head` and `tail`. The `head` and `tail` commands take a file as argument and prints its first and last 10 lines of the file respectively.

**Problem 20:** Implement unix command `grep`. The `grep` command takes a string and a file as arguments and prints all lines in the file which contain the specified string.


```
$ python grep.py she.txt sure
The shells that she sells are seashells I'm sure.
I'm sure that the shells are seashore shells.
```


**Problem 21:** Write a program `wrap.py` that takes filename and width as aruguments and wraps the lines longer than `width`.


```
$ python wrap.py she.txt 30
I'm sure that the shells are s
eashore shells.
So if she sells seashells on t
he seashore,
The shells that she sells are
seashells I'm sure.
She sells seashells on the sea
shore;
```


**Problem 22:** The above wrap program is not so nice because it is breaking the line at middle of any word. Can you write a new program `wordwrap.py` that works like `wrap.py`, but breaks the line only at the word boundaries?


```
$ python wordwrap.py she.txt 30
I'm sure that the shells are
seashore shells.
So if she sells seashells on
the seashore,
The shells that she sells are
seashells I'm sure.
She sells seashells on the
seashore;
```


**Problem 23:** Write a program `center_align.py` to center align all lines in the given file.


```
$ python center_align.py she.txt
  I'm sure that the shells are seashore shells.
    So if she sells seashells on the seashore,
The shells that she sells are seashells I'm sure.
       She sells seashells on the seashore;
```


**2.6. List Comprehensions**
List Comprehensions provide a concise way of creating lists. Many times a complex task can be modelled in a single line.

Here are some simple examples for transforming a list.


```
&amp;gt;&amp;gt;&amp;gt; a = range(10)
&amp;gt;&amp;gt;&amp;gt; a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
&amp;gt;&amp;gt;&amp;gt; [x for x in a]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
&amp;gt;&amp;gt;&amp;gt; [x*x for x in a]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
&amp;gt;&amp;gt;&amp;gt; [x+1 for x in a]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```


It is also possible to filter a list using `if` inside a list comprehension.


```
&amp;gt;&amp;gt;&amp;gt; a = range(10)
&amp;gt;&amp;gt;&amp;gt; [x for x in a if x % 2 == 0]
[0, 2, 4, 6, 8]
&amp;gt;&amp;gt;&amp;gt; [x*x for x in a if x%2 == 0]
[0, 4, 8, 36, 64]
```


It is possible to iterate over multiple lists using the built-in function `zip`.


```
&amp;gt;&amp;gt;&amp;gt; a = [1, 2, 3, 4]
&amp;gt;&amp;gt;&amp;gt; b = [2, 3, 5, 7]
&amp;gt;&amp;gt;&amp;gt; zip(a, b)
[(1, 2), (2, 3), (3, 5), (4, 7)]
&amp;gt;&amp;gt;&amp;gt; [x+y for x, y in zip(a, b)]
[3, 5, 8, 11]
```


we can use multiple `for` clauses in single list comprehension.


```
&amp;gt;&amp;gt;&amp;gt; [(x, y) for x in range(5) for y in range(5) if (x+y)%2 == 0]
[(0, 0), (0, 2), (0, 4), (1, 1), (1, 3), (2, 0), (2, 2), (2, 4), (3, 1), (3, 3), (4, 0), (4, 2), (4, 4)]

&amp;gt;&amp;gt;&amp;gt; [(x, y) for x in range(5) for y in range(5) if (x+y)%2 == 0 and x != y]
[(0, 2), (0, 4), (1, 3), (2, 0), (2, 4), (3, 1), (4, 0), (4, 2)]

&amp;gt;&amp;gt;&amp;gt; [(x, y) for x in range(5) for y in range(x) if (x+y)%2 == 0]
[(2, 0), (3, 1), (4, 0), (4, 2)]
```


The following example finds all Pythagorean triplets using numbers below 25. `(x, y, z)` is a called pythagorean triplet if `x*x + y*y == z*z`.


```
&amp;gt;&amp;gt;&amp;gt; n = 25
&amp;gt;&amp;gt;&amp;gt; [(x, y, z) for x in range(1, n) for y in range(x, n) for z in range(y, n) if x*x + y*y == z*z]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
```


**Problem 24:** Provide an implementation for zip function using list comprehensions.


```
&amp;gt;&amp;gt;&amp;gt; zip([1, 2, 3], ["a", "b", "c"])
[(1, "a"), (2, "b"), (3, "c")]
```


**Problem 25:** Python provides a built-in function `map` that applies a function to each element of a list. Provide an implementation for map using list comprehensions.


```
&amp;gt;&amp;gt;&amp;gt; def square(x): return x * x
...
&amp;gt;&amp;gt;&amp;gt; map(square, range(5))
[0, 1, 4, 9, 16]
```


**Problem 26:** Python provides a built-in function `filter(f, a)` that returns items of the list a for which `f(item)` returns true. Provide an implementation for `filter` using list comprehensions.


```
&amp;gt;&amp;gt;&amp;gt; def even(x): return x %2 == 0
...
&amp;gt;&amp;gt;&amp;gt; filter(even, range(10))
[0, 2, 4, 6, 8]
```


**Problem 27:** Write a function `triplets` that takes a number `n` as argument and returns a list of triplets such that sum of first two elements of the triplet equals the third element using numbers below n. Please note that `(a, b, c)` and `(b, a, c)` represent same triplet.


```
&amp;gt;&amp;gt;&amp;gt; triplets(5)
[(1, 1, 2), (1, 2, 3), (1, 3, 4), (2, 2, 4)]
```


**Problem 28:** Write a function `enumerate` that takes a list and returns a list of tuples containing `(index,item)` for each item in the list.


```
&amp;gt;&amp;gt;&amp;gt; enumerate(["a", "b", "c"])
[(0, "a"), (1, "b"), (2, "c")]
&amp;gt;&amp;gt;&amp;gt; for index, value in enumerate(["a", "b", "c"]):
...     print(index, value)
0 a
1 b
2 c
```


**Problem 29:** Write a function `array` to create an 2-dimensional array. The function should take both dimensions as arguments. Value of each element can be initialized to None:


```
&amp;gt;&amp;gt;&amp;gt; a = array(2, 3)
&amp;gt;&amp;gt;&amp;gt; a
[[None, None, None], [None, None, None]]
&amp;gt;&amp;gt;&amp;gt; a[0][0] = 5
[[5, None, None], [None, None, None]]
```


**Problem 30:** Write a python function `parse_csv` to parse csv (comma separated values) files.


```
&amp;gt;&amp;gt;&amp;gt; print(open('a.csv').read())
a,b,c
1,2,3
2,3,4
3,4,5
&amp;gt;&amp;gt;&amp;gt; parse_csv('a.csv')
[['a', 'b', 'c'], ['1', '2', '3'], ['2', '3', '4'], ['3', '4', '5']]
```


**Problem 31:** Generalize the above implementation of csv parser to support any delimiter and comments.


```
&amp;gt;&amp;gt;&amp;gt; print(open('a.txt').read())
# elements are separated by ! and comment indicator is #
a!b!c
1!2!3
2!3!4
3!4!5
&amp;gt;&amp;gt;&amp;gt; parse('a.txt', '!', '#')
[['a', 'b', 'c'], ['1', '2', '3'], ['2', '3', '4'], ['3', '4', '5']]
```


**Problem 32:** Write a function `mutate` to compute all words generated by a single mutation on a given word. A mutation is defined as inserting a character, deleting a character, replacing a character, or swapping 2 consecutive characters in a string. For simplicity consider only letters from `a` to `z`.


```
&amp;gt;&amp;gt;&amp;gt; words = mutate('hello')
&amp;gt;&amp;gt;&amp;gt; 'helo' in words
True
&amp;gt;&amp;gt;&amp;gt; 'cello' in words
True
&amp;gt;&amp;gt;&amp;gt; 'helol' in words
True
```


**Problem 33:** Write a function `nearly_equal` to test whether two strings are nearly equal. Two strings `a` and `b` are nearly equal when `a` can be generated by a single mutation on `b`.


```
&amp;gt;&amp;gt;&amp;gt; nearly_equal('python', 'perl')
False
&amp;gt;&amp;gt;&amp;gt; nearly_equal('perl', 'pearl')
True
&amp;gt;&amp;gt;&amp;gt; nearly_equal('python', 'jython')
True
&amp;gt;&amp;gt;&amp;gt; nearly_equal('man', 'woman')
False
```


**2.7. Dictionaries**
Dictionaries are like lists, but they can be indexed with non integer keys also. Unlike lists, dictionaries are not ordered.


```
&amp;gt;&amp;gt;&amp;gt; a = {'x': 1, 'y': 2, 'z': 3}
&amp;gt;&amp;gt;&amp;gt; a['x']
1
&amp;gt;&amp;gt;&amp;gt; a['z']
3
&amp;gt;&amp;gt;&amp;gt; b = {}
&amp;gt;&amp;gt;&amp;gt; b['x'] = 2
&amp;gt;&amp;gt;&amp;gt; b[2] = 'foo'
&amp;gt;&amp;gt;&amp;gt; b[(1, 2)] = 3
&amp;gt;&amp;gt;&amp;gt; b
{(1, 2): 3, 'x': 2, 2: 'foo'}
```


The `del` keyword can be used to delete an item from a dictionary.


```
&amp;gt;&amp;gt;&amp;gt; a = {'x': 1, 'y': 2, 'z': 3}
&amp;gt;&amp;gt;&amp;gt; del a['x']
&amp;gt;&amp;gt;&amp;gt; a
{'y': 2, 'z': 3}
```


The `keys` method returns all keys in a dictionary, the `values` method returns all values in a dictionary and `items` method returns all key-value pairs in a dictionary.


```
&amp;gt;&amp;gt;&amp;gt; a.keys()
['x', 'y', 'z']
&amp;gt;&amp;gt;&amp;gt; a.values()
[1, 2, 3]
&amp;gt;&amp;gt;&amp;gt; a.items()
[('x', 1), ('y', 2), ('z', 3)]
```


The `for` statement can be used to iterate over a dictionary.


```
&amp;gt;&amp;gt;&amp;gt; for key in a: print(key)
...
x
y
z
&amp;gt;&amp;gt;&amp;gt; for key, value in a.items(): print(key, value)
...
x 1
y 2
z 3
```


Presence of a key in a dictionary can be tested using `in` operator or `has_key` method.


```
&amp;gt;&amp;gt;&amp;gt; 'x' in a
True
&amp;gt;&amp;gt;&amp;gt; 'p' in a
False
&amp;gt;&amp;gt;&amp;gt; a.has_key('x')
True
&amp;gt;&amp;gt;&amp;gt; a.has_key('p')
False
```


Other useful methods on dictionaries are `get` and `setdefault`.


```
&amp;gt;&amp;gt;&amp;gt; d = {'x': 1, 'y': 2, 'z': 3}
&amp;gt;&amp;gt;&amp;gt; d.get('x', 5)
1
&amp;gt;&amp;gt;&amp;gt; d.get('p', 5)
5
&amp;gt;&amp;gt;&amp;gt; d.setdefault('x', 0)
1
&amp;gt;&amp;gt;&amp;gt; d
{'x': 1, 'y': 2, 'z': 3}
&amp;gt;&amp;gt;&amp;gt; d.setdefault('p', 0)
0
&amp;gt;&amp;gt;&amp;gt; d
{'y': 2, 'x': 1, 'z': 3, 'p': 0}
```


Dictionaries can be used in string formatting to specify named parameters.


```
&amp;gt;&amp;gt;&amp;gt; 'hello %(name)s' % {'name': 'python'}
'hello python'
&amp;gt;&amp;gt;&amp;gt; 'Chapter %(index)d: %(name)s' % {'index': 2, 'name': 'Data Structures'}
'Chapter 2: Data Structures'
```


**2.7.1. Example: Word Frequency**
Suppose we want to find number of occurrences of each word in a file. Dictionary can be used to store the number of occurrences for each word.

Lets first write a function to count frequency of words, given a list of words.


```
def word_frequency(words):
    """Returns frequency of each word given a list of words.

        &amp;gt;&amp;gt;&amp;gt; word_frequency(['a', 'b', 'a'])
        {'a': 2, 'b': 1}
    """
    frequency = {}
    for w in words:
        frequency[w] = frequency.get(w, 0) + 1
    return frequency
```


Getting words from a file is very trivial.


```
def read_words(filename):
    return open(filename).read().split()
```


We can combine these two functions to find frequency of all words in a file.


```
def main(filename):
    frequency = word_frequency(read_words(filename))
    for word, count in frequency.items():
        print(word, count)

if __name__ == "__main__":
    import sys
    main(sys.argv[1])
```


**Problem 34:** Improve the above program to print the words in the descending order of the number of occurrences.

**Problem 35:** Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?

**Problem 36:** Write a program to find anagrams in a given list of words. Two words are called anagrams if one word can be formed by rearranging letters of another. For example 'eat', 'ate' and 'tea' are anagrams.


```
&amp;gt;&amp;gt;&amp;gt; anagrams(['eat', 'ate', 'done', 'tea', 'soup', 'node'])
[['eat', 'ate', 'tea], ['done', 'node'], ['soup']]
```


**Problem 37:** Write a function `valuesort` to sort values of a dictionary based on the key.


```
&amp;gt;&amp;gt;&amp;gt; valuesort({'x': 1, 'y': 2, 'a': 3})
[3, 1, 2]
```


**Problem 38:** Write a function `invertdict` to interchange keys and values in a dictionary. For simplicity, assume that all values are unique.


```
&amp;gt;&amp;gt;&amp;gt; invertdict({'x': 1, 'y': 2, 'z': 3})
{1: 'x', 2: 'y', 3: 'z'}
```


**2.7.2. Understanding Python Execution Environment**
Python stores the variables we use as a dictionary. The `globals()` function returns all the globals variables in the current environment.


```
&amp;gt;&amp;gt;&amp;gt; globals()
{'__builtins__': &amp;lt;module '__builtin__' (built-in)&amp;gt;, '__name__': '__main__', '__doc__': None}
&amp;gt;&amp;gt;&amp;gt; x = 1
&amp;gt;&amp;gt;&amp;gt; globals()
{'__builtins__': &amp;lt;module '__builtin__' (built-in)&amp;gt;, '__name__': '__main__', '__doc__': None, 'x': 1}
&amp;gt;&amp;gt;&amp;gt; x = 2
&amp;gt;&amp;gt;&amp;gt; globals()
{'__builtins__': &amp;lt;module '__builtin__' (built-in)&amp;gt;, '__name__': '__main__', '__doc__': None, 'x': 2}
&amp;gt;&amp;gt;&amp;gt; globals()['x'] = 3
&amp;gt;&amp;gt;&amp;gt; x
3
```


Just like `globals` python also provides a function `locals` which gives all the local variables in a function.


```
&amp;gt;&amp;gt;&amp;gt; def f(a, b): print(locals())
...
&amp;gt;&amp;gt;&amp;gt; f(1, 2)
{'a': 1, 'b': 2}
```


One more example:


```
&amp;gt;&amp;gt;&amp;gt; def f(name):
...     return "Hello %(name)s!" % locals()
...
&amp;gt;&amp;gt;&amp;gt; f("Guido")
Hello Guido!
```

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
    <item>
      <title>Getting started with Python</title>
      <dc:creator>Esther Wavinya</dc:creator>
      <pubDate>Tue, 28 Apr 2020 08:10:19 +0000</pubDate>
      <link>https://dev.to/estherwavinya/getting-started-with-python-aa9</link>
      <guid>https://dev.to/estherwavinya/getting-started-with-python-aa9</guid>
      <description>&lt;p&gt;As a beginner in code I am going to help my fellow beginners in studying python. I am writing what I have been learning personally according to Python Practice Book by Anand Chitipothu. It is going to be kind of a review. According to my previous article in my medium account I mentioned several Python libraries, frameworks and micro-frameworks. That depends on exactly what you are doing with this programming language because it is too wide. &lt;/p&gt;

&lt;p&gt;For instance: &lt;code&gt;Pandas&lt;/code&gt; (Python data analysis) is a must in the data science life cycle. It is the most popular and widely used Python library for data science, along with &lt;code&gt;NumPy&lt;/code&gt; in &lt;code&gt;matplotlib&lt;/code&gt;. If you haven't read the article here is the link &lt;a href="https://medium.com/@estherwavinya/what-i-should-have-known-about-python-570ad0b47203" rel="noopener noreferrer"&gt;What I should have known about python&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now let's get back to business.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.0 Getting Started&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;1.1. Running Python Interpreter&lt;/strong&gt;&lt;br&gt;
Python comes with an interactive interpreter. When you type &lt;code&gt;python&lt;/code&gt; in your shell or command prompt, the python interpreter becomes active with a &lt;code&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; prompt and waits for your commands.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
$ python
Python 3.7.4 (v3.7.4:e09359112e, Jul  8 2019, 14:54:52)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&amp;gt;&amp;gt;&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can type any valid python expression at the prompt. python reads the typed expression, evaluates it and prints the result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 42
42
&amp;gt;&amp;gt;&amp;gt; 4 + 2
6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 1:&lt;/strong&gt; Open a new Python interpreter and use it to find the value of &lt;code&gt;2 + 3&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.2. Running Python Scripts&lt;/strong&gt;&lt;br&gt;
Open your text editor, type the following text and save it as &lt;code&gt;hello.py&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;print("hello, world!")&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;And run this program by calling &lt;code&gt;python hello.py&lt;/code&gt;. Make sure you change to the directory where you saved the file before doing it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python hello.py
hello, world!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.3. Datatypes&lt;/strong&gt;&lt;br&gt;
Python has support for all basic datatypes and also have very powerful compound datatypes.&lt;/p&gt;

&lt;p&gt;Python has integers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 1 + 2
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python is pretty good at handling very large numbers as well. For example, let us try to compute 2 raises to the power of 1000.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is a pretty big number, isn’t it? Can you count how many digits it has?&lt;/p&gt;

&lt;p&gt;Python has floating point numbers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 1.2 + 2.3
3.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; "hello world"
'hello world'
&amp;gt;&amp;gt;&amp;gt; print("hello world")
hello world
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;String can be enclosed either in single quotes or double quotes. Both are exactly the same. In Python, strings are very versatile and it very easy to work with them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 'hello' + 'world'
'helloworld'

&amp;gt;&amp;gt;&amp;gt; "hello" * 3
'hellohellohello'

&amp;gt;&amp;gt;&amp;gt; print("=" * 40)
========================================
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;len&lt;/code&gt; is used to find the length of a string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; len('helloworld')
10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python supports multi-line strings too. They are enclosed in three double quotes or three single quotes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;text = """This is a multi-line string.
Line 2
Line 3
and the text may have "quotes" too.
"""
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print(text)
This is a multi-line string.
Line 2
Line 3
and the text may have "quotes" too.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python supports the usual escape codes. &lt;code&gt;\n&lt;/code&gt; indicates new line, &lt;code&gt;\t&lt;/code&gt; indicates a tab etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print "a\nb\nc"
a
b
c
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has lists. Lists are one of the most useful data types of Python.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = ["a", "b", "c"]
&amp;gt;&amp;gt;&amp;gt; x
['a', 'b', 'c']
&amp;gt;&amp;gt;&amp;gt; len(x)
3
&amp;gt;&amp;gt;&amp;gt; x[1]
'b'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has another datatype called &lt;code&gt;tuple&lt;/code&gt; for representing fixed width records. &lt;code&gt;Tuples&lt;/code&gt; behave just like lists, but they are immutable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; point = (2, 3)
&amp;gt;&amp;gt;&amp;gt; point
(2, 3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When writing tuples, the parenthesis can be omitted most of the times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; point = 2, 3
&amp;gt;&amp;gt;&amp;gt; point
(2, 3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is also possible to assign a tuple multiple values at once:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; yellow = (255, 255, 0)
&amp;gt;&amp;gt;&amp;gt; r, g, b = yellow
&amp;gt;&amp;gt;&amp;gt; print(r, g, b)
255 255 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has a &lt;code&gt;dictionary&lt;/code&gt; datatype for representing name-value pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; person = {"name": "Alice", "email": "alice@example.com"}
&amp;gt;&amp;gt;&amp;gt; person['name']
'Alice'
&amp;gt;&amp;gt;&amp;gt; person['email']
'alice@example.com'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has a &lt;code&gt;set&lt;/code&gt; datatype too. A set is an unordered collection of elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = {1, 2, 3, 2, 1}
&amp;gt;&amp;gt;&amp;gt; x
{1, 2, 3}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python has a &lt;code&gt;boolean&lt;/code&gt; type. It has two special values True and False to represent &lt;code&gt;truth&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, Python has a special type called &lt;code&gt;None&lt;/code&gt; to represent nothing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = None
&amp;gt;&amp;gt;&amp;gt; print(x)
None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you know most of the common data structures of Python. While they look very simple, mastering them takes a bit of practice. Make sure you go through all the examples and the practice problems in the subsequent sections.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.4. Variables&lt;/strong&gt;&lt;br&gt;
You’ve already seen variables in the previous section. Let us look at them closely now.&lt;/p&gt;

&lt;p&gt;In Python, variables don’t have a type. They are just placeholders which can hold any type of values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 5
&amp;gt;&amp;gt;&amp;gt; x
5
&amp;gt;&amp;gt;&amp;gt; x = 'hello'
&amp;gt;&amp;gt;&amp;gt; x
'hello'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is important to notice the difference between variables and strings. Often new programmers get tricked by this. Can you spot any error in the following example?&lt;/p&gt;

&lt;p&gt;&lt;code&gt;name = “Alice” print(“name”)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.5. Functions&lt;/strong&gt;&lt;br&gt;
Python has many built-in functions. The &lt;code&gt;print&lt;/code&gt; is the most commonly used built-in function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print('hello')
hello
&amp;gt;&amp;gt;&amp;gt; print('hello', 1, 2, 3)
hello 1 2 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We’ve also see the &lt;code&gt;len&lt;/code&gt; function in the previous sections. The &lt;code&gt;len&lt;/code&gt; function computes the length of a string, list or other collections.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; len("hello")
5
&amp;gt;&amp;gt;&amp;gt; len(['a', 'b', 'c'])
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One important thing about Python is that it doesn’t allow operations on incompatible data types. For instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 5 + "2"
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
TypeError: unsupported operand type(s) for +: 'int' and 'str'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is because it is not possible to add a number to a string. We need to either convert &lt;code&gt;5&lt;/code&gt; into a string or &lt;code&gt;"2"&lt;/code&gt; into a number. The built-in function &lt;code&gt;int&lt;/code&gt; converts a string into a number and the &lt;code&gt;str&lt;/code&gt; function converts any value into a string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; int("5")
5
&amp;gt;&amp;gt;&amp;gt; str(5)
'5'
&amp;gt;&amp;gt;&amp;gt; 5 + int("2")
7
&amp;gt;&amp;gt;&amp;gt; str(5) + "2"
'52'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.5.1. Example: Counting the number of digits in a number&lt;/strong&gt;&lt;br&gt;
Let us write a program to compute number of digits in a number. Let us look at some numbers first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; 12345
12345
&amp;gt;&amp;gt;&amp;gt; 2 ** 100
1267650600228229401496703205376
&amp;gt;&amp;gt;&amp;gt; 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can combile the previously mentioned built-in functions to solve this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; len(str(12345))
5
&amp;gt;&amp;gt;&amp;gt; len(str(2 ** 100))
31
&amp;gt;&amp;gt;&amp;gt; len(str(2 * 1000))
302

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.6. Writing Custom Functions&lt;/strong&gt;&lt;br&gt;
Just like a value can be associated with a name, a piece of logic can also be associated with a name by defining a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; def square(x):
...    return x * x
...
&amp;gt;&amp;gt;&amp;gt; square(5)
25

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The body of the function is indented. Indentation is the Python’s way of grouping statements.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;...&lt;/code&gt; is the secondary prompt, which the Python interpreter uses to denote that it is expecting some more input.&lt;/p&gt;

&lt;p&gt;The functions can be used in any expressions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; square(2) + square(3)
13
&amp;gt;&amp;gt;&amp;gt; square(square(3))
81

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Existing functions can be used in creating new functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; def sum_of_squares(x, y):
...    return square(x) + square(y)
...
&amp;gt;&amp;gt;&amp;gt; sum_of_squares(2, 3)
13

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Functions are just like other values, they can assigned, passed as arguments to other functions etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; f = square
&amp;gt;&amp;gt;&amp;gt; f(4)
16
&amp;gt;&amp;gt;&amp;gt; def fxy(f, x, y):
...     return f(x) + f(y)
...
&amp;gt;&amp;gt;&amp;gt; fxy(square, 2, 3)
13

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is important to understand, the scope of the variables used in functions.&lt;/p&gt;

&lt;p&gt;Lets look at an example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
x = 0
y = 0
def incr(x):
    y = x + 1
    return y
incr(5)
print x, y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Variables assigned in a function, including the arguments are called the local variables to the function. The variables defined in the top-level are called global variables.&lt;/p&gt;

&lt;p&gt;Changing the values of &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; inside the function &lt;code&gt;incr&lt;/code&gt; won’t effect the values of global &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;But, we can use the values of the global variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
pi = 3.14
def area(r):
    return pi * r * r

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When Python sees use of a variable not defined locally, it tries to find a global variable with that name.&lt;/p&gt;

&lt;p&gt;However, you have to explicitly declare a variable as global to modify it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
numcalls = 0
def square(x):
    global numcalls
    numcalls = numcalls + 1
    return x * x

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 2:&lt;/strong&gt; How many multiplications are performed when each of the following lines of code is executed?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
print square(5)
print square(2*5)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 3:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
x = 1
def f():
    return x
print x
print f()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 4:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
x = 1
def f():
    x = 2
    return x
print x
print f()
print x

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 5:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
x = 1
def f():
        y = x
        x = 2
        return x + y
print x
print f()
print x

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 6:&lt;/strong&gt; What will be the output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
x = 2
def f(a):
    x = a * a
    return x
y = f(3)
print x, y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Functions can be called with keyword arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; def difference(x, y):
...    return x - y
...
&amp;gt;&amp;gt;&amp;gt; difference(5, 2)
3
&amp;gt;&amp;gt;&amp;gt; difference(x=5, y=2)
3
&amp;gt;&amp;gt;&amp;gt; difference(5, y=2)
3
&amp;gt;&amp;gt;&amp;gt; difference(y=2, x=5)
3

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And some arguments can have default values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; def increment(x, amount=1):
...    return x + amount
...
&amp;gt;&amp;gt;&amp;gt; increment(10)
11
&amp;gt;&amp;gt;&amp;gt; increment(10, 5)
15
&amp;gt;&amp;gt;&amp;gt; increment(10, amount=2)
12

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is another way of creating functions, using the &lt;code&gt;lambda&lt;/code&gt; operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; cube = lambda x: x ** 3
&amp;gt;&amp;gt;&amp;gt; fxy(cube, 2, 3)
35
&amp;gt;&amp;gt;&amp;gt; fxy(lambda x: x ** 3, 2, 3)
35

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that unlike function definition, lambda doesn’t need a &lt;code&gt;return&lt;/code&gt;. The body of the &lt;code&gt;lambda&lt;/code&gt; is a single expression.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;lambda&lt;/code&gt; operator becomes handy when writing small functions to be passed as arguments etc. We’ll see more of it as we get into solving more serious problems.&lt;/p&gt;

&lt;p&gt;Python provides some useful built-in functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; min(2, 3)
2
&amp;gt;&amp;gt;&amp;gt; max(3, 4)
4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;len&lt;/code&gt; computes length of a string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; len("helloworld")
10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;int&lt;/code&gt; converts string to integer and built-in function &lt;code&gt;str&lt;/code&gt;converts integers and other type of objects to strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; int("50")
50
&amp;gt;&amp;gt;&amp;gt; str(123)
"123"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 7:&lt;/strong&gt; Write a function &lt;code&gt;count_digits&lt;/code&gt; to find number of digits in the given number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; count_digits(5)
1
&amp;gt;&amp;gt;&amp;gt; count_digits(12345)
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Methods are special kind of functions that work on an object.For example, &lt;code&gt;upper&lt;/code&gt; is a method available on string objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = "hello"
&amp;gt;&amp;gt;&amp;gt; print x.upper()
HELLO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As already mentioned, methods are also functions. They can be assigned to other variables and can be called separately.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; f = x.upper
&amp;gt;&amp;gt;&amp;gt; f()
'HELLO'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 8:&lt;/strong&gt; Write a function &lt;em&gt;istrcmp&lt;/em&gt; to compare two strings, ignoring the &lt;br&gt;
case.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; istrcmp('python', 'Python')
True
&amp;gt;&amp;gt;&amp;gt; istrcmp('LaTeX', 'Latex')
True
&amp;gt;&amp;gt;&amp;gt; istrcmp('a', 'b')
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.7. Conditional Expressions&lt;/strong&gt;&lt;br&gt;
Python provides various operators for comparing values. The result of a comparison is a boolean value, either &lt;code&gt;True&lt;/code&gt; or &lt;code&gt;False&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 2 &amp;lt; 3
True
&amp;gt;&amp;gt;&amp;gt; 2 &amp;gt; 3
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the list of available conditional operators.&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;==&lt;/code&gt; equal to&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;!=&lt;/code&gt; not equal to&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;&amp;lt;&lt;/code&gt; less than&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;&amp;gt;&lt;/code&gt; greater than&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;&amp;lt;=&lt;/code&gt; less than or equal to&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;&amp;gt;=&lt;/code&gt; greater than or equal to&lt;/p&gt;

&lt;p&gt;It is even possible to combine these operators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 5
&amp;gt;&amp;gt;&amp;gt; 2 &amp;lt; x &amp;lt; 10
True
&amp;gt;&amp;gt;&amp;gt; 2 &amp;lt; 3 &amp;lt; 4 &amp;lt; 5 &amp;lt; 6
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The conditional operators work even on strings - the ordering being the &lt;code&gt;lexical order&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; "python" &amp;gt; "perl"
True
&amp;gt;&amp;gt;&amp;gt; "python" &amp;gt; "java"
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are few logical operators to combine boolean values.&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;a and b&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt; only if both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are True.&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;a or b&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt; if either &lt;code&gt;a&lt;/code&gt; or &lt;code&gt;b&lt;/code&gt; is True.&lt;/p&gt;

&lt;p&gt;-&lt;code&gt;not a&lt;/code&gt; is True only if &lt;code&gt;a&lt;/code&gt; is False.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; True and True
True
&amp;gt;&amp;gt;&amp;gt; True and False
False
&amp;gt;&amp;gt;&amp;gt; 2 &amp;lt; 3 and 5 &amp;lt; 4
False
&amp;gt;&amp;gt;&amp;gt; 2 &amp;lt; 3 or 5 &amp;lt; 4
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 9:&lt;/strong&gt; What will be output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print 2 &amp;lt; 3 and 3 &amp;gt; 1
print 2 &amp;lt; 3 or 3 &amp;gt; 1
print 2 &amp;lt; 3 or not 3 &amp;gt; 1
print 2 &amp;lt; 3 and not 3 &amp;gt; 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 10:&lt;/strong&gt; What will be output of the following program?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = 4
y = 5
p = x &amp;lt; y or x &amp;lt; z
print(p)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;if&lt;/code&gt; statement is used to execute a piece of code only when a boolean expression is true.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 42
&amp;gt;&amp;gt;&amp;gt; if x % 2 == 0: print('even')
even
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;code&gt;print('even')&lt;/code&gt; is executed only when &lt;code&gt;x % 2 == 0&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt;.&lt;br&gt;
The code associated with &lt;code&gt;if&lt;/code&gt; can be written as a separate indented block of code, which is often the case when there is more than one statement to be executed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; if x % 2 == 0:
...     print('even')
...
even
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;if&lt;/code&gt; statement can have optional &lt;code&gt;else&lt;/code&gt; clause, which is executed when the boolean expression is &lt;code&gt;False&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 3
&amp;gt;&amp;gt;&amp;gt; if x % 2 == 0:
...     print('even')
... else:
...     print('odd')
...
odd
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;if&lt;/code&gt; statement can have optional &lt;code&gt;elif&lt;/code&gt; clauses when there are more conditions to be checked. The &lt;code&gt;elif&lt;/code&gt; keyword is short for &lt;code&gt;else if&lt;/code&gt;, and is useful to avoid excessive indentation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 42
&amp;gt;&amp;gt;&amp;gt; if x &amp;lt; 10:
...        print('one digit number')
... elif x &amp;lt; 100:
...     print('two digit number')
... else:
...     print('big number')
...
two digit number
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 11:&lt;/strong&gt; What happens when the following code is executed? Will it give any error? Explain the reasons.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = 2
if x == 2:
    print(x)
else:
    print(y)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problem 12:&lt;/strong&gt; What happens the following code is executed? Will it give any error? Explain the reasons.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = 2
if x == 2:
    print(x)
else:
    x +
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.8. Lists&lt;/strong&gt;&lt;br&gt;
Lists are one of the great data structures in Python. We are going to learn a little bit about lists now. Basic knowledge of lists is requrired to be able to solve some problems that we want to solve in this chapter.&lt;/p&gt;

&lt;p&gt;Here is a list of numbers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here is a list of strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = ["hello", "world"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;List can be heterogeneous. Here is a list containing integers, strings and another list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; x = [1, 2, "hello", "world", ["another", "list"]]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The built-in function &lt;code&gt;len&lt;/code&gt; works for lists as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3]
&amp;gt;&amp;gt;&amp;gt; len(x)
3

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;[]&lt;/code&gt; operator is used to access individual elements of a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; x = [1, 2, 3]
&amp;gt;&amp;gt;&amp;gt; x[1]
2
&amp;gt;&amp;gt;&amp;gt; x[1] = 4
&amp;gt;&amp;gt;&amp;gt; x[1]
4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first element is indexed with &lt;code&gt;0&lt;/code&gt;, second with &lt;code&gt;1&lt;/code&gt; and so on.&lt;br&gt;
We’ll learn more about lists in my next article.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.9. Modules&lt;/strong&gt;&lt;br&gt;
Modules are libraries in Python. Python ships with many standard library modules.&lt;br&gt;
A module can be imported using the &lt;code&gt;import&lt;/code&gt; statement.&lt;br&gt;
Lets look at &lt;code&gt;time&lt;/code&gt; module for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&amp;gt;&amp;gt;&amp;gt; import time
&amp;gt;&amp;gt;&amp;gt; time.asctime()
'Tue Sep 11 21:42:06 2012'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;asctime&lt;/code&gt; function from the &lt;code&gt;time&lt;/code&gt; module returns the current time of the system as a string.&lt;br&gt;
The &lt;code&gt;sys&lt;/code&gt; module provides access to the list of arguments passed to the program, among the other things.&lt;br&gt;
The &lt;code&gt;sys.argv&lt;/code&gt; variable contains the list of arguments passed to the program. As a convention, the first element of that list is the name of the program.&lt;/p&gt;

&lt;p&gt;Lets look at the following program &lt;code&gt;echo.py&lt;/code&gt; that prints the first argument passed to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import sys
print(sys.argv[1])

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets try running it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
$ python echo.py hello
hello
$ python echo.py hello world
hello

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are many more interesting modules in the standard library. We’ll learn more about them in the coming articles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem 13:&lt;/strong&gt; Write a program &lt;code&gt;add.py&lt;/code&gt; that takes 2 numbers as command line arguments and prints its sum.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
$ python add.py 3 5
8
$ python add.py 2 9
11

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>writing</category>
    </item>
  </channel>
</rss>
