python try里面嵌套try_为何python函数内部使用try结构依然会报错

#代码方便测试改成了s=None,使用的时候改称s=input(),去掉return a b d这些

def select_num(s=None):

try:

b=float(s)

a=int(b)

if a-b==0:

return a

print('整数')

if a-b!=0:

return b

print('浮点数')

except:

try:

d=complex(s)

return d

print('虚数')

except:

a='输入的不是数字'

return a

print('输入的不是数字')

#测试

import unittest

class test(unittest.TestCase):

def test01(self):

t=select_num(s='1.1')

self.assertEqual(type(t),float)

def test02(self):

t=select_num(s='1')

self.assertEqual(type(t),int)

def test03(self):

t=select_num(s='+1')

self.assertEqual(type(t),int)

def test04(self):

t=select_num(s='-1')

self.assertEqual(type(t),int)

def test05(self):

t=select_num(s='-1.1')

self.assertEqual(type(t),float)

def test06(self):

t=select_num(s='+1.1')

self.assertEqual(type(t),float)

def test07(self):

t=select_num(s='0j')

self.assertEqual(type(t),complex)

def test08(self):

t=select_num(s='1+0j')

self.assertEqual(type(t),complex)

def test09(self):

t=select_num(s='abc')

self.assertEqual(t,'输入的不是数字')

if __name__ == '__main__':

unittest.main()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值