Python循环迭代问题

Meg*_*gan 4 python iteration loops

两个版本,返回相反的答案,但总是一个出错.我不确定我哪里出错了.我已经尝试了一系列其他选项,但这似乎是最接近的.编辑:需要循环

目标:识别列表中的元素,识别元素何时不在列表中,识别列表何时为[],相应地返回字符串.

def search_for_string(a_list, search_term):
    i=0
    for search_term in a_list:
        i += 1
        if a_list[i] == search_term: 
            return 'string found!' 
        elif a_list[i] != search_term:
            return 'string not found2'
    if len(a_list) == 0:
        return 'string not found'

apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)


def search_for_string(a_list, search_term):
    i=0
    for search_term in a_list:
        if a_list[i] == search_term: 
            return 'string found!' 
        elif a_list[i] != search_term:
            return 'string not found2'
        i += 1
    if len(a_list) == 0:
        return 'string not found'

apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)
Run Code Online (Sandbox Code Playgroud)

其他测试:

apple = search_for_string(['a', 'b', 'c'], 'b')
apple = search_for_string([], 'b')
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 9

Python让你的生活变得非常容易:

def search_for_string(a_list, search_term):
    if search_term in a_list:
        return 'string found!'
    return 'string not found'
Run Code Online (Sandbox Code Playgroud)