我的问题是是否有人可以帮我调试这段代码:
import datetime
print ("What is your date of birth? ")
dateofbirth = input("Please type your date of birth in a YYYY-MM-DD format ")
year, month, day = map(int, dateofbirth.split('-'))
dateofbirth1 = datetime.date(year, month, day)
today = datetime.date.today()
open('dateutil.tar').read()
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(today, dateofbirth1).years
if difference_in_years < 18
print ("Sorry, you are not eligible to vote.")
else
print ("You are over 18 and thus eligible to vote.")
我的目标是尝试编写一段代码,如果有人超过 18 岁并因此有资格投票,它就可以解决。这意味着通过要求该人输入他们的出生日期,然后计算出他们的出生日期和今天日期之间的年差,然后使用 IF 语句告诉他们是否能够投票(即如果年差大于或小于 18)。
目前我在调试这段代码时遇到了几个问题。首先,在第 10 行有一个语法错误,我不确定如何纠正。其次,如果我删除最后 4 行并再次运行代码,我会收到以下错误:
Traceback (most recent call last):
File "C:\removed\canyouvote.py", line 8, in <module>
open('dateutil.tar').read()
File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 5: character maps to <undefined>
但是,很可能还有其他我目前无法解决的错误。可悲的是,由于我对编程很陌生,我的知识和经验并不是很好,所以任何帮助都将不胜感激!在尝试研究解决方案时,我尝试使用我不熟悉的编码,所以请纠正我的错误。
非常感谢您!
最佳答案
您获得 UnicodeDecodeError
的原因是您试图打开并阅读 tarball ——也就是说,一个二进制文件——就好像它是一个文本文件一样。
当您这样做时,Python 会尝试解释该文件的任意字节,就好像它们表示您的默认字符集 (cp1252) 中的字符一样,但是如果幸运的话,这会给您一个异常(exception),或者如果您成功地给您完整的垃圾你不是。尝试打开dateutil.tar
在文本编辑器中查看它作为文本的意义。
很难说如何解决这个问题,因为不清楚你为什么要首先打开和读取那个文件。如jonrsharpe指出,你没有对结果做任何事情。我无法想象你会对他们做什么。
如果你想制作 dateutil
是可导入的,这样做的方法不是对脚本中的 tarball 做任何事情,而是在运行它之前从脚本外部安装模块。最简单的方法就是 pip install dateutil
,它会自动找到dateutil
的正确版本,下载它,解压缩它,然后安装它以供您的所有脚本使用。
话虽如此,确实没有必要 dateutil
这里。如果你只是减去两个 datetime
对象,你会得到一个 timedelta
目的。
同时,SyntaxError
来自这段代码:
if difference_in_years < 18
print ("Sorry, you are not elegible to vote.")
else
print ("You are over 18 and thus elegible to vote.")
在 Python 中,复合语句如
if
和 else
套件前需要一个冒号,套件必须缩进。见First Steps Towards Programming本教程的部分。所以:if difference_in_years < 18:
print("Sorry, you are not eligible to vote.")
else:
print("You are over 18 and thus eligible to vote.")
(另请注意,我已删除括号前的空格,以适应 PEP 8 样式,并正确拼写“合格”。)
关于python - 如何使用 Python 找到两个日期之间的年差? (计算一个人是否超过 18 岁),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26620919/