k.dog k.dog - 1 month ago 6
Python Question

Function to count the the position of the first occurrence of item ‘y’ in sequence ‘z’

enter image description hereWe need to make a function that takes a list

z
and returns the index at which
y
first occurs. For example, if it's the second item in the list it will return
1
, etc. We only use
for
loops,
if else
statements and boolean values.

My function is working for all the number values I have been given, however when I put in a string as a list it only returns me one.

def positionfirst(z,y):
val=0
for item in y:
if z!=item:
val+=1
if val==len(y):
return None
else:
return val

Answer

Your picture shows your error:

print((positionfirst('d', ['abcdefg'])))

Will return 0, as 'd' != 'abcdefg', which is the only element in ['abcdefg']. You probably want

print((positionfirst('d', 'abcdefg'))).

This way the for loop iterates over the chars in the string. You can add a

print(item)

in your loop, to see what is happening. The first version will give

'abcdefg'

the second

'a'
'b'
'c'
'd'
'e'
'f'
'g'.

Those are the items you will compare against. Finally a bit shorter version of your function:

def positionfirst(z, y):
    val = 0
    for item in y:
        if z == item:
            return val
        val += 1
    return None
Comments