python - 在 for 循环中添加了 else 语句,现在即使 if 为 true,也只会打印 else 部分
问题描述
这是我的第一门计算机科学课程,如果这个答案真的很明显,请原谅我。我写了下面的代码,它工作得很好。我只需要添加一个 else 语句来说明无效的名称输入。
这是之前的:
mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
name = input("Please enter a name:")
这是之后:
mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
else:
print("That name is not in this class.")
name = input("Please enter a name:")
name = input("Please enter a name:")
它只是不断打印“该名称不在此类中”。无论我输入什么。SOS
解决方案
每次循环都会评估该if
语句,因此您需要跟踪名称是否已找到,然后仅在最后打印。
例如:
while name!='q':
found = False
for x in range(20):
if mynames[x] == name:
print(mynames[x], "scored", myscores[x])
found = True
break
if not found:
print("That name is not in this class.")
name = input("Please enter a name:")
推荐阅读
- javascript - 使用 vanilla JS 突出显示活动选项卡
- jquery-ui - 使用 jQuery-ui 自动完成显示加载 gif
- javascript - 如何在three.js中将自定义字体渲染的大小设置为屏幕外画布?
- android - Android Firebase - 如何获取子节点数据
- c++ - 没有 layoutChanged,QTreeView 新行不可见
- php - preg_match_all 使用 $row 计算匹配词
- android - 不适用于包名称和 firebase
- php - Laravel - 在 whereHas Closure 内动态访问模型属性
- r - 如何将列表的一部分写入一个数据框中?
- android - Oreo FCM 通知图标在应用程序被终止时不显示(完全关闭)