Why does Python's eval(input("Enter input: ")) change input's datatype?
Why does Python's eval(input("Enter input: ")) change input's datatype?
问题
In Python 3, I write a simple command to accept an integer input from the user thus:
x = int(input("Enter a number: "))
If I skip the int()
part and simply use x = input("Enter a number: ")
, my input's datatype is a string, not an integer. I understand that.
However, if I use the following command:
x = eval(input("Enter a number: "))
the input's datatype is 'int'.
Why does this happen?
回答1
Why does this happen?
x = eval(input("Enter a number: "))
is not the same thing as x = eval('input("Enter a number: ")')
The former first calls input(...)
, gets a string, e.g. '5'
then evaluates it, that's why you get an int
, in this manner:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-09-17 向量内积(点乘)和外积(叉乘)概念及几何意义
2021-09-17 jQuery Migrate
2021-09-17 Best way to expose resource strings to JavaScript files in ASP.NET MVC?
2021-09-17 What's the difference between sweetalert and sweetalert2?
2021-09-17 Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]
2021-09-17 sweetalert2 and xss
2021-09-17 上海居住证办理条件以及流程?