Python3.9.13中if语句条件为真但代码不执行的问题排查
问题分析与修复方案
问题描述
Python 3.9.13代码意图实现石头剪刀布的胜负统计逻辑,但存在以下问题:
- 打印
CLASS变量显示为s,但CLASS == "s"的比较结果为False - 所有分支内的注册提示(如
rock registered)从未打印 - 胜场、平局、负场分数始终为0
代码片段
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) wins = 0 losses = 0 ties = 0 while True: save_webcam_image() image = Image.open(file_path).convert("RGB") size = (224, 224) image = ImageOps.fit(image, size, Image.Resampling.LANCZOS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1 data[0] = normalized_image_array prediction = model.predict(data, verbose=0) index = np.argmax(prediction) class_name = class_names[index] confidence_score = prediction[0][index] CLASS = str(class_name[2:]) botChoice = random.choice(['rock', 'paper', 'scissors']) print("You choose:",CLASS) print("I choose:",botChoice) if CLASS == "r": print("rock registered") if botChoice == "rock": ties += 1 elif botChoice == "paper": losses += 1 else: wins +=1 elif CLASS == "p": print("paper registered") if botChoice == "paper": ties += 1 elif botChoice == "scissors": losses += 1 else: wins +=1 elif CLASS == "s": print("scissors registered") if botChoice == "scissors": ties += 1 elif botChoice == "rock": losses += 1 else: wins +=1 print("\nCurrent Score: "+str(wins)+" / " + str(ties) + " / " + str(losses) + "\n")
输出示例
You choose: s I choose: paper Current Score: 0 / 0 / 0
原因分析
核心问题是CLASS字符串包含不可见空白字符(如换行符\n、空格 或制表符\t)。从输出示例中You choose: s下方的空行可以推断,CLASS实际是s\n而非单纯的s,导致字符串比较不匹配,所有分支逻辑都未触发。
这种情况通常是因为class_name本身带有空白字符,切片后这些字符被保留到了CLASS中。
修复方案
步骤1:验证问题(可选但推荐)
在打印CLASS时使用repr()函数,直接显示字符串的真实内容,确认是否存在不可见字符:
print("You choose:", repr(CLASS)) # 若输出为 's\n' 或 's ',则验证了空白字符的存在
步骤2:清理CLASS字符串
对CLASS进行空白字符清理,使用strip()方法去除字符串前后的所有空白字符(包括换行、空格、制表符):
# 替换原CLASS赋值语句 CLASS = str(class_name[2:]).strip()
额外检查(可选)
如果清理后仍有问题,需确认class_names数组的内容:
- 确保
class_name[2:]确实能得到单个字符的r/p/s - 例如若
class_names中的元素是完整单词(如"rock"),则class_name[2:]会得到"ck",此时需改为取首字符:CLASS = class_name[0].strip()
修复后效果
修复后,CLASS会被清理为纯净的r/p/s,字符串比较将正常匹配,分支内的注册提示会打印,胜负分数也会正确更新。
内容的提问来源于stack exchange,提问作者The Cuber
相关产品推荐
相关产品推荐

