Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python True Keyword



In Python, the True keyword represents a boolean value resulting from comparison operations. It is equivalent to the integer value 1. True is a case-sensitive keyword.

It can be used in control flow statements like if, while, and for loops to direct the execution of code based on conditional logic.

Integer value of True Keyword

The integer value of True keyword is 1. In arithmetic operation, True can be used in place of 1.

Example

Lets try to find the integer value of True keyword with the following example −

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

Output

Following is the output of above code −

The integer value of the True keyword : 1

True keyword is case-sensitive

True keyword is case-sensitive. It must be written as True, With T capitalized. Using true instead of True will results in a NameError

Example

Lets understand the case-sensitive of True keyword with an example −

print("We will get NameError",true)

Output

We will get an error in the output −

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 Keyword in Conditional Statements

The True keyword is also used in conditional statements like if and while loops to manage code execution based on logical conditions.

Example

True Keyword can be used in if statement. If the given condition is true then the statements inside it gets executed −

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

Output

Following is the output of the above code −

The given condition is true

True Keyword in Functions

When we define a function, if the given expression within the function is satified, then it will return True; otherwise, it will return False.

Here, we have created a function named is_odd() to check whether the number is odd or not. If the number is odd it will return True else it will return 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))

Output

Following is the output of the above code −

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

True Keyword in loops

If we use the True keyword in loops it executes an infinite loop untile a break statement is encountered.

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)

Output

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
Advertisements