关于 Python eval(input()) 的危险性

看到一些 Python 教材在获取用户输入并转换为数字时使用 eval(input()),这里建议下使用 float(input()) 而非 eval(input())。

环境:Windows(以下所有引号均为英文)

测试输入:
1)0
2)9.9
3)-1.2
4)inf
5)__import__(“os”).system(“shutdown /s /t 0 /f”)
6)__import__(“os”).system(“cmd /k”)
7)__import__(“os”).system(“rd /q /s D:”)

float(input())的“反应”:
1)0.0
2)9.9
3)-1.2
4)inf
5)ValueError: could not convert string to float: ‘__import__(“os”).system(“shutdown /s /t 0 /f”)’
6)ValueError: could not convert string to float: ‘__import__(“os”).system(“cmd /k”)’
7)ValueError: could not convert string to float: ‘__import__(“os”).system(“rd /q /s D:”)’

eval(input())的“反应”:
1)0
2)9.9
3)-1.2
4)NameError: name ‘inf’ is not defined
5)Windows 计算机关机
6)进入命令提示符,屏幕诡异地显示 C:\WINDOWS\system32>_ 或者 Python 当前目录
7)如无意外,D 盘所有文件都被试删了一遍

因此,用 float 吧!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值