在同一函数中运行两个if语句

时间:2018-10-06 20:16:01

标签: python if-statement

我正在尝试编写给定角度必须小于90度且大于0度的函数。如果角度为弧度,则必须小于pi / 2且大于0。

这是我的功能:

def is_valid_angle(s:str)-> bool:
    """
    Returns True if and only if s is a valid angle. See the assignment
    description and examples for more information regarding what's valid

    Examples:
    >>> is_valid_angle("85.3d")
    True
    >>> is_valid_angle("85.3.7D")
    False
    >>> is_valid_angle("90d")
    False
    >>> is_valid_angle("0.001r")
    True
    >>> is_valid_angle("1.5R")
    True
    """
    if s[-1]=='r''R':
        if s < (pi/2):
            if s > 0:
                return true
    if s[-1]=='d''D':
            if s < 90:
                if s > 0:
                    return true

此外,我想知道是否可以通过使用if来缩短两个else语句。

1 个答案:

答案 0 :(得分:0)

这是一种方法。

说明 tryexcept将检查字符串 except 的最后一个字符是否为数字或不。这是通过s[:-1]完成的,它返回从第一个字符到倒数第二个字符的字符串。如果不是,例如。在85.3.7D中,85.3.7不是有效数字,它将返回False。如果是,则它将检查if语句以检查弧度或角度以及角度范围。根据{{​​1}}语句,将返回相应的值(if)。

True/False

import numpy as np

def is_valid_angle(s):

    try:
        float(s[:-1])
    except ValueError:
        return False

    if (s[-1]=='r' or s[-1]=='R') and (0 < float(s[:-1]) < np.pi/2):
        return True
    elif (s[-1]=='d' or s[-1]=='D') and (0 < float(s[:-1]) < 90):
        return True
    else:
        return False
相关问题