为什么要获取ValueError:基为10的int()的文本无效:“”

2024-09-28 01:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个程序时,我得到了一个错误,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)]))

Tags: in程序format错误birthdateintmmbirth
3条回答

让你绊倒的是slice notation,正如其他人所说。以下是一个你想做的版本:

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"}

while True:
    try:
        BirthDate = str(input("Enter Birth Date in format DDMMYY - "))
        break
    except ValueError:
        print("Error - Numbers in format DDMMYY only")

DD = BirthDate[0:2] 
MM = BirthDate[2:4]
YY = BirthDate[4:]

print("Your Birth Month is - ", (CalendarDict[int(MM)]))

注意起始位置和结束位置是如何匹配的。在

我宁愿把这个放在评论中,但是没有足够的重复次数,所以这里就这样。在

首先,Python中的数组切片要求您以[a:b]的格式给出数字,其中a是您要获取的第一个字符的索引,b是字符的索引,而不是,包括要获取的字符,因此变量MM应该是BirthDate[2:4]。在

接下来,要检查某些内容是否符合您的“DDMMYY”要求,您可能应该使用int(input("Enter your DOB),因为如果您使用str()函数将其转换为字符串,那么任何人都可以输入随机文本,并且可以逃脱惩罚(因为我相信您正在寻找整数输入)

另外,正如其中一条评论中提到的,尝试将InputError=False放在try部分,而不是{}部分。在

代码如下:

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 = int(input("Enter Birth Date in format DDMMYY - ")) # change to int() from str()
        InputError = False # set error to false since the above line got evaluated
    except ValueError:
        print("Error - Numbers in format DDMMYY only")

DD = BirthDate[0:2] 
MM = BirthDate[2:4]
YY = BirthDate[4:6]

print("Your Birth Month is - ", (CalendarDict[MM])) # converting into integer is not required since it already is one!  

您可以使用datetime模块高效地完成您想要的工作。在

import datetime

while True:
    try:
        birthDate = datetime.datetime.strptime(input("Enter Birth Date in format DD/MM/YYYY - "), "%d/%m/%Y")
        break
    except ValueError as ve:
        print(ve)
        continue

print("Your Birth Month is - {}".format(birthDate.strftime("%B")))

这导致使用:

^{pr2}$

datetime非常强大,尤其是提供的.strptime,用于解析日期,而{}则用于提供各种输出。如果您打算处理输入、输出和日期,我建议您阅读documentationdatetime很容易扩展到带有日期的更复杂的任务。在

如果您使用的是Python2,请将input更改为raw_input。在

我还删除了您的if语句-它似乎在根据MM的定义检查MM。请注意,CalendarDict是不必要的,因为您可以使用datetime的能力。我已经将while循环改为只使用控制流语句,而不是变量。在

还有一个一般提示:对变量使用camelCasingunderscore_casing,因为CapitalCasing通常是为类保留的。在

相关问题 更多 >

    热门问题