为什么if语句没有返回正确的值?

2024-07-05 10:00:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个程序,将计算电阻的电阻。大约有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

输出-真,有效


Tags: thefalsetruereturnifischeck序列
1条回答
网友
1楼 · 发布于 2024-07-05 10:00:55
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. 最好不要在函数体中打印任何内容。返回真/假
  2. 将有效颜色作为参数添加到默认值为所有有效颜色的函数中。这样,功能将更加通用-例如,你可以使用它来检查只是颜色的子集。你知道吗
  3. 如果您还想接受小写字母序列,您可能需要执行sequence.upper()

相关问题 更多 >