我只是想知道如何比较字典中的两个对象:
a = {}
while z:
if a[z] == a[s]:
print("Correct!")
else:
print("You don't know that country.")
z = input("Enter a country: ")
s = input("What is the capital of " + z + " ? ")
我想在Correct
时打印z = s
;当z
不在a
时,请打印You don't know that country.
答案 0 :(得分:0)
假设a
是一个以国家/地区为键,字母为值的字典,您应该进行两项单独的检查:首先,您要确保输入的国家/地区作为密钥存在于字典。为此,您应该使用in
运算符。其次,您要检查输入的大写是否与字典中的大写相匹配。为此,您使用字典上的国家/地区执行索引访问,并检查该值是否等于输入的资本:
capitals = {
'Austria': 'Vienna',
'Belgium': 'Brussels',
'Denmark': 'Copenhagen',
'France': 'Paris',
'Germany': 'Berlin',
'Netherlands': 'Amsterdam',
'Norway': 'Oslo',
'Sweden': 'Stockholm',
'Switzerland': 'Bern',
'United Kingdom': 'London'
}
while True:
country = input("Enter a country: ")
# abort the loop if the user didn’t enter anything
if not country:
break
# check whether we know that country
if country in capitals:
capital = input("What is the capital of {}? ".format(country))
if capital == capitals[country]:
print('That was correct!')
else:
print('You made a mistake there.')
else:
print('I do not know that country, sorry.')
答案 1 :(得分:-1)
我认为您正在寻找的代码如下。如果没有,请说明您的问题。
dict = {"Germany":"Berlin", "France":"Paris", "Italy":"Rome"}
while 1:
country = input("Country: ")
capital = input("Capital: ")
if(dict[country] == capital):
print("Correct!")
else:
print("Wrong!")
输入必须在行情中。