You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理Python中空输入字符串?解决ValueError报错问题

问题场景

用户编写的Python代码期望在输入为空时将score设为7,但输入为空时脚本崩溃,抛出ValueError: invalid literal for int() with base 10: ''错误,原代码如下:

score = int(input("Anzahl Schläge auf Bahn " + str(bahn + 1) + ": "))
if score <= 0:
    score = 7
elif score >= 7:
    score = 7
elif score == '':
    score = 7
scores.append(score)

用户尝试将空字符串转为浮点数但未成功,同时困惑其他程序处理空输入的方式。

解决方案

最终通过异常处理器实现需求,可行代码如下:

# Punkte pro Bahn
while bahn < bahnen:
    print()
    scoreCheck = int(0)
    while scoreCheck <= 0:
        try:
            scoreCheck = int(input("Anzahl Schläge auf Bahn " + str(bahn + 1) + ": "))
        except ValueError:
            print("gib bitte eine ZAHL > 0 ein"), print()
    
        else:
            if scoreCheck <= 0:
                print("gib bitte eine ZAHL > 0 ein"), print()
            elif scoreCheck > MaxSchleg:
                score = MaxSchleg +1
            else:
                score = int(scoreCheck)
    bahn += 1

这段代码仅接受正整数输入,完全符合预期功能。

内容的提问来源于stack exchange,提问作者HerrStadtGraf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 01:00:54