[英]Can we assign the assigned variables for a variable in python?
I have the below python code.我有以下 python 代码。 I am unable to understand that how the result prints the x value as true, and the Z value as false.我无法理解结果如何将 x 值打印为真,将 Z 值打印为假。 And a as 11 and b as 10. a为11,b为10。
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Let's see what True and False are made of让我们看看 True 和 False 是由什么组成的
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> bool.__bases__
(<class 'int'>,)
True and False are bool
type which itself is a specialization of int
. True 和 False 是bool
类型,它本身是int
的特化。 And they behave like the integers 1 and 0.它们的行为类似于整数 1 和 0。
>>> int(True)
1
>>> int(False)
0
But unlike regular variables, you can't assign anything to them.但与常规变量不同的是,您不能为它们分配任何内容。 That's because they are also python language Keywords and the compiler won't allow the names "True" and "False" to be variables.那是因为它们也是 python 语言关键字,编译器不允许名称“True”和“False”作为变量。
>>> True = 10
File "<stdin>", line 1
SyntaxError: cannot assign to True
>>>
In your examples, True
is 1
and False
is 0
, so在你的例子中, True
是1
而False
是0
,所以
This... is the same as... resulting in...
1 == True 1 == 1 True
2 == False 2 == 1 False
3 == True 3 == 1 False
True + 10 1 + 10 11
False + 10 0 + 10 10
In python, True = 1, False = 0, so x=(1==True) means x = True if 1==1 else False.在 python 中,True = 1,False = 0,所以 x=(1==True) 表示 x = True if 1==1 else False。
For z, z=(3==True) means z=(3==1).对于 z,z=(3==True) 表示 z=(3==1)。 3 doesn't equal 1, so z = False. 3 不等于 1,所以 z = False。
For a, a=True+10 means a = 1+10=11.对于 a,a=True+10 表示 a = 1+10=11。 For b, b=False+10 means b=0+10=10.对于b,b=False+10表示b=0+10=10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.