The True
keyword in Python is a Boolean constant that represents the logical value true. It is one of the two values of the bool data type (True and False). The True keyword is case-sensitive and must always be written with an uppercase T.
Example
is_raining = True
if is_raining:
print("Take an umbrella!")
Output:
Take an umbrella!
Syntax
variable = True
- True: Represents a logical true value in Python.
Why Use True?
- Control Flow: Used in conditional statements (if, while, etc.) to direct the program’s execution.
- Logical Evaluations: Represents the result of logical expressions that evaluate to true.
- Boolean Flags: Used as flags to indicate a state or condition in a program.
Common Examples
1. Basic Usage in Conditionals
is_daytime = True
if is_daytime:
print("Good morning!")
Output:
Good morning!
2. Logical Expressions
x = 5
y = 3
result = x > y # True because 5 is greater than 3
print(result)
Output:
True
3. Using True in Loops
while True:
print("This will run forever unless stopped!")
break # Stops the infinite loop
Output:
This will run forever unless stopped!
4. Boolean Return Values
def is_even(number):
return number % 2 == 0
print(is_even(4)) # Output: True
print(is_even(5)) # Output: False
5. Using True as a Flag
keep_running = True
while keep_running:
print("Program is running...")
keep_running = False # Change the flag to exit the loop
Output:
Program is running...