파이썬 문법

파이썬(Python)은 문법.

mdesign 2024. 8. 2. 03:34

파이썬(Python)은 문법.

파이썬(Python)은 문법이 간결하고 읽기 쉬워서 프로그래밍 입문자에게 적합한 언어입니다. 기본 문법을 이해하면 파이썬 프로그래밍의 기초를 잘 다질 수 있습니다. 주요 기본 문법 요소는 다음과 같습니다:


1. 변수와 데이터 타입

파이썬은 동적 타이핑 언어로, 변수를 선언할 때 타입을 명시할 필요가 없습니다. 변수는 값을 할당받을 때 타입이 결정됩니다.

x = 10         # 정수
y = 3.14       # 실수
name = "Alice" # 문자열
is_valid = True # 불리언

 

2. 기본 연산자

산술 연산자: +, -, *, /, %, ** (제곱), // (정수 나눗셈)
비교 연산자: ==, !=, <, >, <=, >=
논리 연산자: and, or, not

a = 10
b = 5

print(a + b)  # 15
print(a > b)  # True
print(a == b) # False
print(not (a > b)) # False


3. 문자열

문자열은 작은따옴표(')나 큰따옴표(")로 감쌉니다. 여러 줄 문자열은 삼중 따옴표(''' 또는 """)로 감쌉니다

single_line = "Hello, World!"
multi_line = """This is a
multi-line string."""


문자열은 다양한 방법으로 조작할 수 있습니다

name = "Alice"
print(name.upper())   # "ALICE"
print(name.lower())   # "alice"
print(name[1:4])      # "lic"


4. 리스트와 튜플

리스트: 가변(mutable) 시퀀스 타입입니다. 대괄호([])를 사용합니다.

fruits = ["apple", "banana", "cherry"]
fruits.append("date") # 추가
print(fruits[1])      # "banana"
print(fruits[:2])     # ["apple", "banana"]


튜플: 불변(immutable) 시퀀스 타입입니다. 소괄호(())를 사용합니다.

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


5. 딕셔너리

딕셔너리는 키와 값의 쌍으로 데이터를 저장합니다. 중괄호({})를 사용합니다.

student = {"name": "Alice", "age": 20}
print(student["name"]) # "Alice"
student["age"] = 21


6. 제어 구조

조건문: if, elif, else

x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")


반복문: for, while

# for문
for i in range(5): # 0부터 4까지
    print(i)

# while문
count = 0
while count < 5:
    print(count)
    count += 1

 

7. 함수

함수는 def 키워드를 사용하여 정의합니다.

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

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


8. 클래스

클래스는 객체 지향 프로그래밍을 지원하며 class 키워드를 사용하여 정의합니다.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, my name is {self.name}."

person = Person("Alice", 30)
print(person.greet()) # "Hello, my name is Alice."


9. 파일 입출력

파일을 읽고 쓰는 기본적인 방법입니다.

# 파일 쓰기
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

# 파일 읽기
with open('example.txt', 'r') as file:
    content = file.read()
    print(content) # "Hello, World!"



이 외에도 예외 처리(try, except), 모듈과 패키지, 리스트 컴프리헨션, 제너레이터 등 다양한 기능이 파이썬에는 존재합니다. 기본 문법을 잘 이해한 후에는 이러한 고급 기능들을 익히는 것도 중요합니다.