如何在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
相关产品推荐
相关产品推荐

