-2

I have a programming homework assignment. Everything went smoothly until I reached a problem using Try/Except. If I type a valid datetime, the program will take it and it will move on, but if I use a valid datetime format, the exception won't react.

Here is my code:

 import datetime
import csv


def get_stock_name(prompt,mode):
    while True:
        try:
            return open(input(prompt) + ".csv")
        except FileNotFoundError:
            print("File not found. Please try again.")
        except IOError:
            print("There was an IOError opening the file. Please try again.")


def get_stock_date(prompt):
    while True:
        try:
            return (input(prompt))
        except TypeError:
            print("Try again.")
        except ValueError:
            print("Try again.")


def get_stock_purchased(prompt):
    while True:
        try:
            return (input(prompt))
        except ValueError:
            print("Try again.")
        except TypeError:
            print("try again.")


stock_name = get_stock_name("Enter the name of the file ==> ", "w")

stock_date = datetime.datetime.strptime(get_stock_date("Enter the stock purchase date ==> " , "%m/%d/%Y"))

stock_sold = datetime.datetime.strptime(get_stock_date("Enter the date you sold the stock ==>" , "%m/%d/%Y"))

stock_purchased = get_stock_purchased("How many stocks were purchased on start date ==>")
tokyolerd
  • 29
  • 1
  • 10
  • How could there be a `TypeError` or `ValueError` if all you're doing is `input()`? And if it succeeds, it stops the function. I think you need to have another look at `while`, `return`, and possibly `break`. Oh, and also at recursion. And saving references. – TigerhawkT3 Apr 11 '16 at 04:26
  • The exception is raised in python 2? What do you input? – tdelaney Apr 11 '16 at 04:28
  • @TigerhawkT3 Thanks! And while I was messing around with it, it gave me two different errors (TypeError and ValueError) So that's why I made two exceptions. – tokyolerd Apr 11 '16 at 04:30
  • @tdelaney Python 3. If I input 5/10/2004 it will move on, but if I input anything else, It will give me a ValueError. – tokyolerd Apr 11 '16 at 04:31
  • Also, your parens are messed up - you're sending two arguments to the recursive call of `get_stock_date` and only one to `strptime`. – TigerhawkT3 Apr 11 '16 at 04:32
  • Is your indentation correct? – tdelaney Apr 11 '16 at 04:32
  • This example isn't runnable... there is nothing to call the function. Can you post a working example and also post the stack trace? I think your `strptime` is raising the error and the try/except is in the wrong place. But the stack trace is needed to be sure. – tdelaney Apr 11 '16 at 04:34
  • @tdelaney I believe so. I made another function similar to that one and it takes the exceptions and stuff. – tokyolerd Apr 11 '16 at 04:35
  • @tdelaney I edited it and posted the whole thing. – tokyolerd Apr 11 '16 at 04:38

3 Answers3

0

You currently have a loop that will immediately end the function and return a string in any situation I can think of off the top of my head, exceptions that (as just mentioned) I don't think will happen, a call to strptime with the wrong number of arguments, and a recursive call to your function with the wrong number of arguments. And you never save or return a meaningful value. Maybe the recursive call just has wrong indentation? Anyway, you'll have to completely restructure your code, as most of it makes little sense:

import datetime
def get_stock_date(prompt):
    while True:
        d = input(prompt)
        try:
            d = datetime.datetime.strptime(d, "%m/%d/%Y")
        except (ValueError, TypeError):
            print("Try again.")
        else:
            return d

stock_date = get_stock_date("Enter the stock purchase date ==> ")
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

To clarify Tigerhawk's initial comment: in order for the try-catch to handle TypeError or ValueError, you need to cast the input to datetime in the try statement.

import datetime

def get_stock_date(prompt):
  while True:
    try:
      return datetime.datetime.strptime(input(prompt), "%m/%d/%Y")
    except (ValueError, TypeError):
      print("Try again.")

stock_date = get_stock_date("Enter the stock purchase date ==> ")

Additionally, your initial post had strange indentation that made it look like you were making a recursive call to get_stock_date, which caused confusion.

Lastly, you will need to use raw_input if you're using Python 2.

-1

I think this is what you are looking for:

def get_stock_date(prompt):
    try:
        stock_date = datetime.datetime.strptime(prompt, "%m/%d/%Y")
        return(stock_date)
    except:
        print("Try Again.")
        prompt = input("Enter the stock purchase date ==> ")
        get_stock_date(prompt)

get_stock_date(input("Enter the stock purchase date ==> " ))
Shobeir
  • 127
  • 7
  • You are converting the passed `prompt`, which will fail, and then getting a new value with a bare `input()` call (without the "Enter the stock purchase..." prompt). – TigerhawkT3 Apr 11 '16 at 04:56
  • Thanks. Yes, that was the idea. I wanted it to ask the user to enter a valid value. – Shobeir Apr 11 '16 at 05:18