如何将布尔逻辑合并到定义的函数中?

How does one incorporate Boolean logic in defined functions?

我已经让这个工作了,但我试图直观地理解 if(见下文...has_botton_and_top)语句在这种情况下是如何工作的……即布尔逻辑是如何工作的:

def cylinder_surface_area(radius, height,has_top_and_bottom ):          
side_area = height * 6.28 * radius    
if has_top_and_bottom:          
  top_area = 2*3.14 * radius ** 2        
  return (side_area + top_area)     
else:return side_area 

print(cylinder_surface_area(10,5,False))

我不经常使用 Python,但当我使用时,我真的很喜欢使用 Python IDLE 编辑器。它为您的代码提供了一个非常简单的编辑器,您可以非常轻松地执行它。在编辑器方面,完全是个人喜好问题。只要您使用的编辑器满足您的所有需求并且您可以使用它,它就是最适合您的编辑器。

现在,关于你的问题:我完全可以理解你的困惑是从哪里来的。 Python 处理变量的方式(因此不需要严格输入变量)起初也让我感到困惑。从 Python 文档中,

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None False zero of any numeric type, for example, 0, 0L, 0.0, 0j. any empty sequence, for example, '', (), []. any empty mapping, for example, {}. instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. All other values are considered true -- so objects of many types are always true. Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

因此,您的函数期望您输入布尔值输入,但是即使您输入字符串、整数、双精度值或其他任何内容,它仍然能够使用定义明确的方式评估所有这些行为。我假设您的困惑来自于您可以将任何变量评估为 True 或 False,而不是布尔逻辑的核心工作方式。如果您也需要我解释布尔逻辑,请随时发表评论,我也会添加。