【问题标题】:Random key from dictionary does not recognize it's value when entered as an input字典中的随机键在作为输入输入时无法识别它的值
【发布时间】:2017-08-26 04:02:13
【问题描述】:

尝试通过字典执行此操作,但它不起作用。有针对这个的解决方法吗? 该作业要求用户从字典中猜测一个随机选择的国家的首都。当用户写出答案时,它会变成值并检查是否与国家键匹配。

import random
capitals = {'England': 'London', 'Spain': 'Madrid', 'France': 'Paris'}
rand= (random.choice (list(capitals)))
for i in capitals:
        inp= input("what's is the capital of "+rand+ ":   ")
        if inp.upper()==capitals[i].upper():
            print ("correct")
            break
        else:
            print ("think again")

【问题讨论】:

  • 您询问的是rand 的大写,但检查的是i 的大写。
  • else 应与for 对齐

标签: python dictionary random


【解决方案1】:

在第一次迭代中, inp.upper() 的值为 PARIScapitals[i].upper() 的值为 LONDON

你需要做的是,而不是比较inp.upper() == capitals[i].upper() 您应该执行以下操作

inp.upper() == capitals[rand].upper()

【讨论】:

    【解决方案2】:

    我认为不需要那个 for 循环。您应该将重试次数与资本列表的大小断开。

    您可以改用 while 循环:

    import random
    capitals = {'England': 'London', 'Spain': 'Madrid', 'France': 'Paris'}
    rand= (random.choice (list(capitals)))
    
    while True:
        inp= input("what's is the capital of "+rand+ ":   ")
    
        if inp.upper()==capitals[rand].upper():
            print ("correct")
            break
        else:
            print ("think again")
    

    【讨论】:

    • 你说得对,我只是想先把这个基本的想法付诸实践,然后再继续调整。我正在考虑将其更改为while循环。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2017-08-13
    • 1970-01-01
    相关资源
    最近更新 更多