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

为什么我的Python脚本能接收整数输入却无法处理字符串输入?

解决Python脚本无法处理字符串输入的问题

Hey there! Let's break down why your script is throwing that error when you enter a string, and fix it right away.

问题根源

你写的是Python 2代码,这里的input()函数和Python 3里的逻辑完全不同——它会把用户输入的内容直接当作Python表达式去执行。当你输入John时,它会误以为你在引用一个叫John的变量,但这个变量根本没定义,所以就触发了NameError。而输入整数时,它能直接把数字当作表达式求值,所以能正常输出。

快速解决方案

把input()换成raw_input()就搞定了!raw_input()会把用户输入的所有内容都当作纯字符串接收,不管输入的是数字还是文本,都不会尝试解析成Python代码。

修改后的代码

#!/usr/bin/python
for i in range(5):
    value = raw_input("Enter the value : ")
    print value

测试效果

输入字符串时:

$ ./fun+for.py
Enter the value : John
John
Enter the value : Alice
Alice
...

输入整数时也依然能正常运行:

$ ./fun+for.py
Enter the value : 4
4
Enter the value : 5
5
...

额外小提示

如果之后你切换到Python 3,要记住:Python 3里已经没有raw_input()了,它把raw_input()的功能整合到了input()里,所以在Python 3中直接用input()就能接收所有字符串输入啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:47:11