为什么我的if语句未返回正确的值?

时间:2019-09-17 11:45:00

标签: python python-3.x

我正在创建一个程序,该程序将计算电阻器的电阻。将有大约5个独立的功能。第一个功能是查明电阻器序列是否有效,第二个功能是我检查所提供的序列,以查看电阻器序列是否有效。

#The parameter is a resistor sequence. Example NKOD.
#Returns TRUE if the length is equal to four & FALSE if its not.

def check_length(sequence):
    """ (str) -> bool

    Return whether the length of the resistor sequence is valid.

    >>> check_length('NKOD')
    True
    >>> check_length('NKO')
    False
    """

    sequence = input("Enter the resistor sequence: ")

    if len(sequence) == 4:
        print("True")
        return True
    else:
        print("False")
        return False

#The parameter is a resistor sequence with a valid length.
#Returns TRUE only if sequence contains uppercase D,K,L,N,O,R,V,W,Y,Z
#Anything else, such as lowercase will return FALSE

def check_colours(sequence):
    """ (str) -> bool

    Return True if and only if the sequence contains the letters 
    D,K,L,N,O,R,V,W,Y,Z.

    >>> check_colours('NKOD')
    True
    >>> check_colours('NKOF')
    False
    """
    if any(x in ["D","K","L","N","O","R","V","W","Y","Z"] for x in 
sequence):
        print("VALID")
        return True
    else:
        print("INVALID")
        return False

#Program
sequence = " "               
check_length(sequence)
check_colours(sequence)

输入-NKOD

输出-正确,有效

1 个答案:

答案 0 :(得分:1)

def check_colours(sequence, valid_colors="DKLNORVWYZ"):
    return all(color in valid_colors for color in sequence)

print(check_colours('NKOD'))
print(check_colours('NKOF'))

输出

True
False

笔记夫妇:

  1. 最好不要在函数主体中打印任何内容。只需返回True / False
  2. 添加有效颜色作为参数,以所有有效颜色的默认值起作用。这样,功能将更加通用-例如您可以使用它来检查颜色的子集。
  3. 如果您还想接受小写字母序列,则可能需要sequence.upper()