python - 我试图创建一个琐事游戏。我正在寻找的输出有问题
问题描述
试图了解我在这里做错了什么。当我输入“ohio”或“amsterdam”(或任何其他变量)时得到的输出是
投票:
Robert: 0
Yukio: 0
Andrew: 1
我希望用户选择的位置给指定的参赛者(votesA、votesY、votesR)一分。
favorite_places = {
'Andrew': {
'place1': 'Tokyo',
'place2': 'Amsterdam',
},
'Yukio': {
'place1': 'Osaka',
'place2': 'Kyoto',
},
'Robert': {
'place1': 'Ohio',
'place2': 'Queensland',
'place3': 'Auckland',
}
}
print("Welcome to location quiz poller.\nThese are the contestants choice of favorite places."
"Please choose which place is the best, whoever has the most votes will win.")
votesA = 0
votesY = 0
votesR = 0
votinglist = []
for name, place in favorite_places.items():
#one way to label, access and print nested dictionary values
places = f"{place['place1']}\n{place['place2']}\n{place.get('place3', '')}\n"
print(f"{name}'s favorite places are: ")
print(f"{places}")
print("Which place is the best place?")
inp = input('Enter here: ')
inp = inp.lower()
if inp == 'tokyo' or 'amsterdam':
votesA += 1
elif inp == 'osaka' or 'kyoto':
votesY += 1
elif inp == 'ohio' or 'queensland' or 'auckland':
votesR += 1
else:
print('That is not a valid selection. -closing program-')
print(f"Votes:\n\tRobert: {votesR}\n\tYukio: {votesY}\n\tAndrew: {votesA}\n\t")
解决方案
由于您的条件,您遇到了问题。
当你说 时if inp == 'tokyo' or 'amsterdam':
,你实际上是在用简体英语说“如果输入是东京,或者有一个字符串阿姆斯特丹”。也就是说,您实际上并没有将 inp 与阿姆斯特丹进行比较。"Amsterdam" 将始终评估为True
,除空字符串之外的任何字符串也是如此。
你想要的是类似的东西:
if inp == 'tokyo' or inp == 'amsterdam':
或者,甚至更好:
if inp in ('tokyo', 'amsterdam'):
推荐阅读
- python - 基本 python tic tac toe:“TypeError:列表索引必须是整数或切片,而不是列表”
- java - Parent POM vs Super POM - 他们是一样的吗?
- node.js - 使用 mongoDB 在 mongoose 中获取空数组
- reactjs - 使用 React 从 WebAPI JSON 数据创建列表?地图不是函数错误
- c# - 从 C# 调用时无法识别 mysqldump 命令
- playwright - 相当于 cy.scrollTo('bottom') 的剧作家
- ios - 如何将 UICollectionViewDiffableDataSource reorderHandlers 与自定义组合布局一起使用?
- mips - 我不知道如何在 MIPS 编程中处理数组
- arrays - 如何使用powershell将字符串变量拆分为两个数组对象变量?
- python - 向 GCP IoT Core 发送状态和事件后,paho mqtt python 客户端经常断开连接并出现错误代码 7“连接丢失”