Python True关键字



在Python中,True关键字表示比较运算的结果布尔值。它等价于整数1。True是一个区分大小写的关键字。

它可以用于if、while和for循环等控制流语句,根据条件逻辑来控制代码的执行。

True关键字的整数值

True关键字的整数值为1。在算术运算中,True可以代替1使用。

示例

让我们尝试通过以下示例查找True关键字的整数值:

x=True
y=int(x)
print("The integer value of the True keyword :",y)

输出

以下是上述代码的输出:

The integer value of the True keyword : 1

True关键字区分大小写

True关键字区分大小写。必须写成True,其中T大写。使用true代替True将导致NameError

示例

让我们通过一个例子来了解True关键字的大小写敏感性:

print("We will get NameError",true)

输出

输出将出现错误:

Traceback (most recent call last):
  File "E:\pgms\Keywords\True.py", line 2, in <module>
    print("We will get NameError",true)
                                  ^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?

True关键字在条件语句中

True关键字也用于ifwhile循环等条件语句,根据逻辑条件来管理代码执行。

示例

True关键字可以用于if语句。如果给定的条件为真,则执行其中的语句:

a=5
b=9
if a < b:
    print("The given condition is true")
else:
    print("The given condition is false")

输出

以下是上述代码的输出:

The given condition is true

True关键字在函数中

当我们定义一个函数时,如果函数中给定的表达式满足条件,则返回True;否则,返回False

在这里,我们创建了一个名为is_odd()的函数来检查数字是否为奇数。如果数字为奇数,则返回True;否则返回False:

def is_odd(num):
    return num%2!=0	
x=5
print(x,"is an odd number True/False :",is_odd(x))
y=16
print(y,"is an odd number True/False :",is_odd(y))

输出

以下是上述代码的输出:

5 is an odd number True/False : True
16 is an odd number True/False : False

True关键字在循环中

如果在循环中使用True关键字,则会执行无限循环,直到遇到break语句。

x=[]
while True:
    user_input = int(input("Enter 0 to stop: "))
    if user_input == 0:
        break
    else:
        x.append(user_input)

print('List after appending numbers: ',x)

输出

Enter 0 to stop: 1
Enter 0 to stop: 2
Enter 0 to stop: 3
Enter 0 to stop: 4
Enter 0 to stop: 0
List after appending numbers:  [1, 2, 3, 4]
python_keywords.htm
广告
© . All rights reserved.