Python习题-isNum()函数的实现

题目:实现isNum函数,参数为一个字符串,如果这个字符串属于整数,浮点数或者复数的表示,则返回Ture,否则返回False。 

代码实现:

def isNum(str):
    try:
        a=eval(str)
        if type(a) == type(1) or type(a) == type(1.0) or type(a) == type(1+1j):
            return True
        else:
            return False
    except:
        return False
str1=input()
print(isNum(str1),end='')

运行结果:

问题一:如果没有a=eval(str)呢?

测试一下input的输入类型:

def isNum(str):
    try:
        a=eval(str)
        if type(a) == type(1) or type(a) == type(1.0) or type(a) == type(1+1j):
            return True
        else:
            return False
    except:
        return False
str1=input()
print(type(str1))
print(isNum(str1),end='')

输出结果为: 

  

 说明input输入默认输入类型为字符串,无论是数字还是浮点数还是复数

如果使用了eval函数之后,可以将字符串转化为整数,浮点数,以及复数,即可带入运算了

使用eval函数一般是在不知道函数类型的时候很方便使用,如果题目要求输入一个整数,可以采用int1=int(input())的方式输入

问题二:为什么要加一个try-except语句呢?

首先回顾try语句的使用方法

try:

        <要try的语句>

except  A:#A为异常的情况,比如NameError,TypeError……

       <出现A异常的时候,要输出的语句(一般为提示语句)>

except B:

        ……

3.突发奇想,这题能不能只用 try except语句实现呢?

当然不可以啦,except后接的条件只能是异常情况,不能为普通条件

猜你喜欢

转载自blog.csdn.net/m0_65485230/article/details/130325048