Python 3.6 If Statement with Criteria

问题描述 投票:0回答:3

我正在尝试使用Python 3中的条件创建经典的if语句。我能够从此代码中输入一个数字,但我无法弄清楚为什么代码不会打印“热”或“冷”。我该怎么做才能解决这个问题?我需要在这个声明中加入elif吗?

N = float(input(("Enter Number: ")))
def is_hot (N):
    if N/2>1 and N-1>1:
        print (N, "is hot")
    else:
        N/2<1 and N-1<1
        print (N, "is cold")
python python-3.x function if-statement
3个回答
0
投票

你需要修复你的函数,因为它看起来需要一个elif ...:而不是else:而且你需要实际调用函数,一旦你得到你的输入。所以...

def is_hot (N):
    if N/2>1 and N-1>1:      # N > 2
        print (N, "is hot")
    elif N/2<1 and N-1<1:    # N < 2
        print (N, "is cold")
    else:                    # N is 2
        print (N, "is just right!")
n = float(input(("Enter Number: ")))
is_hot(n)

请注意,在调用func和定义func时,我没有在两个地方都使用N.它可以工作,但就代码可读性而言,它并不总是最好的。

此外,最佳做法是在代码顶部列出您的函数。

此外,您可以并且可能应该在函数中使用与调用代码中不同的变量名称。这不是为了功能,而是为了可读性。如果有人没有注意,他们可能会看到相同的名字并认为它是一个全局变量。同样,您不必使用不同的变量名称,但最好使用不同的变量名称。如果不出意外,函数中的变量名通常更通用,并且调用代码中的变量名更具体。这是一个例子:

def merge_lists(list1, list2): # generic..
    return zip(list1, list2)
my_merged_inventory_list = merge_lists(list_of_stock_items, list_of_item_prices)

3
投票

因为你只定义了函数is_hot(N),但你没有调用它。


3
投票

正如@Brad所罗门在评论中提到的那样。而不是你应该使用elif。

N = float(input(("Enter Number: ")))
def is_hot (N):
    if (N/2>1 and N-1>1):
        print (N, "is hot")
    elif (N/2<1 and N-1<1) :
        print (N, "is cold")
    else :
        print(N,"neither hot nor cold")

is_hot(N)

注意: - 您还可以添加一个默认条件(else部分),它与任何一种情况都不匹配。更新: - 添加了Gary建议的函数调用

© www.soinside.com 2019 - 2024. All rights reserved.