आइए देखें कि हम पायथन में कस्टम लेन () फ़ंक्शन को कैसे लागू कर सकते हैं। निम्न चरणों का उपयोग करके पहले इसे स्वयं आज़माएं।
कदम
-
उपयोगकर्ता स्ट्रिंग/सूची/टुपल से इटरेटर प्राप्त करें।
-
एक फ़ंक्शन को अपनी पसंद के अनुसार कस्टम नाम के साथ परिभाषित करें और इसे इटरेटर पास करके लागू करें।
- गिनती को 0 से प्रारंभ करें।
- लूप को तब तक चलाएं जब तक वह अंत तक न पहुंच जाए।
- गिनती में 1 की वृद्धि करें
- गिनती लौटाएं।
उदाहरण
## 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:- tutorialspoint Length of tutorialspoint is 14