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    
posted @   ChuckLu  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用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 上海居住证办理条件以及流程?
点击右上角即可分享
微信分享提示