Python_test8_Robust input_190617

12 篇文章 0 订阅
12 篇文章 0 订阅

conclusion

  • complex()和complex(eval())之间的比较将能够排除非数字类型的输入。
    注意:不能直接使用eval(),否则,用户可以通过输入表达式(如100**2)输入数字,与要求不同(在实际应用中带来安全隐患)。
  • 高危函数eval()
  • try - except / assert
#coding:utf-8
'''
program2.数字的鲁棒输入
---------------------------
获得用户输入的一个数字,
可能是浮点数或复数,
如果是整数仅接收十进制形式,且只能是数字。
对输入数字进行平方运算,输出结果。
---------------------------
(1)无论用户输入何种内容,程序无错误;‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬
(2)如果输入有误,请输出"输入有误"。
'''
'''
complex()和complex(eval())之间的比较将能够排除非数字类型的输入。
注意:不能直接使用eval(),否则,用户可以通过输入表达式(如100**2)输入数字,
与要求不同(在实际应用中带来安全隐患)。
'''
print("all the test arg for program2 is 100*3 which is a malformed arg!")
print("----------")
try:
    test=input()
    print(complex(test))
    print(complex(eval(test)))
except Exception as e:   #用Exception表示一下子抓住所有异常,这个一般情况下建议在异常最后面用,用在最后抓未知的异常
        print(e)
        print("100*3 is a malformed string but complex(eval(test) is:",complex(eval(test)))
print("----------")    
#print(type(complex(4)))
#print(complex(4))

def form(a):
    form1=[int,float,complex]
    #print(type(a) in form1)
    return (type(a) in form1)
    
#form(eval(input ()))#test form()

try:
    uin=input()
    cuin=eval(uin)
except:
    print("输入有误")
try:
    if form(cuin) is True:
        print(pow(eval(uin),2))
except:
    pass
print("----------")
s = input()
try:
    if complex(s) == complex(eval(s)):
        print(eval(s)**2)
except:
    print("输入有误")
print("----------")




'''
program1.英文字符的鲁棒输入
---------------------------
获得用户的任何可能输入,
将其中的英文字符进行打印输出,
程序不出现错误。
'''
#print(ord('A'),ord('z'))
userin=input()
#print(userin)
#print("----------")
for i in userin:
    if ord(i) >=ord('A') and ord(i) <= ord('Z') or ord(i) >=ord('a') and ord(i) <= ord('z') :
        print(i,end='')
    
all the test arg for program2 is 100*3 which is a malformed arg!
----------
100*3
complex() arg is a malformed string
100*3 is a malformed string but complex(eval(test) is: (300+0j)
----------
100*3
90000
----------
100*3
输入有误
----------
ajsfhafh@#@%23678sjdfgjhASKFHJ
ajsfhafhsjdfgjhASKFHJ
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值