Working with Strings and Booleans
In addition to numeric data types, Python provides strings for text data and booleans for true/false values. Let's explore these types:
-
Open the file /home/labex/project/variables.py in the WebIDE.
-
Add the following code to define string and boolean variables:
## String data type - for text
camp_name = "Python Base Camp"
location = 'Programming Valley' ## Strings can use single or double quotes
## Boolean data type - for true/false values
is_safe = True
has_water = True
enemy_nearby = False
- Add code to check and display these variables:
## Displaying string and boolean variables
print("\nString variables:")
print("Camp name:", camp_name, "- Type:", type(camp_name))
print("Location:", location, "- Type:", type(location))
print("\nBoolean variables:")
print("Is the camp safe?", is_safe, "- Type:", type(is_safe))
print("Is water available?", has_water, "- Type:", type(has_water))
print("Is enemy nearby?", enemy_nearby, "- Type:", type(enemy_nearby))
- Let's also demonstrate some string operations:
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)
## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
- Run your script:
python3 /home/labex/project/variables.py
You should see output similar to:
Water supply: 100
Food supply: 50
Ammunition: 40
Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>
Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678
String variables:
Camp name: Python Base Camp - Type: <class 'str'>
Location: Programming Valley - Type: <class 'str'>
Boolean variables:
Is the camp safe? True - Type: <class 'bool'>
Is water available? True - Type: <class 'bool'>
Is enemy nearby? False - Type: <class 'bool'>
Full location: Python Base Camp in Programming Valley
--------------------
Camp Information
--------------------
Notice how strings can be concatenated with the + operator and repeated with the * operator. Booleans are useful for representing conditions and controlling program flow.