如何在Python中将for循环代码转换为while循环?
我试图编写一个名为has_no_e的函数,该函数将字符串作为参数,如果字符串包含字母e,则返回False;如果字符串不包含字母e,则返回True 我已经用for循环编写了这个函数,但是我没有用while循环编写一个类似的函数来做同样的事情 下面是我的for循环函数:如何在Python中将for循环代码转换为while循环?,python,for-loop,while-loop,Python,For Loop,While Loop,我试图编写一个名为has_no_e的函数,该函数将字符串作为参数,如果字符串包含字母e,则返回False;如果字符串不包含字母e,则返回True 我已经用for循环编写了这个函数,但是我没有用while循环编写一个类似的函数来做同样的事情 下面是我的for循环函数: def has_no_e(word): for letters in word: if letters == "e": return False retur
def has_no_e(word):
for letters in word:
if letters == "e":
return False
return True
我写的函数是:
def has_no_e2(word):
index = 0
while index < len(word):
if word[index] != "e":
index += 1
return False
return True
def没有e2(字):
索引=0
而索引
你能告诉我while循环的函数有什么问题吗?它每次都返回False,这与是否有“e”无关。您不需要创建函数,它已经存在,名为find() has_e=word.find(“e”) 函数要么返回字母的确切位置,要么返回-1(如果不存在)
有两种方法可以实现相同的修复。与现有代码保持更紧密联系的是
def has_no_e2(word):
index = 0
while index < len(word):
if word[index] != "e":
index += 1
continue # skip the rest of the loop and go back to the top
return False
return True
def没有e2(字):
索引=0
而索引
更好的是
def has_no_e2(word):
index = 0
while index < len(word):
if word[index] == "e":
return False
index += 1
return True
def没有e2(字):
索引=0
而索引
请注意,以下两段代码大致相当:
for elem in iterable:
# code
_index = 0
while _index < len(iterable):
elem = iterable[_index]
# code
_index += 1
对于iterable中的元素:
#代码
_索引=0
而_指数
它比这更复杂,因为for
循环通常使用迭代器而不是索引,但你明白了。试试:
index = 0
while index < len(word):
if word[index] != "e":
index += 1
else:
return False
return True
index=0
而索引
当前,您的代码在第一个循环结束时返回false。您可以使用以下运算符:
def has_no_e(word):
return 'e' not in word
如果您确实需要一个while循环:
def while_has_no_e(word):
characters = list(word)
while characters:
if characters.pop() == 'e':
return False
return True
print(has_no_e('foo'))
print(has_no_e('element'))
print(while_has_no_e('foo'))
print(while_has_no_e('element'))
输出:
def没有e1(_字符串):
返回“e”不在\u字符串中
def没有e2(_字符串):
返回_string.find('e')=-1
def没有e3(_字符串):
while\u字符串:
如果_字符串[0]=“e”:
返回错误
_字符串=_字符串[1:]
返回真值
如果名称=“\uuuuu main\uuuuuuuu”:
单词='和字母'e`'
印刷品(
没有e1(字),
没有e2(单词),
没有e3(单词),
)
word='没有它'
印刷品(
没有e1(字),
没有e2(单词),
没有e3(单词),
)
一些更改,您就可以开始了,您只需将为循环编写的任何条件写入while,就这样:
def没有e2(字):
索引=0
而索引
现在让我给你一句话:
>string='hello'
>>>如果string.count('e')>0,则为False,否则为True
假的
#更改内容
>>>字符串='hlo'
>>>如果string.count('e')>0,则为False,否则为True
真的
True
False
True
False