Python多个if else函数并返回

时间:2018-04-25 07:39:15

标签: python python-3.x if-statement

这在python上可行吗?

def NearSourceFactor(seismic_source_distance,seismic_source_select): 
    Na = 0 
    if (seismic_source_distance <= 2) and (seismic_source_select == "A"):
        Na == 1.5
    elif (seismic_source_distance <= 5) and (seismic_source_select == "A"):
        return Na == 1.2
    elif (seismic_source_distance > 10) and (seismic_source_select == "A"):
        return Na == 1.0
    elif (seismic_source_distance <= 2) and (seismic_source_select == "B"):
        return Na == 1.3
    elif (seismic_source_distance <= 5) and (seismic_source_select == "B"):
        return Na == 1.0
    elif (seismic_source_distance > 10) and (seismic_source_select == "B"):
        return Na == 1.0
    elif (seismic_source_distance <= 2) and (seismic_source_select == "C"):
        return Na == 1.0
    elif (seismic_source_distance <= 5) and (seismic_source_select == "C"):
        return Na == 1.0
    elif (seismic_source_distance > 10) and (seismic_bldg_geometry == "C"):
        return Na == 1.0

Na = NearSourceFactor(seismic_source_distance,seismic_source_select) 

seismic_source是10而seismic_source_select = B但不幸的是答案是=“无”

我期待答案是1.0

1 个答案:

答案 0 :(得分:0)

def NearSourceFactor(seismic_source_distance,seismic_source_select): 

    if (seismic_source_distance <= 2) and (seismic_source_select == "A"):
        return 1.5
    elif (seismic_source_distance <= 5) and (seismic_source_select == "A"):
        return 1.2
    elif (seismic_source_distance > 10) and (seismic_source_select == "A"):
        return 1.0
    elif (seismic_source_distance <= 2) and (seismic_source_select == "B"):
        return 1.3
    elif (seismic_source_distance <= 5) and (seismic_source_select == "B"):
        return 1.0
    elif (seismic_source_distance >= 10) and (seismic_source_select == "B"):
        return 1.0
    elif (seismic_source_distance <= 2) and (seismic_source_select == "C"):
        return 1.0
    elif (seismic_source_distance <= 5) and (seismic_source_select == "C"):
        return 1.0
    elif (seismic_source_distance > 10) and (seismic_bldg_geometry == "C"):
        return 1.0

Na = NearSourceFactor(seismic_source_distance,seismic_source_select) 

我修复它以便它可以做你想要的,但请注意以下事项:

a)没有理由配置你想要返回的变量,你需要做的就是返回值(例如,返回1)

b)写Na == 1.0时,实际上是在比较和接收一个布尔值。

c)尝试看看你是否可以将逻辑更改为没有那么多if statments(看起来你的默认值为1,所以你可以将所有内容放在else语句中)例如