변수#

소개#

변수는 데이터를 저장하고 프로그램 전체에서 재사용 및 조작할 수 있도록 해줍니다. 파이썬은 동적 타입 언어이므로 변수의 타입을 명시적으로 선언할 필요가 없습니다. 대신, 변수에 할당된 값에 따라 타입이 자동으로 추론됩니다. 예를 들면 다음과 같습니다.

angle = 90           # angle is an integer
dist = "Distance: "  # dist is a string
steps = 2.5          # steps is a float

파이썬은 강력한 타입 시스템을 채택하고 있어, 명시적으로 변환하지 않고는 호환되지 않는 타입에 대한 연산을 수행할 수 없습니다. 예를 들면 다음과 같습니다.

red_tiles = 2                       # red_tiles is an integer
green_tiles = "4"                   # green_tiles is a string
result = red_tiles + green_tiles    # Creates a TypeError

이러한 문제를 해결하려면 필요한 경우 명시적으로 데이터 형식을 변환해야 합니다.

red_tiles = 2       # red_tiles is an integer
green_tiles = "4"   # green_tiles is a string

# Convert green_tiles to an integer before adding
result = int(green_tiles) + red_tiles

이 API 설명은 파이썬에서 흔히 사용되는 변수 유형을 설명합니다. 모든 유형을 다 포함하는 것은 아니지만, 실제 사용 환경에서 가장 많이 활용될 가능성이 높은 유형들을 다룹니다.

  • 로컬 변수 – 함수 내부에서 선언되고 해당 범위 내에서만 사용됩니다. 임시 값이나 격리된 값에 가장 적합합니다.

  • 전역 변수 – 함수 외부에서 선언되고 프로젝트 전체에서 사용됩니다. 함수 간 데이터 공유에 적합합니다.

  • 정수 – 소수점이 없는 계산, 거리 또는 기타 모든 것에 사용되는 정수입니다.

  • Float – 소수점이 있는 숫자로, 정확한 측정이나 계산에 유용합니다.

  • 문자열 – 메시지, 레이블 또는 읽기 쉬운 출력을 표시하는 데 사용되는 텍스트 값입니다.

  • Boolean – True 또는 False 값.

  • NoneType – Python에서 값이 없음을 나타냅니다.

  • 범위 – 루프에서 가장 일반적으로 사용되는 숫자 시퀀스를 자동으로 생성합니다.

  • 목록 – 변경 가능한 항목 모음입니다. 객체나 센서 판독값과 같은 값 그룹을 저장하는 데 적합합니다.

  • 2D List – 리스트의 리스트; 행, 그리드 또는 테이블과 같은 데이터를 나타내는 데 이상적입니다.

  • 튜플 – 변경할 수 없는 고정된 값 시퀀스입니다. 그룹화되고 변경되지 않는 데이터에 유용합니다.

변수 선언 및 할당#

변수를 만들려면 = 연산자를 사용하여 이름에 값을 할당하기만 하면 됩니다.

distance = 3

변수 이름을 지정할 때는 다음 규칙을 준수해야 합니다.

  • 이름에는 특수 문자(예: 느낌표)를 포함할 수 없습니다.

  • 이름은 숫자로 시작할 수 없습니다.

  • 이름에는 공백을 사용할 수 없습니다.

  • 이름은 VEXcode에서 예약어(예: robot)일 수 없습니다.

Local Variables#

지역 변수는 함수 또는 코드 블록 내부에서 정의됩니다. 따라서 해당 함수 또는 블록의 범위 내에서만 접근 가능하며, 그 외부에서는 볼 수 없습니다.

def show_local():
    # This variable only exists inside this function
    message = "I'm local!" 
    console.print(message)

show_local()

지역 변수는 특정 함수 또는 프로그램의 특정 부분 내에서만 유효한 임시 값을 저장하는 데 일반적으로 사용됩니다.

Global Variables#

전역 변수는 함수나 블록 외부에서 정의됩니다. 따라서 함수 내부를 포함하여 프로그램 어디에서든 접근하고 읽을 수 있습니다.

참고: 전역 변수는 프로젝트 어디에서든 사용할 수 있습니다. 이는 유용할 수 있지만, 버그를 찾기 어렵게 만들 수도 있습니다. 변수 값이 변경될 경우, 변경된 부분을 찾기 위해 프로젝트의 여러 부분을 확인해야 할 수 있습니다. 특정 함수에서만 값이 필요한 경우에는 지역 변수를 사용하세요.

# The variable is defined outside a function
message = "I'm global!"  

def show_global():
    # You can access 'message' inside a function
    console.print(message)
    console.new_line()

show_global()
# And you can access 'message' outside a function
console.print(message)

기본적으로 함수 내부에서 변수에 값을 할당하면 지역 변수가 생성됩니다. 함수 내부에서 전역 변수를 수정하려면 global 키워드를 사용하여 명시적으로 선언해야 합니다.

# Define the global variable
count = 0 

def increase_count():
    # Use the global keyword to let you modify the
    # global variable
    global count
    count = count + 1
    console.print("Count: {}".format(count))

increase_count()
console.new_line()
increase_count()

데이터 유형#

파이썬 변수는 다양한 유형의 데이터를 저장할 수 있으며, 각 유형은 서로 다른 사용 사례에 적합합니다. 다음은 가장 일반적으로 사용되는 유형입니다.

Integer#

정수는 양수 또는 음수입니다.

steps = 3

# Drive forward for the variable value in steps
robot.drive_for(FORWARD, steps, STEPS)

# Add to the variable and drive forward the new value
wait(1, SECONDS)
steps = steps + 1
robot.drive_for(FORWARD, steps, STEPS)

Float#

부동소수점 숫자는 소수점이 있는 숫자입니다.

# Store a value with decimal points
raw_value = 0.88

# Print the decimal value as a percentage
console.print(raw_value * 100, "%")

String#

문자열은 문자의 연속으로, 일반적으로 텍스트에 사용됩니다.

# Set the variable to a string then print the string
message = "Ready!"
console.print(message)

Note: A string must always be enclosed within matching quotation marks, either single (’) or double (”). You can use either style, but the opening and closing marks must match.

Boolean#

부울 값은 True 거짓), False 의 값을 나타냅니다.

# Set the state of the variable
delivered = False

# Print different messages depending on the Boolean.
if delivered:
    console.print("Package delivered!")
else: 
    console.print("Delivering...")

불리언 값은 프로젝트 진행 중 언제든지 변경할 수 있습니다.

# Print the value of the delivered variable
delivered = True
console.print(delivered)
console.new_line()
wait(2, SECONDS)

# Clear the screen and print the value of the variable again
console.clear()
delivered = False
console.print(delivered)

NoneType#

NoneType은 파이썬에서 값이 없음을 나타냅니다.

# No task is assigned yet
current_task = None

# Check if a task is assigned
if current_task is None:
    console.print("No task!")
else:
    console.print("Task: {}".format(current_task))

Range#

범위(range)는 숫자들의 연속체로, 일반적으로 반복문에서 숫자 시퀀스를 생성하는 데 사용됩니다. 형식은 다음과 같습니다.

range(start, stop, step)

구성 요소

설명

start

선택 사항입니다. 시작 값은 포함적입니다(수열은 여기서 시작됩니다). 기본값은 0입니다.

stop

정지값은 배타적입니다(수열은 이 숫자 이전에 멈춥니다).

step

선택 사항입니다. 단계는 각 숫자가 얼마나 증가(또는 감소)하는지를 결정합니다. 기본값은 1입니다.

# Drive and turn 4 times to move in a square
for index in range(4):
    robot.drive_for(FORWARD, 1, STEPS)
    robot.turn_for(RIGHT, 90)

# Count by 2 starting at 1 and ending before 12
for index in range(1, 12, 2): 
    # Print the values on the screen with each loop
    console.print(index)
    console.new_line()

List#

리스트는 여러 항목을 하나의 변수에 저장하는 데 사용됩니다. 프로젝트에서 항목을 추가, 제거, 변경하거나 각 항목을 하나씩 사용할 수 있습니다. 리스트는 센서 판독값, 색상 또는 객체 이름과 같이 관련 값을 함께 저장하려는 경우에 유용합니다. 리스트는 대괄호 [] 를 사용하여 생성합니다.

# Define a list of colors
colors = ["Red", "Green", "Blue", "Purple"]

# Repeat for the number of items in the colors list
for index in colors:
    # Print each color in order
    console.print(index)
    console.new_line()

리스트에 항목을 추가하려면 append 명령어를 사용하세요.

# Define a list of colors
colors = ["Red", "Green", "Blue", "Purple"]

# Append a new color to the list
colors.append("Yellow")

# Repeat for the number of items in the colors list
for index in colors:
    # Print each color in order
    console.print(index)
    console.new_line()

2D List#

2차원 리스트 또는 리스트의 리스트는 그리드, 표 또는 행렬을 나타내는 데 일반적으로 사용됩니다. 각 하위 리스트는 행 또는 특정 데이터 그룹을 나타냅니다.

# Assign the values in the matrix 2D list
matrix = [
    ["A", 1, "Red"],
    ["B", 2, "Orange"],
    ["C", 3, "Yellow"]
]
# Loop through each row
for row in matrix: 
    # Loop through each column in the row 
    for element in row: 
        console.print(element, ", ")
    console.new_line()

2D 리스트 내의 특정 요소 또는 전체 하위 리스트를 수정할 수 있습니다.

# Assign the values in the matrix 2D list
matrix = [
    ["A", 1, "Red"],
    ["B", 2, "Orange"],
    ["C", 3, "Yellow"]
]
# Modify the color (in column 2) in row 0
matrix[0][2] = "Blue"

# Print the modified row from the matrix 2D list 
console.print(matrix[0])

Tuple#

튜플은 생성 후에는 변경할 수 없는 항목들의 순서입니다. 튜플은 관련 있는 값들을 그룹화하는 데 자주 사용됩니다.

# Define a tuple
set_1 = (3, "Left")

# Print the tuple
console.print(set_1)

Tuples are created using parentheses () rather than square brackets [].