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

Python Jupyter Notebook代码问题:输入1/2无法触发对应函数如何修复

解决Jupyter Notebook中输入选择无法触发对应函数的问题

这种问题我之前在Jupyter环境里碰过好几次,大概率是输入内容的格式问题在搞鬼,咱们一步步来排查修复:

最常见的原因:输入含多余空白字符

Jupyter的输入框偶尔会让用户不小心输入前后空格,或者输入后带了隐藏的换行符,导致response的值是类似" 1"或"1\n"的形式,和你判断条件里的"1"完全不匹配。

修复方法:在获取输入后立即清理首尾空白字符,修改输入行代码:

response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:").strip()

strip()方法会自动去掉字符串首尾的所有空白字符(包括空格、换行符、制表符等),确保你拿到的是干净的"1"或"2"。

更鲁棒的处理:转成整数判断

如果想进一步提升代码的容错性(比如用户输入了带空格的数字、或者不小心输入了非数字内容),可以把输入转成整数来判断,同时处理转换失败的情况:

def cs_service_bot(): 
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:").strip()
    try:
        choice = int(response)
        if choice == 1: 
            return new_customer() 
        elif choice == 2: 
            return existing_customer() 
        else: 
            print("Sorry, we didn't understand your selection.") 
            return cs_service_bot() 
    except ValueError:
        print("Please enter a valid number (1 or 2).")
        return cs_service_bot() 

cs_service_bot()

这样不管用户输入的是" 2 "、"2\n"还是"abc",代码都能正确处理,不会直接跳转到错误提示。

最后确认:函数定义是否正确

虽然你提到没有报错,但还是建议检查new_customer()和existing_customer()这两个函数是否已经正确定义,比如函数名有没有拼写错误、括号是否齐全等——如果函数未定义,调用时会抛出NameError,但你没遇到报错的话这一步大概率没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:51:09