Introduction to Computing for Engineers and Computer Scientists

Chapter 3: Algorithm and Program Development

Questions

From Class?

From Piazza

Interactive versus Script

Simplest Solution
In [16]:
#!/usr/bin/env python3

import argparse

# Default is that the program is not interactive.
# Change from the prompt or a Jupyter cell if is interactive.
interactive = False


def get_args():

    result = None

    if not interactive:
        parser = argparse.ArgumentParser(
            description='Simulate flexible command line arguments.')
        parser.add_argument('--arg1', default=12, type=int, metavar='int',
                            help='Argument 1')
        args = parser.parse_args()
        result = args.arg1
    else:
        result = int(input("Enter value for arg1: "))

    return result


def simulating_simulation(arg):
    print("Simulating receiving arguments in a simulation. arg = ", arg)


def run_test():
    print("Testing.")
    test_result = get_args()
    print("Test result = ", test_result)
    print("Can call all of the other code with args now.")
    simulating_simulation(test_result)


run_test()
Testing.
usage: ipykernel_launcher.py [-h] [--arg1 int]
ipykernel_launcher.py: error: unrecognized arguments: -f /Users/donaldferguson/Library/Jupyter/runtime/kernel-c061a760-2bd2-42f8-b8e8-b089dbaed348.json
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2
/Users/donaldferguson/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2918: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
In [17]:
print("Change interactive to True and try again.")
interactive = True
run_test()
Change interactive to True and try again.
Testing.
Enter value for arg1: 2
Test result =  2
Can call all of the other code with args now.
Simulating receiving arguments in a simulation. arg =  2
Slightly More Sophisticated Solution
In [18]:
#!/usr/bin/env python3

import argparse

# main is the top-level module for this execution.
# Do not worry about this for now.
# An execution can either be interactive, i.e. something types/sends
# the Python statements, or driven from file input, e.g. ./foo --arg
#
# If there is no file associated with __main__, then we are interactive.
def is_interactive():
    import __main__ as main
    return not hasattr(main, '__file__')


# Default is that the program is not interactive.
# Change from the prompt or a Jupyter cell if is interactive.
interactive = is_interactive()


def get_args():

    result = None

    if not interactive:
        parser = argparse.ArgumentParser(
            description='Simulate flexible command line arguments.')
        parser.add_argument('--arg1', default=12, type=int, metavar='int',
                            help='Argument 1')
        args = parser.parse_args()
        result = args.arg1
    else:
        result = int(input("Enter value for arg1: "))

    return result


def simulating_simulation(arg):
    print("Simulating receiving arguments in a simulation. arg = ", arg)


def run_test():
    print("Testing.")
    test_result = get_args()
    print("Test result = ", test_result)
    print("Can call all of the other code with args now.")
    simulating_simulation(test_result)


run_test()
Testing.
Enter value for arg1: 33
Test result =  33
Can call all of the other code with args now.
Simulating receiving arguments in a simulation. arg =  33

Another Possible Solution

In [29]:
import argparse

def get_args():

    result = None

    try:
        parser = argparse.ArgumentParser(
           description='Simulate flexible command line arguments.')
        parser.add_argument('--arg1', default=12, type=int, metavar='int',
                            help='Argument 1')
        args = parser.parse_args()
        result = args.arg1
    except: 
        print("Got an arg parse exception. Trying a prompt.")
        result = int(input("Enter value for arg1: "))

    return result

get_args()
usage: ipykernel_launcher.py [-h] [--arg1 int]
ipykernel_launcher.py: error: unrecognized arguments: -f /Users/donaldferguson/Library/Jupyter/runtime/kernel-c061a760-2bd2-42f8-b8e8-b089dbaed348.json
Got an arg parse exception. Trying a prompt.
Enter value for arg1: 32
Out[29]:
32

Switch to Presentation

Babylonian Square Root

In [1]:
# Copyright 2017, 2013, 2011 Pearson Education, Inc., W.F. Punch & R.J.Enbody
# Newton's Method to calculate square root

# get three inputs from the user (two ints, 1 float)
# note not robust on bad input
number_str = input("Find the square root of integer: ")
number_int = int(number_str)
guess_str = input("Initial guess: ")
guess_float = float(guess_str)
tolerance_float = float(input("What tolerance: "))

original_guess_float = guess_float # hang onto the original guess
count_int = 0                      # count the number of guesses
previous_float = 0                 # track the previous calculated value

while abs(previous_float - guess_float) > tolerance_float:
       previous_float = guess_float
       quotient_float = number_int/guess_float
       guess_float = (quotient_float + guess_float)/2
       count_int = count_int + 1

# output the three original values, the number of
# iterations and the square root
print("Square root of",number_int," is: ",guess_float)
print("Took ",count_int," reps to get it to tolerance: ",tolerance_float)
print("Starting from a guess of: ", original_guess_float)
Find the square root of integer: 125
Initial guess: 10
What tolerance: 0.2
Square root of 125  is:  11.180555555555555
Took  2  reps to get it to tolerance:  0.2
Starting from a guess of:  10.0
  • Try this with input -125. I dare you.
- My programmers use something like [Sphinx](http://www.sphinx-doc.org/en/stable/) to document "real" programs. - Structured comments $\rightarrow$ HTML pages the describe functions, parameters, etc.

``` def public_fn_with_sphinxy_docstring(name, state=None): """This function does something. :param name: The name to use. :type name: str. :param state: Current state to be in. :type state: bool. :returns: int -- the return code. :raises: AttributeError, KeyError """ return 0 ```


- This is just FYI.