python 菜鸟:返回值_Python中的真实值和虚假值:详细介绍

 2023-09-06 阅读 28 评论 0

摘要:python 菜鸟:返回值 欢迎 (Welcome) In this article, you will learn: 在本文中,您将学习: What truthy and falsy values are. 什么是真实和虚假的价值观。 What makes a value truthy or falsy. 是什么使价值真实或虚假。 How to use the bool() function to

python 菜鸟:返回值

欢迎 (Welcome)

In this article, you will learn:

在本文中,您将学习:

  • What truthy and falsy values are.

    什么是真实和虚假的价值观。
  • What makes a value truthy or falsy.

    是什么使价值真实或虚假。
  • How to use the bool() function to determine if a value is truthy or falsy.

    如何使用bool()函数确定值是真实的还是虚假的。

  • How to make objects from user-defined classes truthy or falsy using the special method __bool __.

    如何使用特殊方法__bool __使用户定义的类的对象正确或错误。

Let's begin! ✨

让我们开始!

真值与真值和虚假值 (Truth Values vs. Truthy and Falsy Values)

Let me introduce you to these concepts by comparing them with the values True and False that we typically work with.

让我通过将它们与我们通常使用的TrueFalse值进行比较来向您介绍这些概念。

Expressions with operands and operators evaluate to either True or False and they can be used in an if or while condition to determine if a code block should run.

具有操作数和运算符的表达式的计算结果为TrueFalse ,可以在ifwhile条件中使用它们来确定是否应运行代码块。

Here we have an example:

这里有一个例子:

# Expression 5 < 3
>>> if 5 < 3:print("True")
else:print("False")# Output
False

In this example, everything is working as we expected because we used an expression with two operands and an operator 5 < 3.

在此示例中,一切都按预期工作,因为我们使用了带有两个操作数和运算符5 < 3的表达式。

But what do you think will happen if we try to run this code?

但是,如果我们尝试运行此代码,您认为会发生什么?

>>> a = 5>>> if a:print(a)

Notice that now we don't have a typical expression next to the if keyword, only a variable:

注意,现在在if关键字旁边没有典型的表达式,只有一个变量:

Surprisingly, the output is:

令人惊讶的是,输出为:

5

If we change the value of a to zero, like this:

如果我们的值更改a零,就像这样:

>>> a = 0>>> if a:print(a)

There is no output.

没有输出。

I'm sure that you must be asking this right now: what made the code run successfully?

我确定您现在必须问这个问题: 是什么使代码成功运行?

The variable a is not a typical expression. It doesn't have operators and operands, so why did it evaluate to True or False depending on its value?

变量a不是典型的表达式。 它没有运算符和操作数,那么为什么根据其值求值为TrueFalse

The answer lies on the concept of Truthy and Falsy values, which are not truth values themselves, but they evaluate to either True or False.

答案在于Truthy和Falsy值的概念,它们本身不是真值,但它们的评估结果为TrueFalse

真实和虚假的价值观 (Truthy and Falsy Values)

In Python, individual values can evaluate to either True or False. They do not necessarily have to be part of a larger expression to evaluate to a truth value because they already have one that has been determined by the rules of the Python language.

在Python中,单个可以评估为TrueFalse 。 它们不一定必须是较大表达式的一部分才能评估为真值,因为它们已经具有由Python语言规则确定的表达式。

The basic rules are:

基本规则是:

  • Values that evaluate to False are considered Falsy.

    评估为False值被视为Falsy

  • Values that evaluate to True are considered Truthy.

    评估为True值被视为Truthy

According to the Python Documentation:

根据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 (and, or, not).

可以测试任何对象的真值,以在ifwhile条件中使用,或用作以下布尔运算的操作数(和,或非)。

🔸布尔上下文 (🔸 Boolean Context)

When we use a value as part of a larger expression, or as an if or while condition, we are using it in a boolean context.

当我们将值用作较大表达式的一部分或作为ifwhile条件时,我们在布尔上下文中使用它。

You can think of a boolean context as a particular "part" of your code that requires a value to be either True or False to make sense.

您可以将布尔上下文视为代码的特定“部分”,该部分要求一个值必须为TrueFalse才有意义。

For example, (see below) the condition after the if keyword or after the while keyword has to evaluate to either True or False:

例如,(见下文) if关键字之后或while关键字之后的条件必须计算为TrueFalse

💡 Tip: The value can be stored in a variable. We can write the name of the variable after the if or while keyword instead of the value itself. This will provide the same functionality.

💡 提示:值可以存储在变量中。 我们可以在ifwhile关键字之后写变量的名称, while不是值本身。 这将提供相同的功能。

Now that you know what truthy and falsy values are and how they work in a boolean context, let's see some real examples of truthy and falsy values.

既然您知道了什么是真实值和虚假值,以及它们在布尔上下文中如何工作,让我们看一下真实和虚假值的真实示例。

🔹虚假价值观 (🔹 Falsy Values)

Sequences and Collections:

序列和集合:

  • Empty lists []

    空清单[]

  • Empty tuples ()

    空元组()

  • Empty dictionaries {}

    空字典{}

  • Empty sets set()

    空集set()

  • Empty strings ""

    空字符串""

  • Empty ranges range(0)

    空范围range(0)

Numbers

号码

  • Zero of any numeric type.

    任何数字类型的零。
  • Integer: 0

    整数: 0

  • Float: 0.0

    浮点数: 0.0

  • Complex: 0j

    复杂度: 0j

Constants

常数

  • None

    None

  • False

    False

Falsy values were the reason why there was no output in our initial example when the value of a was zero.

假值是当我们的初始示例中a的值为零时没有输出的原因。

The value 0 is falsy, so the if condition will be False and the conditional will not run in this example:

0是伪造的,因此if条件将为False并且该条件将在此示例中不运行:

>>> a = 0
>>> if a:print(a)# No Output

🔸真实价值观 (🔸 Truthy Values)

According to the Python Documentation:

根据Python文档 :

By default, an object is considered true.

默认情况下,对象被视为true

Truthy values include:

真实值包括:

  • Non-empty sequences or collections (lists, tuples, strings, dictionaries, sets).

    非空序列或集合(列表,元组,字符串,字典,集合)。
  • Numeric values that are not zero.

    不为零的数值。
  • True

    True

This is why the value of a was printed in our initial example because its value was 5 (a truthy value):

这就是为什么在我们最初的示例中打印a的值的原因,因为a的值为5(真实值):

>>> a = 5>>> if a:print(a)# Output5

🔹内置的bool()函数 (🔹 The Built-in bool() Function)

You can check if a value is either truthy or falsy with the built-in bool() function.

您可以使用内置的bool()函数检查值是真还是假。

According to the Python Documentation, this function:

根据Python文档 ,此功能:

Returns a Boolean value, i.e. one of True or False. x (the argument) is converted using the standard truth testing procedure.

返回一个布尔值,即TrueFalse 。 使用标准真值测试过程转换x(自变量)

You only need to pass the value as the argument, like this:

您只需要将值作为参数传递,如下所示:

>>> bool(5)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool({5, 5})
True
>>> bool(-5)
True
>>> bool(0.0)
False
>>> bool(None)
False
>>> bool(1)
True
>>> bool(range(0))
False
>>> bool(set())
False
>>> bool({5, 6, 2, 5})
True

💡 Tip: You can also pass a variable as the argument to test if its value is truthy or falsy.

提示:您还可以将变量作为参数传递,以测试其值是真还是假。

🔸真实的例子 (🔸 Real Examples)

One of the advantages of using truthy and falsy values is that they can help you make your code more concise and readable. Here we have two real examples.

使用真实值和虚假值的优点之一是,它们可以帮助您使代码更简明易懂。 这里我们有两个真实的例子。

Example: We have this function print_even() that takes as an argument a list or tuple that contains numbers and only prints the values that are even. If the argument is empty, it prints a descriptive message:

示例:我们有一个函数print_even() ,该函数将包含数字的列表或元组作为参数,只打印偶数的值。 如果参数为空,则输出描述性消息:

def print_even(data):if len(data) > 0:for value in data:if value % 2 == 0:print(value)else:print("The argument cannot be empty")

Notice this line:

注意这一行:

if len(data) > 0:

We can make the condition much more concise with truthy and falsy values:

我们可以通过真实和虚假的值使条件更加简洁:

if data:

If the list is empty, data will evaluate to False. If it's not empty, it will evaluate to True. We get the same functionality with more concise code.

如果列表为空,则data将评估为False 。 如果不为空,它将计算为True 。 我们用更简洁的代码获得了相同的功能。

This would be our final function:

这将是我们的最终功能:

def print_even(data):if data:for value in data:if value % 2 == 0:print(value)else:print("The argument cannot be empty")

Example: We could also use truthy and falsy values to raise an exception (error) when the argument passed to a function is not valid.

示例:当传递给函数的参数无效时,我们也可以使用true和falsy值引发异常(错误)。

>>> def print_even(data):if not data:raise ValueError("The argument data cannot be empty")for value in data:if value % 2 == 0:print(value)

In this case, by using not data as the condition of the if statement, we are getting the opposite truth value of data for the if condition.

在这种情况下,通过将not data作为if语句的条件,我们获得了if条件的相反的data真值。

Let's analyze not data in more detail:

让我们not data更详细地分析not data

If data is empty:

如果data为空:

  • It will be a falsy value, so data will evaluate to False.

    这将是一个虚假的值,因此data将评估为False

  • not data will be equivalent to not False, which is True.

    not data等同于not False ,这是True

  • The condition will be True.

    条件将为True

  • The exception will be raised.

    将会引发例外。

If data is not empty:

如果data不为空:

  • It will be a truthy value, so it will evaluate to True.

    这将是一个真实值,因此它将评估为True

  • not data will be equivalent to not True, which is False .

    not data等效于not True ,即False

  • The condition will be False.

    条件将为False

  • The exception will not be raised.

    不会引发异常。

Custom使自定义对象具有真实和虚假的价值 (📌 Making Custom Objects Truthy and Falsy Values)

If you are familiar with classes and Object-Oriented Programming, you can add a special method to your classes to make your objects act like truthy and falsy values.

如果您熟悉类和面向对象的编程,则可以在类中添加特殊方法,以使对象的行为像真实值和虚假值一样。

__布尔__() (__bool __())

With the special method __bool__(), you can set a "customized" condition that will determine when an object of your class will evaluate to True or False.

使用特殊的方法__bool__() ,您可以设置一个“自定义”条件,该条件将确定类中的对象何时将求值为TrueFalse

According to the Python Documentation:

根据Python文档 :

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.

缺省情况下,对象被认为是真实的,除非它的类或者定义__bool__()方法,该方法返回False__len__()方法返回零,当与对象调用。

For example, if we have this very simple class:

例如,如果我们有一个非常简单的类:

>>> class Account:def __init__(self, balance):self.balance = balance

You can see that no special methods are defined, so all the objects that you create from this class will always evaluate to True:

您可以看到没有定义任何特殊方法,因此您从此类创建的所有对象将始终评估为True

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
True

We can customize this behavior by adding the special method __bool__():

我们可以通过添加特殊方法__bool__()定义此行为:

>>> class Account:def __init__(self, balance):self.balance = balancedef __bool__(self):return self.balance > 0

Now, if the account balance is greater than zero, the object will evaluate to True. Otherwise, if the account balance is zero, the object will evaluate to False.

现在,如果帐户余额大于零,则对象将评估为True 。 否则,如果帐户余额为零,则该对象将评估为False

>>> account1 = Account(500)
>>> bool(account1)
True
>>> account2 = Account(0)
>>> bool(account2)
False

💡 Tip: If __bool__() is not defined in the class but the __len__() method is, the value returned by this method will determine if the object is truthy or falsy.

💡 提示:如果__bool__()未在类中定义但__len__()方法,通过该方法返回的值将确定对象是truthy或falsy。

Summary总结 (🎓 In Summary )

  • Truthy values are values that evaluate to True in a boolean context.

    True值是在布尔上下文中评估为True的值。

  • Falsy values are values that evaluate to False in a boolean context.

    False值是在布尔上下文中计算为False的值。

  • Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None, and False.

    伪造的值包括空序列(列表,元组,字符串,字典,集合),每种数字类型为零, NoneFalse

  • Truthy values include non-empty sequences, numbers (except 0 in every numeric type), and basically every value that is not falsy.

    真实值包括非空序列,数字(每种数字类型中的0除外),以及基本上每个不虚假的值。

  • They can be used to make your code more concise.

    它们可以使您的代码更简洁。

I really hope you liked my article and found it helpful. Now you can work with truthy and falsy values in your Python projects. Check out my online courses. Follow me on Twitter. 👍

我真的希望您喜欢我的文章并发现它对您有所帮助。 现在,您可以在Python项目中使用真实值和虚假值。 查看我的在线课程 。 在Twitter上关注我。 👍

翻译自: https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/

python 菜鸟:返回值

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/7113.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息