当我运行这个程序时,我得到了一个错误,ValueError:invalid literal for int(),基数为10:'',我觉得这是与int和str转换有关,但我真的不太确定,有什么帮助,谢谢:)
CalendarDict = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May",
6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"Novemeber",
12:"December"}
InputError = True
while InputError:
try:
BirthDate = str(input("Enter Birth Date in format DDMMYY - "))
except ValueError:
print("Error - Numbers in format DDMMYY only")
InputError = False
DD = BirthDate[0:2]
MM = BirthDate[3:4]
YY = BirthDate[4:6]
if MM == BirthDate[3:4]:
print("Your Birth Month is - ", (CalendarDict[int(MM)]))
让你绊倒的是slice notation,正如其他人所说。以下是一个你想做的版本:
注意起始位置和结束位置是如何匹配的。在
我宁愿把这个放在评论中,但是没有足够的重复次数,所以这里就这样。在
首先,Python中的数组切片要求您以
[a:b]
的格式给出数字,其中a是您要获取的第一个字符的索引,b是字符的索引,而不是,包括要获取的字符,因此变量MM应该是BirthDate[2:4]
。在接下来,要检查某些内容是否符合您的“DDMMYY”要求,您可能应该使用
int(input("Enter your DOB
),因为如果您使用str()函数将其转换为字符串,那么任何人都可以输入随机文本,并且可以逃脱惩罚(因为我相信您正在寻找整数输入)另外,正如其中一条评论中提到的,尝试将}部分。在
InputError=False
放在try
部分,而不是{代码如下:
您可以使用
datetime
模块高效地完成您想要的工作。在这导致使用:
^{pr2}$datetime
非常强大,尤其是提供的.strptime
,用于解析日期,而{datetime
很容易扩展到带有日期的更复杂的任务。在如果您使用的是Python2,请将
input
更改为raw_input
。在我还删除了您的
if
语句-它似乎在根据MM的定义检查MM。请注意,CalendarDict
是不必要的,因为您可以使用datetime
的能力。我已经将while
循环改为只使用控制流语句,而不是变量。在还有一个一般提示:对变量使用
camelCasing
或underscore_casing
,因为CapitalCasing
通常是为类保留的。在相关问题 更多 >
编程相关推荐