我正在尝试一个代码,在输入字符串时,我们得到字符串的长度。但是,如果输入整数或浮点数据类型,则会收到“错误数据类型”消息。请在下面找到我的代码:
def string_length(word):
if type(word) == int:
return "This is wrong data type"
elif type(word) == float:
return "Wrong data type again!"
else:
return len(word)
word = input("Enter the string: ")
print(string_length(word))
对于字符串输入,程序运行良好,但是对于整数,它返回的是位数(“字符”)而不是消息。请在下面的“输出终端”窗口中找到:
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hellooo
7
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: Hello there
11
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 123
3
PS D:\Python\Practice> python .\stringlength_exercise2.py
Enter the string: 12.20
5
你能帮我识别/纠正这个错误吗
提前谢谢
你的意思是要有一个函数为你尝试这些类型吗
由于您的输入可以是int和float,您可以使用:
相关问题 更多 >
编程相关推荐