当作为inpu输入时,字典中的随机键无法识别其值

2024-04-24 04:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

试图通过字典来做这件事,但没有用。有解决办法吗? 该作业要求用户从字典中随机选择一个国家的首都。当用户写入答案时,它将被转换为值并检查是否与国家/地区密钥匹配。你知道吗

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")

Tags: 答案用户import字典作业密钥random国家
2条回答

我不认为有必要这样做。您应该将重试次数与资本清单的大小断开连接。你知道吗

您可以改用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")

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

你需要做的是,而不是比较inp.upper() == capitals[i].upper() 你应该做以下事情

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

相关问题 更多 >