ahhhhhjulie ahhhhhjulie - 1 year ago 118
Python Question

Python how to make an exception for non positive numbers

How can I raise an exception here to catch nonpositive inputs? Right now nothing gets printed if I input a negative number

Generate fibonacci sequence to the nth digit
def fib(n):
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in range(0, int(n)):
nxt = prev + curr
print str(curr),
prev = curr
curr = nxt
except ValueError or Exception:
new = raw_input("Invalid input. Please enter a positive integer: ")

n = raw_input("Enter number of terms: ")

Answer Source

As Jon says, it's a much better design strategy to separate the input gathering from the core Fibonacci calculation. Also, it's generally better to use a simple loop than to use a recursive call (calling a function inside itself) unless you really need recursion (eg, when processing a recursive data structure, like a directory tree)..

Here's a modified version of your code. I've made a few other minor changes. In Python, we don't need a temporary variable like nxt to do the core Fibonacci calculation. Instead we use tuple assignment so we can update curr and save the old curr to prev in one step.

def input_positive_integer(prompt=''):
    """ Get a positive integer from the user """
    while True:
            n = int(raw_input(prompt))
            if n <= 0:
                raise ValueError
        except ValueError:
            print "Invalid input.",
            prompt = "Please enter a positive integer: "
    return n

def fib(n):
    """ Print n terms of the Fibonacci sequence """
    prev, curr = 0, 1
    for terms in range(n):
        print curr,
        prev, curr = curr, prev + curr

n = input_positive_integer("Enter number of terms: ")


Enter number of terms: -4
Invalid input. Please enter a positive integer: q
Invalid input. Please enter a positive integer: 2.5
Invalid input. Please enter a positive integer: 5
1 1 2 3 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download