Работа со строками и булевыми значениями
В дополнение к числовым типам данных Python предоставляет строки (strings) для текстовых данных и булевы значения (booleans) для представления истинных и ложных значений. Исследуем эти типы:
-
Откройте файл /home/labex/project/variables.py в WebIDE.
-
Добавьте следующий код для определения строковых и булевых переменных:
## 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
- Добавьте код для проверки и отображения этих переменных:
## 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))
- Также продемонстрируем некоторые операции со строками:
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)
## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
- Запустите свой скрипт:
python3 /home/labex/project/variables.py
Вы должны увидеть вывод, похожий на следующий:
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
--------------------
Обратите внимание, как строки можно объединять с помощью оператора + и повторять с помощью оператора *. Булевы значения полезны для представления условий и управления потоком выполнения программы.