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

Python编写板球计分板时字符串比较逻辑异常该如何解决?

问题原因

  • 逻辑运算符使用错误
    你当前的判断条件(whoWonTheToss != team1) or (whoWonTheToss != team2)逻辑上永远为真:任意输入值都不可能同时等于team1和team2,所以只要两个队伍名称不同,不管输入什么内容,都会满足「不等于team1 或者 不等于team2」的条件,触发无效提示。比如你输入的是RCB,它不等于CSK,所以or条件成立。
  • 输入存在多余空格
    从运行日志可以看到你输入team1的时候输入的是RCB (末尾带空格),而后续掷币获胜方输入的是RCB(无末尾空格),就算修正了逻辑运算符,两个字符串也会因为空格差异被判定为不相等。

修复方案

  1. 将判断条件中的or替换为and,只有当输入内容既不等于team1也不等于team2时,才判定为无效输入
  2. 对所有用户输入调用strip()方法,自动去除首尾的空白字符,避免误输入的空格影响匹配结果

修改后的代码如下:

print("\nWelcome to our Cricket Score Board program")
# 输入时去除首尾空格
team1 = input("Enter team 1 name: ").strip()
team2 = input("Enter team 2 name: ").strip()

print("Do the toss")
whoWonTheToss = input("Who won the toss: ").strip()
print(whoWonTheToss)

# 替换or为and
if (whoWonTheToss != team1) and (whoWonTheToss != team2):
    print("Enter a valid choice")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:09:04