防止错误的用户输入导致程序崩溃

时间:2017-12-02 13:03:52

标签: python loops input biopython http-error

我正在尝试从UniProt数据库访问FASTA序列。当正确输入UniProt代码(一个6位数的字符串,例如P10079)时,这当前有效,但是如果输入的不正确,它会导致程序崩溃。我试图写一个循环,所以用户可以重新输入另一个代码,直到一个正确输入,虽然我仍然收到错误。这是因为我没有在函数中使用它吗? 干杯

    #Get User Input and access data from UniProt
user_input = input ("Type in your protein accession code: ")
try:
    handle = ExPASy.get_sprot_raw(user_input)
except HTTPError as e:
    user_input = input("Invalid UniProt Accession Code\nPlease enter another code:") 
else:
    record = SwissProt.read(handle)
    handle.close()
    print("Searching UniProt... \nFinding Sequence... \nChecking for matches...") 
    print (record.description)
    sequence = record.sequence
    print ("Your Fasta Sequence is: ", sequence)

1 个答案:

答案 0 :(得分:0)

问题是只有在没有异常发生时才会执行else语句。因此,如果第一个输入无效,即导致异常,而不是第二个输入,则将跳过整个else块。

其中一种可能性是将所有内容放在循环中,直到get_sprot_raw成功执行,然后获取序列信息。

from Bio import ExPASy
from Bio import SwissProt
from urllib.error import HTTPError  

while True:
    user_input = input ("Type in your protein accession code: ")
    try:
        handle = ExPASy.get_sprot_raw(user_input)
    except HTTPError as e:
        print("Invalid UniProt Accession Code\nPlease enter another code:")
    else:
        break

record = SwissProt.read(handle)
handle.close()
print("Searching UniProt... \nFinding Sequence... \nChecking for matches...") 
print (record.description)
sequence = record.sequence
print ("Your Fasta Sequence is: ", sequence)