You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:27:02