Book Image

Python Fundamentals

By : Ryan Marvin, Mark Ng’ang’a, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Ng’ang’a, Amos Omondi

Overview of this book

<p>After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions.</p> <p>As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation.</p> <p>By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.</p>
Table of Contents (12 chapters)
Python Fundamentals
Preface

Chapter 8: Modules, Packages, and File Operations


Activity 34: Inspecting Modules

Solution:

  1. Inspect the resources defined in the itertools library by using the dir() function:

    >>> import itertools
    >>> dir(itertools)
    ['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'comp
    ress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
  2. Use the help() function to read about how to use the itertools library:

    >>> help(itertools)

    You should see an output such as this:

    Help on built-in module itertools:
    
    NAME
        itertools - Functional tools for creating and using iterators.
    DESCRIPTION
        Infinite iterators:
        count(start=0, step=1) --> start, start+step, start+2*step, ...
        cycle(p) --> p0, p1, ... plast, p0, p1, ...
        repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times
    
        Iterators terminating on the shortest input sequence:
        accumulate(p[, func]) --> p0, p0+p1, p0+p1+p2
        chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ...
        chain.from_iterable([p, q, ...]) --> p0, p1, ... plast, q0, q1, ...
        compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...
        dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails
        groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)
        filterfalse(pred, seq) --> elements of seq where pred(elem) is False
        islice(seq, [start,] stop [, step]) --> elements from
               seq[start:stop:step]
        starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...
        tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n
        takewhile(pred, seq) --> seq[0], seq[1], until pred fails
        zip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ...
    
        Combinatoric generators:
        product(p, q, ... [repeat=1]) --> cartesian product
        permutations(p[, r])
        combinations(p, r)
        combinations_with_replacement(p, r)
    
    CLASSES
        builtins.object
            accumulate
            chain
            combinations
            combinations_with_replacement
            compress
            count
            cycle
            dropwhile
            filterfalse
            groupby
            islice
    /var/folders/lb/k8ws21qn1x5gxq9zbrlqxp9w0000gn/T/tmp__ayalkd

Activity 35: Listing the Resources Defined in a Package or Module

Solution:

def package_enumerator(package):
  """
  List the resources defined in a package or module.
  """
  resources = dir(package)
  for resource in resources:
      print(resource)

import string 
package_enumerator(string)

Activity 36: Using Resources in a Module

Solution:

import random

def random_number_generator(l):
    """
    Generate a list of random numbers of length l.
    """
    output = []
  
    for i in range(l):
        output.append(random.randint(0, 1000))
    
    return output

Activity 37: Performing File Operations

Solution:

with open("myfile.txt", 'w') as f: 
  f.write("I love Python")

Activity 38: Working with Files

Solution:

import csv

output_data = []

with open('input.csv', 'r') as f:
    mock_data_reader = csv.reader(f)
    output_data = []
    line_count = 1
    for row in mock_data_reader: 
      if line_count != 1:
        row[1] = int(row[1]) * 15
        output_data.append(row)
      line_count += 1

with open('output.csv', 'w') as f:
    fields = ['name', 'wages']
    output_writer = csv.DictWriter(f, fieldnames=fields)

    output_writer.writeheader()

    for line in output_data:
      output_writer.writerow(
        {
          'name': line[0],
          'wages': line[1]
        }
      )

This sample solution is also present in the wage_calculator.py file in the accompanying code files.