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

如何在Python中实现指定输入对应返回特定响应的功能?

代码修改方案

你当前的代码存在两个核心问题:

  • Python要求if分支下的执行代码必须缩进,你现有代码中print语句没有缩进,运行会直接抛出语法错误
  • 只处理了输入为5的场景,没有对其他输入做分支判断

基础修改版(满足输入20返回指定内容的需求)

response = input('Type a number')
if response == '5':
    print('5 was the correct answer')
else:
    print(f'{response} was NOT the correct answer')

多响应扩展版(适配多输入对应不同返回的需求)

如果后续需要新增更多输入对应的响应规则,用字典映射的方式维护更方便:

response = input('Type a number')
# 可自由扩展输入和对应返回内容的映射规则
response_mapping = {
    '5': '5 was the correct answer',
    '20': '20 was NOT the correct answer',
    '3': '3 is the test answer'
}
# 匹配到规则输出对应内容,未匹配到输出默认提示
print(response_mapping.get(response, f'{response} is undefined input'))

输入合法性优化版

如果需要避免用户输入非数字内容导致逻辑异常,可以增加类型校验:

try:
    response = int(input('Type a number'))
except ValueError:
    print('Please enter a valid integer')
else:
    if response == 5:
        print('5 was the correct answer')
    else:
        print(f'{response} was NOT the correct answer')

内容的提问来源于stack exchange,提问作者chrqma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:54:05