Python True Keyword
True is a built-in Boolean value that represents truth or logical true value. It is one of the two Boolean constants (True and False) and is often used in conditions, loops and logical operations.
Python treats True as 1 when used in arithmetic operations and as a truthy value in conditional statements (if-else). Let's take an example.
if True:
print("This will always execute")
The print statement will always get executed here because the condition is set to True.
Let's look at some examples that involve using True keyword.
Example 1: Using True in Conditional Statements
x = 10
f = x > 5
if f:
print("x is greater than 5")
Output
x is greater than 5
Explanation: x>5 evaluates as True, hence print statement in if condition gets executed.
Example 2: Using True in Loops.
True keyword is often used with while loop to create infinite loop.
c = 0
while True:
print(c)
c += 1
if c == 5:
break # Stops the loop when count reaches 5
Output
0 1 2 3 4
Example 3: Using True as 1 in Arithmetic Operations.
print(True + 5)
print(True * 3)
Output
6 3
Explanation: Python considers True equal to 1 in arithmetc calculations, therefore True + 5 and True + 3 equals 6 and 4 respectively.