문자열 및 부울 (Boolean) 다루기
Python 은 숫자 데이터 유형 외에도 텍스트 데이터에 대한 문자열과 참/거짓 값에 대한 부울을 제공합니다. 이러한 유형을 살펴보겠습니다.
-
WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.
-
다음 코드를 추가하여 문자열 및 부울 변수를 정의합니다.
## 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
--------------------
문자열이 + 연산자로 연결되고 * 연산자로 반복될 수 있음을 확인하십시오. 부울은 조건을 나타내고 프로그램 흐름을 제어하는 데 유용합니다.