从For循环中制作While循环

时间:2020-09-30 13:13:15

标签: python-3.x for-loop while-loop

我编写了这段代码,它对以下各项工作正常:

编写代码以检查通过input()给出的字符串是否仅包含有效字符,但是一旦到达一个无效字符,则停止。因此,如果字符串有效,则打印有效的 string 。如果字符串无效,则在该点之前打印无效的字符串

但是现在我必须为此使用while循环,但我无法完成它,你们可以帮我还是向我解释如何在保持完全相同的功能的同时将这段代码转换为while循环。

file = input()

invalid_letter_found = False
correct_letters = []

for current_letter in file:
    if current_letter in ['A', 'T', 'G', 'C']:
        correct_letters.append(current_letter)
        continue
    elif current_letter != ['A', 'T', 'G', 'C']:
        invalid_letter_found = True
        break
if invalid_letter_found == True:
    print(f'invalid {"".join(correct_letters)}')
else:
    print(f'valid {"".join(correct_letters)}')

2 个答案:

答案 0 :(得分:1)

此程序将在查询中提供与上述程序完全相同的输出

file = input()
n=len(file)
lst=[]
for alp in file:  # this will convert the string to list, you can use any other method if you don't want for loop
    lst.append(alp) #Here the conversion ends
invalid_letter_found = False
correct_letters = []
i= 0
while i < n:
    if lst[i] in ["A", "T", "G", "C"]:
        correct_letters.append(lst[i])
        i += 1
        continue
    elif lst[i] != ["A", "T", "G", "C"]:
        invalid_letter_found = True
        break
if invalid_letter_found == True:
    print(f'invalid {"".join(correct_letters)}')
else:
    print(f'valid {"".join(correct_letters)}')

答案 1 :(得分:0)

虽然您需要使用while循环的唯一原因是这是否是一项家庭作业问题,但以下是正确方向的提示:

  1. 您可以使用string slicing
  2. 逐步删除字符串中的字母
current_letter = file[0]
file = file[1:]
  1. 您可以将字符串长度用作while循环的条件-一旦字符串长度为零,就可以完成:
while len(file):