Issue
I want to write a function which will find out the length of a list based on user input. I don't want to use the in-built function len(). PLease help me. Function which i have written is working for strings but for lists it is failing.
#function for finding out the length
def string_length(a):
for i in a:
j+=1
return j
#taking user input
a = input("enter string :")
length = string_length(a)
print("length is ", length)
Solution
You probably need to initialize your variable j
(here under renamed counter
):
def string_length(my_string):
"""returns the length of a string
"""
counter = 0
for char in my_string:
counter += 1
return counter
# taking user input
string_input = input("enter string :")
length = string_length(string_input)
print("length is ", length)
This could also be done in one "pythonic" line using a generator expression, as zondo has pointed out:
def string_length(my_string):
"""returns the length of a string
"""
return sum(1 for _ in my_string)
Answered By - Reblochon Masque
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.