Python 변수 및 데이터 유형

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 변수와 데이터 유형의 기본적인 개념을 배우게 됩니다. 변수는 코드에서 데이터를 저장, 접근 및 조작할 수 있게 해주는 프로그래밍의 필수적인 구성 요소입니다. 다양한 데이터 유형을 이해하는 것은 효과적인 Python 프로그램을 작성하는 데 매우 중요합니다.

다양한 변수를 생성하고, Python 에서 사용할 수 있는 다양한 데이터 유형을 탐색하며, 유형 변환을 수행하고, 표현식에서 변수를 사용하는 방법을 배우게 됩니다. 이러한 기술은 Python 프로그래밍의 기초를 형성하며, 더 복잡한 애플리케이션을 개발하는 데 필수적입니다.

이 랩을 마치면 Python 에서 다양한 데이터 유형을 사용하여 변수를 생성하고 사용하는 데 익숙해질 것입니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 중급 레벨의 실험이며 완료율은 68%입니다.학습자들로부터 98%의 긍정적인 리뷰율을 받았습니다.

첫 번째 Python 변수 생성하기

이 단계에서는 Python 에서 변수를 생성하고 사용하는 방법을 배우게 됩니다. 변수는 데이터 값을 저장하고 코드에서 더 쉽게 참조할 수 있도록 의미 있는 이름을 부여하는 컨테이너입니다.

새로운 Python 파일을 생성하고 몇 가지 기본 변수를 정의하는 것으로 시작해 보겠습니다.

  1. WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.

  2. 다음 코드를 추가하여 세 개의 변수를 정의합니다.

## Creating basic variables
water_supply = 100    ## Amount of water in gallons
food_supply = 50      ## Amount of food in pounds
ammunition = 40       ## Number of ammunition rounds

Python 에서 변수를 생성하려면 이름을 지정한 다음 등호 (=) 와 할당하려는 값을 차례로 지정합니다.

  1. 이러한 변수의 값을 표시하는 코드를 추가해 보겠습니다.
## Displaying variable values
print("Water supply:", water_supply)
print("Food supply:", food_supply)
print("Ammunition:", ammunition)
  1. WebIDE 에서 터미널을 열고 다음을 실행하여 스크립트를 실행합니다.
python3 /home/labex/project/variables.py

다음과 같은 출력이 표시됩니다.

Water supply: 100
Food supply: 50
Ammunition: 40

축하합니다. 첫 번째 Python 변수를 생성하고 해당 값을 표시했습니다. 이러한 변수는 프로그램이 접근하고 조작할 수 있는 정보를 저장합니다.

숫자 데이터 유형 이해하기

Python 에는 다양한 유형의 데이터를 분류하는 데 사용되는 여러 데이터 유형이 있습니다. 이 단계에서는 두 가지 숫자 데이터 유형인 정수 (integer) 와 부동 소수점 숫자 (float) 에 대해 배우게 됩니다.

  1. WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.

  2. 파일에 다음 코드를 추가하여 서로 다른 숫자 데이터 유형의 변수를 정의합니다.

## Numeric data types
integer_value = 42        ## Integer (whole number)
float_value = 3.14159     ## Float (decimal number)
  1. type() 함수를 사용하여 이러한 변수의 유형을 살펴보겠습니다.
## Check the data types
print("\nUnderstanding data types:")
print("integer_value:", integer_value, "- Type:", type(integer_value))
print("float_value:", float_value, "- Type:", type(float_value))
  1. 이제 이러한 숫자 유형으로 몇 가지 기본 연산을 수행해 보겠습니다.
## Basic operations with numbers
sum_result = integer_value + float_value
product_result = integer_value * float_value

print("\nBasic operations:")
print(f"{integer_value} + {float_value} = {sum_result}")
print(f"{integer_value} * {float_value} = {product_result}")
  1. 스크립트를 실행합니다.
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

정수와 부동 소수점 숫자로 연산을 수행할 때 필요에 따라 Python 이 자동으로 결과를 부동 소수점 숫자로 변환한다는 점에 유의하십시오.

문자열 및 부울 (Boolean) 다루기

Python 은 숫자 데이터 유형 외에도 텍스트 데이터에 대한 문자열과 참/거짓 값에 대한 부울을 제공합니다. 이러한 유형을 살펴보겠습니다.

  1. WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.

  2. 다음 코드를 추가하여 문자열 및 부울 변수를 정의합니다.

## 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
  1. 이러한 변수를 확인하고 표시하는 코드를 추가합니다.
## 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))
  1. 또한 몇 가지 문자열 연산을 시연해 보겠습니다.
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)

## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
  1. 스크립트를 실행합니다.
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
--------------------

문자열이 + 연산자로 연결되고 * 연산자로 반복될 수 있음을 확인하십시오. 부울은 조건을 나타내고 프로그램 흐름을 제어하는 데 유용합니다.

타입 변환 및 타입 검사

때로는 값을 한 데이터 유형에서 다른 데이터 유형으로 변환하거나 변수의 데이터 유형을 확인해야 합니다. 이를 유형 변환 (또는 유형 캐스팅) 이라고 합니다. 이 개념을 살펴보겠습니다.

  1. WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.

  2. 유형 변환을 시연하는 코드를 추가합니다.

## Type conversion examples
print("\nType Conversion Examples:")

## Converting string to integer
supplies_str = "75"
supplies_int = int(supplies_str)
print(f"String '{supplies_str}' converted to integer: {supplies_int} - Type: {type(supplies_int)}")

## Converting integer to string
days_int = 30
days_str = str(days_int)
print(f"Integer {days_int} converted to string: '{days_str}' - Type: {type(days_str)}")

## Converting integer to float
distance_int = 100
distance_float = float(distance_int)
print(f"Integer {distance_int} converted to float: {distance_float} - Type: {type(distance_float)}")

## Converting float to integer (note: this truncates the decimal part)
temperature_float = 32.7
temperature_int = int(temperature_float)
print(f"Float {temperature_float} converted to integer: {temperature_int} - Type: {type(temperature_int)}")
  1. 데이터 유형을 확인하는 코드를 추가합니다.
## Type checking
print("\nType Checking Examples:")
value1 = 42
value2 = "42"
value3 = 42.0

print(f"Is {value1} an integer? {isinstance(value1, int)}")
print(f"Is {value2} an integer? {isinstance(value2, int)}")
print(f"Is {value3} a float? {isinstance(value3, float)}")
print(f"Is {value2} a string? {isinstance(value2, str)}")
  1. 스크립트를 실행합니다.
python3 /home/labex/project/variables.py

다음과 유사한 출력이 표시됩니다.

...previous output...

Type Conversion Examples:
String '75' converted to integer: 75 - Type: <class 'int'>
Integer 30 converted to string: '30' - Type: <class 'str'>
Integer 100 converted to float: 100.0 - Type: <class 'float'>
Float 32.7 converted to integer: 32 - Type: <class 'int'>

Type Checking Examples:
Is 42 an integer? True
Is 42 an integer? False
Is 42.0 a float? True
Is 42 a string? True

다음 사항에 유의하십시오.

  • int()는 값을 정수로 변환합니다.
  • float()는 값을 부동 소수점 숫자로 변환합니다.
  • str()은 값을 문자열로 변환합니다.
  • 부동 소수점 숫자를 정수로 변환할 때 소수점 부분이 잘립니다 (반올림되지 않음).
  • isinstance() 함수는 변수가 특정 유형인지 확인합니다.

이러한 변환 함수는 사용자로부터 입력을 처리하거나 서로 다른 소스의 데이터를 사용할 때 유용합니다.

표현식 및 의사 결정에서의 변수 사용

변수는 표현식과 의사 결정 구조에서 사용될 때 진정한 힘을 발휘합니다. 변수를 계산 및 조건문에서 사용하는 방법을 살펴보겠습니다.

  1. WebIDE 에서 /home/labex/project/variables.py 파일을 엽니다.

  2. 계산에서 변수를 사용하는 것을 시연하는 코드를 추가합니다.

## Variables in expressions
print("\nVariables in Expressions:")

water_per_day = 4  ## gallons
food_per_day = 2.5  ## pounds

## Calculate how long supplies will last
water_days = water_supply / water_per_day
food_days = food_supply / food_per_day

print(f"With {water_supply} gallons of water, consuming {water_per_day} gallons per day, water will last {water_days} days")
print(f"With {food_supply} pounds of food, consuming {food_per_day} pounds per day, food will last {food_days} days")
  1. 조건문에서 변수를 사용하는 것을 시연하는 코드를 추가합니다.
## Using variables for decision making
print("\nDecision Making with Variables:")

## Check which supply will run out first
if water_days < food_days:
    limiting_factor = "Water"
    limiting_days = water_days
else:
    limiting_factor = "Food"
    limiting_days = food_days

print(f"{limiting_factor} will run out first, after {limiting_days} days")

## Check if supplies are sufficient for a 10-day journey
journey_days = 10
sufficient_supplies = water_days >= journey_days and food_days >= journey_days and ammunition >= 20

print(f"Planning a {journey_days}-day journey.")
print(f"Do we have sufficient supplies? {sufficient_supplies}")

## Provide specific supply status
if water_days < journey_days:
    print(f"Warning: Water will only last {water_days:.1f} days.")
if food_days < journey_days:
    print(f"Warning: Food will only last {food_days:.1f} days.")
if ammunition < 20:
    print(f"Warning: Only {ammunition} rounds of ammunition available.")
  1. 스크립트를 실행합니다.
python3 /home/labex/project/variables.py

다음과 유사한 출력이 표시됩니다.

...previous output...

Variables in Expressions:
With 100 gallons of water, consuming 4 gallons per day, water will last 25.0 days
With 50 pounds of food, consuming 2.5 pounds per day, food will last 20.0 days

Decision Making with Variables:
Food will run out first, after 20.0 days
Planning a 10-day journey.
Do we have sufficient supplies? True

이것은 변수를 수학적 계산에 사용하는 방법과 변수 값을 기반으로 의사 결정을 내리는 방법을 보여줍니다. 비교 연산자 (<, > =) 와 논리 연산자 (and) 를 사용하여 조건을 만드는 방법을 확인하십시오.

형식 지정 구문 {water_days:.1f}는 부동 소수점을 소수점 한 자리로 표시하도록 지정합니다.

요약

이 랩에서는 Python 변수와 데이터 유형의 기본적인 개념을 배웠습니다. 다음을 포함하여 다양한 유형의 변수를 생성하고 사용했습니다.

  • 정수 (Integers) - 정수
  • 부동 소수점 숫자 (Floats) - 소수점 숫자
  • 문자열 (Strings) - 텍스트 데이터
  • 부울 (Booleans) - 참/거짓 값

또한 다음 방법을 배웠습니다.

  • type() 함수를 사용하여 변수의 유형을 확인합니다.
  • int(), float(), str()과 같은 함수를 사용하여 서로 다른 데이터 유형 간에 변환합니다.
  • 표현식 및 계산에서 변수를 사용합니다.
  • 조건문을 사용하여 변수 값을 기반으로 의사 결정을 내립니다.

이러한 개념은 Python 프로그래밍의 기초를 형성합니다. 변수를 사용하면 데이터를 저장하고 조작할 수 있으며, 다양한 데이터 유형을 이해하면 각 상황에 맞는 올바른 유형을 사용할 수 있습니다. Python 여정을 계속 진행하면서 이러한 기본 사항을 기반으로 더욱 복잡하고 강력한 프로그램을 만들 것입니다.