I'm trying to write a code that will return the index at which the letter c first shows up, or None if c isn't in the string. Here's what I've come up with so far:
def find_c(f):
z = 0
c_pos = None
while c_pos is None or z < len(f):
if f[z] == 'c' or f[z] == 'C':
c_pos = z
z += 1
return c_pos
But regardless of what string I input my output is always None. Any help?
If you are still wanting to use the while loop, after you find the index of the first 'C' you probably just want to return that index instead of looping through the rest of the string.
def find_c(f):
z = 0
while z < len(f):
if f[z] == 'c' or f[z] == 'C':
return z # Returns first index where it finds 'c'
z += 1
return None # Return None if never found
However an easier way to do this instead of using a while loop would be to use a for loop enumerating through the values. You can also use the .lower()
function to make the characters lowercase so you only have to compare against 'c'
like the other commmenter mentioned.
Using a for loop instead:
def find_c(f):
for index, char in enumerate(f):
if char.lower() == 'c':
return index # Returns first index where it finds 'c'
return None # Return None if never found (reached end of string)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments