python - 压缩 if 语句以提供更准确的输出

标签 python python-3.x loops if-statement error-handling

我正在尝试编写一个简单的 if 语句,该语句取决于一组条件(列表中的出现次数为 0),但是当我的两个条件均为 0 时,我遇到了错误,只有一个语句是显示。

if let1 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
elif let2 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
elif let3 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")

我尝试过使用 or 语句,但无法生成所需的输出,通知用户他们的一个、两个或三个输入可能不在我的程序其余部分使用的文本正文中。

对于缺乏简洁的术语表示歉意,因为我对编程非常陌生。

谢谢

编辑:谢谢您的回复,但我应该给出完整的功能......

def segment_sequence(mycorpus, letter1, letter2, letter3):
    corpus_string = "".join(mycorpus)
    a = letter1
    b = letter2
    c = letter3
    d = a + b
    e = b + c
    let1 = corpus_string.count(a)
    let2 = corpus_string.count(b)
    let3 = corpus_string.count(c)
    let1let2 = corpus_string.count(d)
    let2let3 = corpus_string.count(e)
    print(let1,let2,let3)
    if let1 == 0:
        print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
    if let2 == 0:
        print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
    if let3 == 0:
        print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")
    break
    else:
        trans_prob1 = let1let2/let1
        trans_prob2 = let2let3/let2
        if trans_prob1 > trans_prob2:
            print('Here is the proposed boundary given the training corpus:\n')
            print('Proposed end of one word:' ,d,'\n')
            print('Proposed beginning of new word:' ,c,'\n')
        elif trans_prob2 > trans_prob1:
            print('Here is the proposed boundary given the training corpus:\n')
            print('Proposed end of one word: ',e,'\n')
            print('Proposed beginning of new word: ',a,'\n')
        elif trans_prob1 == trans_prob2:
            print('Both ',d,' and ',e,' are equally possible word endings')
        return()

使用 if 而不是 elif 的问题是它不会中断,然后我会收到除以 0 的错误。我不是在寻找任何太复杂的东西,只是简单而准确的用户错误消息。

再次感谢

最佳答案

不要使用elif,而是尝试使用if,如下所示:

if let1 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
if let2 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
if let3 == 0:
    print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")

关于python - 压缩 if 语句以提供更准确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451233/

相关文章:

python - 如何在Python中显式移动光标

python - "ImportError: libcublas.so.10.0"仅在使用 GUI 时用于 Tensorflow

python - 将Ubuntu上的python3连接到SQL Server 2014

python-3.x - 替代全局变量?

c++ - 执行后计数器for循环错误地递增

python - 如何创建不调用任何函数的轨迹栏? OpenCV 3.1 与 Python 2.7

python - 我想关联来自不同 DataFrame 的多个列

python - 如何序列化一个数组?

c - 这个特定函数的时间复杂度\big(O) 是多少?

python - 如何进行从 k 到给定数字并返回到零的无限循环?