Trabajando con cadenas (strings) y booleanos
Además de los tipos de datos numéricos, Python ofrece cadenas (strings) para datos de texto y booleanos para valores verdadero/falso. Exploremos estos tipos:
-
Abre el archivo /home/labex/project/variables.py
en el WebIDE.
-
Agrega el siguiente código para definir variables de tipo cadena y booleana:
## 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
- Agrega código para verificar y mostrar estas 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))
- También demostremos algunas operaciones con cadenas:
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)
## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
- Ejecuta tu script:
python3 /home/labex/project/variables.py
Deberías ver una salida similar a la siguiente:
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
--------------------
Observa cómo las cadenas se pueden concatenar con el operador +
y repetir con el operador *
. Los booleanos son útiles para representar condiciones y controlar el flujo del programa.