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

Python度假成本计算程序:如何在输入语句中添加可选城市列表

解决方法

你可以通过将城市选项列表转换为换行分隔的字符串,拼接在输入提示文本中来实现需求。以下是两种实用的实现方式:

方式一:直接使用列表构造提示语

# 定义城市选项列表
city_options = [
    '1: Paris:      £100', 
    '2: Belgium:    £90',
    '3: Denmark:    £90',
    '4: Sydney:     £210',
    '5: Bangkok:    £200',
    '6: Venice:     £100'
]

# 将列表元素用换行符连接成字符串
options_text = '\n'.join(city_options)

# 构造包含选项的提示语
prompt = f"Please let me know which city you will be flying to:\n{options_text}\nEnter the number of your choice: "

# 获取用户输入
city_flight = input(prompt)

运行这段代码时,用户会看到完整的选项列表,并且被提示输入对应编号,交互逻辑更清晰。

方式二:用字典存储信息(更易维护)

如果后续需要修改城市或价格,用字典存储对应关系会更灵活,同时还能轻松验证用户输入的有效性:

# 存储选项编号、城市名称和对应价格
city_info = {
    '1': ('Paris', 100),
    '2': ('Belgium', 90),
    '3': ('Denmark', 90),
    '4': ('Sydney', 210),
    '5': ('Bangkok', 200),
    '6': ('Venice', 100)
}

# 动态生成选项文本
options_text = '\n'.join([f"{num}: {city}:      £{price}" for num, (city, price) in city_info.items()])

# 构造提示语
prompt = f"Please let me know which city you will be flying to:\n{options_text}\nEnter the number of your choice: "
city_flight = input(prompt)

# 验证输入并提取信息
if city_flight in city_info:
    selected_city, flight_cost = city_info[city_flight]
    print(f"Selected city: {selected_city}, Flight cost: £{flight_cost}")
else:
    print("Invalid input! Please enter a number between 1 and 6.")

这种方式不仅能展示选项,还能直接获取选中城市的价格,为后续计算度假总成本提供便利。

内容的提问来源于stack exchange,提问作者SamWestlake-Cann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:10:16