Imports


In [2]:
# for ipython notebooks this display images inline and imports 
# numpy and matplotlib
%pylab inline

# ----- Future Libraries for Python 3 portability
from __future__ import print_function
from future.builtins import range

# ---- Standard Libraries (not imported by pylab)
import time

# ---- Scientific Libraries (not imported by pylab)
import pandas as pd


Populating the interactive namespace from numpy and matplotlib

In [2]:
# Problem 1
2 + 3


Out[2]:
5

In [3]:
# Problem 2
for hello in ["hello, world!" for x in range(4)]:
    print(hello)


hello, world!
hello, world!
hello, world!
hello, world!

In [4]:
# Problem 3
print(1 + 2)


3

In [5]:
# Problem 4
x = 4
y = x + 1
x = 2
print(x, y)

# Problem 5
x, y = 2, 6
x, y = y, x + 2
print(x, y)

# Problem 6
a, b = 2, 3
c = a
c, b = a, c + 1
print(a, b, c)


2 5
6 4
2 3 2

In [6]:
# Problem 7
numcalls = 0
def square(x):
    global numcalls
    numcalls = numcalls + 1
    return x * x

print(square(5), numcalls) # numcalls will be 1
print(square(2*5), numcalls) # numcalls will be 2 as numcalls is global


25 1
100 2

In [7]:
# Problem 8
x = 1
def f():
    return x
print(x, f())

# output should be 1 1


1 1

In [8]:
# Problem 9
x = 1
def f():
    x = 2
    return x
print(x, f(), x)

# output should be 1, 2, 1


1 2 1

In [9]:
# Problem 10
x = 1
def f():
    y = 1 # original problem had x so use x to make it error
    x = 2
    return x + y
print(x, f(), x)

# output should be 1 3 1 --> nope can only return outside variables, this 
# fails with:  local variable 'x' referenced before assignment


1 3 1

In [10]:
# Problem 11
x = 2
def f(a):
    x = a * a
    return x
y = f(3)
print(x, y)

# output should be 2 9


2 9

In [11]:
# Problem 12
# as a standard function
# def count_digits(number):
#     return len(str(number))

# as a lambda function
count_digits = lambda x: len(str(x))

print(count_digits(5), count_digits(123456))


1 6

In [12]:
# Problem 13
# as a standard function
# def istrcmp(str1, str2):
#     return str1.lower() == str2.lower()

# as a lambda
istrcmp = lambda x, y: x.lower() == y.lower()

print(istrcmp('python', 'Python'), 
      istrcmp('LaTeX', 'Latex'),
      istrcmp('a', 'b'))


True True False

In [18]:
# Problem 14
print(2 < 3 and 3 > 1,
      2 < 3 or 3 > 1,
      2 < 3 or not 3 > 1,
      2 < 3 and not 3 > 1)

# output should be:  True True True False


True True True False

In [20]:
# Problem 15
x, y, z = 4, 5, 6
print(x < y or x < z)
# output should be True

# Problem 16
True, False = False, True
print(True, False, 2 < 3)
# for the love of god, why?  fixed in Python 3
# see: http://python-history.blogspot.com/2013/11/story-of-none-true-false.html
# output should be False True, False but it is:


True
False True True

In [6]:
# Problem 17

x = 2
if x == 2:
    print(x)
else:
    print(y)
    
# this code will execute fully if and only if x = 2 otherwise it will fail,
# this is because python is interpreted

# Problem 18
x = 2
if x == 2:
    print(x)
else:
    x + 
    
# code will fail because the interpeter will detect a syntax error


  File "<ipython-input-6-2cf5e6985c13>", line 17
    x +
       ^
SyntaxError: invalid syntax

In [ ]:
# Problem 19
# The code below should be in a file named add.py and run from the
# command line

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" 
Purpose
-------

Problem 19 from http://anandology.com/python-practice-book/getting-started.html

"""
# ----------------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------------


from __future__ import print_function

import argparse
import sys

# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------


def use_argparse():
    """ Parse the command line arguments using argparse. """
    parser = argparse.ArgumentParser(description='Add some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+', 
                        help='integers to sum')
    parser.add_argument('-s', '--sum', dest='accumulate', 
                        action='store_const', 
                        const=sum, default=sum,
                        help='sum the integers')
    
    args = parser.parse_args()
    return args.accumulate(args.integers)

def use_sys_args():
    """ Parse the command line arguments using sys.args. """
    the_sum = 0
    for arg in sys.argv[1:]: # sys.argv[0] is the name of the script
        the_sum += int(arg)
        
    return the_sum 

def main():
    """ Runs the script as a stand alone application. """
    # print(use_argparse())
    print(use_sys_args())

# ----------------------------------------------------------------------------
# Name
# ----------------------------------------------------------------------------


if __name__ == "__main__":
    main()