问题描述
我有一个编程作业。一切都进行得很顺利,直到使用Try / Except遇到问题为止。如果我输入有效的日期时间,程序将使用它并继续运行,但是如果我使用有效的日期时间格式,则异常不会响应。
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.
此处是我的代码:
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 ==>")
推荐答案
为阐明Tigerhawk的最初评论:为了使try-catch处理TypeError或ValueError,您需要在try语句中将输入转换为datetime。
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 ==> ")
此外,您的姓名首字母帖子中有奇怪的ind该语句看起来像是您递归调用get_stock_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.
最后,如果您使用的是Python 2,则需要使用raw_input。
Lastly, you will need to use raw_input if you're using Python 2.
这篇关于日期时间模块-ValueError try / except无法正常工作python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!