Reputation: 77
I have this Question: Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.) my code:
def is_member(a):
a = raw_input("Give a Number: ")
b = ['hallo', '120', 'me']
for i in a:
if a[i] == b:
return True
else:
return False
print is_member('a')
Mit IDLE console , I come : TypeError: string indices must be integers, not str .Where is the problem ?? . Very Thanks for yours help!
Upvotes: 1
Views: 291
Reputation: 476594
Your a
is a str
(string), next you use a for
loop to iterate over the characters of that string?
You probably want to do it the opposite way. Either:
for i in b:
if a == i:
return True
return False
Or:
for i in range(len(b)):
if a == b[i]:
return True
return False
Note that you can't return False
in the else
case: it is not because the first check fails, the remaining checks cannot eventually yield an element that is equivalent. You thus have to loop through the entire collection before you know for sure the element is not in the list*.
Upvotes: 3
Reputation: 236
First of all, if you want to use raw_input
then you don't need the parameter of is_member
because a
always becomes the return value of raw_input
.
Also a
is a string
, not list
, so i
is string
.
Example:
>>> for i in 'abc':
... print(i)
...
a
b
c
is_member
should be:
def is_member():
a = raw_input("Give a Number: ")
b = ['hallo', '120', 'me']
return a in b
print is_member()
or
def is_member(a):
b = ['hallo', '120', 'me']
return a in b
print is_member('a')
Upvotes: 1
Reputation: 738
Your problem is that the for loop sets i
to hold the values of a
in turn, and so when you reference a[i]
, it tries to find a['hallo']
, which it clearly cannot. You simply need to replace a[i]
with i
, and then it should work perfectly.
Upvotes: 0