让我们看看如何len()
在Python中实现自定义函数。首先使用以下步骤自己尝试。
从用户字符串/列表/元组获取迭代器。
根据需要定义一个具有自定义名称的函数,然后通过传递迭代器来调用它。
计数增加1
将计数初始化为0。
循环运行直到结束。
返回计数。
## function to calculate lenght of the iterator def length(iterator): ## initializing the count to 0 count = 0 ## iterating through the iterator for item in iterator: ## incrementing count count += 1 ## returning the length of the iterator return count if __name__ == "__main__": ## getting input from the user iterator = input("Enter a string:- ") ## invoking the length function with 'iterator' print(f"Length of {iterator} is {length(iterator)}")
如果运行上面的程序,您将得到以下结果。
Enter a string:- nhooo Length of nhooo is 14