มาดูกันว่าเราจะใช้ฟังก์ชัน len() แบบกำหนดเองใน Python ได้อย่างไร ลองทำด้วยตัวเองก่อนโดยใช้ขั้นตอนต่อไปนี้
ขั้นตอน
-
รับตัววนซ้ำจากสตริงผู้ใช้/รายการ/ทูเพิล
-
กำหนดฟังก์ชันด้วยชื่อที่กำหนดเองตามที่คุณต้องการและเรียกใช้โดยส่งตัววนซ้ำ
- เริ่มต้นการนับเป็น 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