如何使用while循环索引匹配字符串元素 实现查询国家对应首都的功能
国家首都查询函数实现(while循环版本)
完整代码
# 补全原始数据末尾缺失的右括号 countries_and_capitals = (['Afghanistan', 'Kabul'], ['Albania', 'Tirana (Tirane)'], ['Algeria', 'Algiers'], ['Andorra', 'Andorra la Vella'], ['Angola', 'Luanda'], ['Antigua and Barbuda', "Saint John's"], ['Argentina', 'Buenos Aires'], ['Armenia', 'Yerevan'], ['Australia', 'Canberra']) def get_capital_from_the_country(cntry): index = 0 total = len(countries_and_capitals) while index < total: country, capital = countries_and_capitals[index] # 直接精确匹配,如需忽略大小写可改为 if country.lower() == cntry.lower(): if country == cntry: return capital index += 1 # 无匹配结果返回提示 return "无对应国家的首都记录"
使用测试
- 查询澳大利亚首都:
get_capital_from_the_country("Australia")→ 返回值为Canberra - 查询安提瓜和巴布达首都:
get_capital_from_the_country("Antigua and Barbuda")→ 返回值为Saint John's - 查询未录入国家:
get_capital_from_the_country("Japan")→ 返回值为无对应国家的首都记录
内容的提问来源于stack exchange,提问作者jump
相关产品推荐
相关产品推荐

