Python Basic Syntax


3. Python 기본 문법 (Python Basic Syntax)

변수와 자료형 (Variables and Data Types)

변수는 데이터를 저장하는 데 사용되며, 자료형은 변수에 저장된 데이터의 종류를 나타냅니다. Python은 동적 타이핑 언어로, 변수의 자료형을 명시적으로 선언하지 않아도 됩니다.

숫자 (Numbers)
정수, 실수, 복소수를 포함합니다.

x = 10  # 정수
y = 3.14  # 실수
z = 2 + 3j  # 복소수

print(type(x))  # <class 'int'>
print(type(y))  # <class 'float'>
print(type(z))  # <class 'complex'>

문자열 (Strings)
문자열은 문자들의 시퀀스입니다.

name = "Alice"
greeting = 'Hello, ' + name

print(greeting)  # Hello, Alice
print(name.upper())  # ALICE
print(len(name))  # 5

리스트 (Lists)
리스트는 순서가 있는 변경 가능한 데이터 컬렉션입니다.

fruits = ["apple", "banana", "cherry"]
fruits.append("date")

print(fruits)  # ['apple', 'banana', 'cherry', 'date']
print(fruits[1])  # banana

튜플 (Tuples)
튜플은 순서가 있는 변경 불가능한 데이터 컬렉션입니다.

coordinates = (10.0, 20.0)
print(coordinates)  # (10.0, 20.0)
print(coordinates[0])  # 10.0

딕셔너리 (Dictionaries)
딕셔너리는 키-값 쌍으로 이루어진 데이터 컬렉션입니다.

person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

print(person["name"])  # John
person["email"] = "john@example.com"
print(person)  # {'name': 'John', 'age': 30, 'city': 'New York', 'email': 'john@example.com'}

집합 (Sets)
집합은 순서가 없는 고유한 요소들의 컬렉션입니다.

numbers = {1, 2, 3, 4, 5}
numbers.add(6)
print(numbers)  # {1, 2, 3, 4, 5, 6}

unique_numbers = {1, 1, 2, 2, 3, 3}
print(unique_numbers)  # {1, 2, 3}

조건문과 반복문 (Conditional Statements and Loops)

조건문과 반복문은 코드의 실행 흐름을 제어합니다.

조건문 (if, elif, else)

age = 20

if age < 18:
    print("미성년자입니다.")
elif age == 18:
    print("막 성인이 되었습니다.")
else:
    print("성인입니다.")

반복문 (for, while)

# for 반복문
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# while 반복문
count = 0
while count < 5:
    print(count)  # 0, 1, 2, 3, 4
    count += 1

함수 정의와 호출 (Function Definition and Call)

함수는 특정 작업을 수행하는 코드 블록을 정의하는 데 사용됩니다.

def greet(name):
    return f"Hello, {name}!"

message = greet("Alice")
print(message)  # Hello, Alice!

모듈과 패키지 (Modules and Packages)

모듈은 코드의 재사용성을 높이고 코드를 조직화하는 데 사용됩니다. 패키지는 관련 모듈들을 그룹화한 것입니다.

모듈 가져오기 (Importing Modules)

import math

print(math.sqrt(16))  # 4.0

모듈에서 특정 함수 가져오기 (Importing Specific Functions)

from math import pi, sqrt

print(pi)  # 3.141592653589793
print(sqrt(25))  # 5.0

패키지 사용 (Using Packages)

패키지는 디렉터리와 __init__.py 파일을 사용하여 구성됩니다. 예를 들어, mypackage라는 패키지가 있고 그 안에 module1.py가 있다면 다음과 같이 사용할 수 있습니다.

# mypackage/module1.py
def hello():
    return "Hello from module1"

# main.py
from mypackage import module1

print(module1.hello())  # Hello from module1

이와 같이 Python의 기본 문법 요소들을 이해하고 활용하면, 효율적이고 조직적인 코드를 작성할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *