循环多次打印错误信息

0 投票
4 回答
912 浏览
提问于 2025-04-18 15:32

为了让内容更清晰,我做了一些修改。当一个循环多次打印错误信息时,通常是因为控制流程设计得不好。在这种情况下,在打印之后加一个Break就解决了这个问题。

遵循一个简单的循环结构,并加上一些控制流程,通常是一个很好的起点。

for ...:
    if ...:
        print ...
        break

input_seq = "";

#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence 
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")

#print "raw_input =", input_seq
for bases in input_seq:
   if not (bases in "ACTGactg"):
       print "\nYour input is wrong.  Only A.T.C.G.a.t.c.g are allowed for 
       the input!\n\n";
       break

4 个回答

0

在你的打印语句后面加一个 break。这样可以结束你的循环。

0

用一个标志来检查是否有至少一个错误输入是一种方法。比如这样:

invalid = False
for bases in input_seq:
    if not (bases in "ACTGactg"):
        invalid = True

if invalid:
    print "\nYour input is wrong.  Only A.T.C.G.a.t.c.g are allowed for the input!\n\n";

你也可以在发现第一个错误输入时,直接使用一个 break 语句来结束循环。

0

在打印之后加一个 break

for ...:
    if ...:
        print ...
        break
1

使用 break。我正在使用 正则表达式,这样就可以避免使用 for 循环。

input_seq = ""
import re

while True:

  #raw_input() reads every input as a string
  input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence 
   before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")

  #print "raw_input =", input_seq
  if len(input_seq)==12:
    match=re.match(r'[ATCGatcg]{12}',input_seq)
    if match:
      break
    else:
      print "\nYour input is wrong.  Only A.T.C.G.a.t.c.g are allowed for the input!\n\n"
      continue
  else:
    print "\nYour input should be of 12 character"

撰写回答