我已经定义了一个函数,如果传递了字符串,则返回长度;如果传递了整数,则输出一些内容。但是,它也在计算整数的长度。
这是我的代码:
def string_length(mystring):
if type(mystring) == int:
return "Sorry, integers don't have length"
else:
return len(mystring)
str = input ( "enter a string" )
print ( string_length(str))
输出为
"C:\Users\Naveen Reddy\PycharmProjects\Assignments\venv\Scripts\python.exe" "C:/Users/Naveen Reddy/PycharmProjects/Assignments/passing int as argument, which should have strings.py"
enter a string222
3
Process finished with exit code 0
,字符串的输出为:
"C:\Users\Naveen Reddy\PycharmProjects\Assignments\venv\Scripts\python.exe" "C:/Users/Naveen Reddy/PycharmProjects/Assignments/passing int as argument, which should have strings.py"
enter a stringabcd
4
Process finished with exit code 0