Python编写数值转DOB程序触发int()转换类ValueError报错求助
报错根因
你遇到的ValueError: invalid literal for int() with base 10: <日值>完全是代码逻辑顺序颠倒导致的:
你在做日期范围合法性校验之前,就已经把原始输入的纯数字日值拼接了st/nd/rd/th这类文本后缀。比如用户输入日值1,经过那串if判断后,day变量的值已经从纯字符串"1"变成了带字母内容的"1st"。后续校验逻辑里直接执行int(day)做数值比较时,Python无法把夹杂字母的字符串转为合法整数,自然触发转换报错。
具体修复步骤
- 调整代码执行顺序:把原本提前做的日值后缀拼接逻辑,整体移动到合法性校验完成之后执行
- 做范围判断时,使用用户最开始输入的、未经过后缀拼接的原始纯数字日值做整数转换和数值对比,避免用带字母后缀的字符串转整数
- 只有当日值通过合法性校验后,再按照规则拼接对应后缀生成最终用于展示的日期格式
修正后的核心参考代码
uy = input("Enter your birth year: ") um = input("Enter the number of your birth month (1-12): ") mn_list = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # 月份映射逻辑可直接通过列表索引取值,减少冗余判断 mn = mn_list[int(um)-1] if um.isdigit() and 1<=int(um)<=12 else "" day_raw = input("please enter the day number of the date (1-31): ") # 先判断输入是否为合法数字,避免非数字内容触发转整数报错 if not day_raw.isdigit(): print("The data entered was not valid, please try again.") else: day_num = int(day_raw) # 用纯数字原始值做合法性校验 if mn == "February" and day_num <= 28: vd = True elif (mn == "April" or mn == "June" or mn == "September" or mn == "November") and day_num <= 30: vd = True elif mn in ["January", "March", "May", "July", "August", "October", "December"] and day_num <= 31: vd = True else: vd = False if vd: # 校验通过后再做后缀拼接 if day_num in (1,21,31): day_display = day_raw + "st" elif day_num in (2,22): day_display = day_raw + "nd" elif day_num in (3,23): day_display = day_raw + "rd" else: day_display = day_raw + "th" print(f"Your date of birth is the {day_display} {mn} {uy}") else: print("The data entered was not valid, please try again.")
可优化的遗留问题
- 当前2月的校验逻辑固定判定最大日值为28,没有覆盖闰年2月29天的合法场景,后续可以加闰年判断逻辑兼容这类情况
- 原有月份映射写了12个连续if/elif分支,通过列表索引直接取值可以大幅减少冗余代码
内容的提问来源于stack exchange,提问作者OAK1000101
相关产品推荐
相关产品推荐

