首页 > 解决方案 > 如何在 python 函数中包含布尔选项

问题描述

如何在我的 python 函数中包含布尔选项?例如,在 panda 的库中有一个方法 .sort_values() 有一个称为升序的参数,默认情况下为 True,但如果设置为 False,则该函数将进行不同的排序。该方法的详细信息对我的问题并不重要,如果您好奇,可以阅读 .sort_values() 的详细信息:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame .sort_values.html

关键是数据帧有一个参数 acsending 默认为 true Pandas.DataFrame.sort_values(self, by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last)

如何编写带有参数(如升序)的函数。假设我编写了一个名为 make_it_more 的函数,它接受一个整数或浮点 x 并向其加一。如果设置为 true 将返回 x+2 的选项。我将如何编写该函数?

def make_it_more(x, one_more=False):
    y=x+1
    if one_more==True:
        y=y+1
    return y

我如何编写 make_it_more 以便它知道只响应 one_more=True,.sort_values() 之类的函数是否检查特定字符串并在给出不匹配字符串时返回错误?

标签: python

解决方案


使用is,像这样:

def make_it_more(x, one_more=False):
    amount_to_make_it_more_by = 2 if one_more is True else 1
    return x + amount_to_make_it_more_by

否则你会遇到这样的问题:

>>> 1 == True
True
>>> 1 is True
False

推荐阅读