在下面的程序中,我从用户处获取输入并检查天气,它输入的是int类型或字符串类型:如果插入的类型为int,则程序终止并显示消息“不允许”,而如果输入的是字符串类型,它返回其长度。
这是我的程序:
#Taking i/p from user and counting length if it is string type.
def string_len (word):
if type(word)==int():
return "not allowed"
else:
return len(word)
word = input("enter a word:")#taking input from user
print(string_len(word))
输出:
PS E:\> python .\len.py
enter a word:testing
7
PS E:\> python .\len.py
enter a word:9567843 ***# here it should not count length int type so.***
7
在这里,它也返回int类型的长度,但不应返回。可能是什么问题?
答案 0 :(得分:0)
input
始终返回字符串,即使内容是数字。
您应该先尝试将输入字符串转换为整数,如果成功,则显示所需的错误消息。
def string_len (word):
try:
int(word)
return "not allowed"
except ValueError:
return len(word)
word = input("enter a word:")
print(string_len(word))