题目要求编写isnumber()函数进行判断。
我的做法
代码:
def is_number(in_string):
“””判断字符串是否为数字”””
_if type(in_string) == int or float:
print(“This is a number!”)
else:
print(“This is not a number!”)
in_string = input(“Please input a string:”)
is_number(in_string)
结果:
Please input a string:1234
This is a number!
Please input a string:1234.55566
This is a number!
error:
Please input a string:238jdiw93e.wekf
This is a number!
没调试出来,无语= =。
参考方法一:
.isdigit()——判断是否为数字
.isalpha()——判断是否为字母
isalnum()——判断是否为数字和字母的组合
代码:
def isnumber(in_string):
“””判断字符串是否为数字”””
_print(“Is this a int number?”)
print(in_string.isdigit())
print("Is this a float number?")<br /> print(in_string.isalpha())print("Is this a string?")<br /> print(in_string.isalnum())
in_string = input(“Please input a string:”)
is_number(in_string)
结果:
error:
Please input a string:123
Is this a int number?
True
Is this a float number?
False
Is this a string?
True
error:
Please input a string:12.32
Is this a int number?
False
Is this a float number?
False
Is this a string?
False
error:
Please input a string:ksad;;,lasdk;sdp
Is this a int number?
False
Is this a float number?
False
Is this a string?
False
没调试出来,无语= =。
参考方法二:
异常:
try: 正常的操作
………………….
except: 发生异常,执行这块代码
………………….
else: 如果没有异常执行这块代码
