관리 메뉴

피터의 개발이야기

[Python] Python 기본 문법 정리 본문

Programming/Python

[Python] Python 기본 문법 정리

기록하는 백앤드개발자 2024. 10. 4. 00:48
반응형

ㅁ 들어가며

ㅇ Python은 간결하고 읽기 쉬운 문법으로 코딩과 실행이 아주 편리한 프로그래밍 언어이다.

ㅇ 이 글을 통해 Python을 시작하는 데 필요한 핵심 개념들을 정리하였다.

 

ㅁ 변수

x = 5  # 정수
y = 3.14  # 부동소수점
name = "Python"  # 문자열
is_cool = True  # 불리언

ㅇ Python에서 변수는 값을 저장하는 저장소이다.
ㅇ 변수를 선언할 때 타입을 명시적으로 지정할 필요가 없다.

 

ㅁ 데이터 타입

#정수(int)
print(1, 2, 3)

#부동소수점(float)
print(1.0, 3.14)

#문자열(str)
print("Hello",'World')

#불리언(bool)
print(True, False)

#리스트(list)
list=[1, 2, 3]
print(list)

#튜플(tuple)
tuple=(1, 2, 3)
print(tuple)

#딕셔너리(dict)
dict={"key": "value"}
print(dict)

#집합(set)
set={1, 2, 3}
print(set)

 

ㅁ 연산자

# 산술 연산자
print(5 + 2)  # 덧셈: 7
print(5 - 2)  # 뺄셈: 3
print(5 * 2)  # 곱셈: 10
print(5 / 2)  # 나눗셈: 2.5
print(5 // 2)  # 정수 나눗셈: 2
print(5 % 2)  # 나머지: 1
print(5 ** 2)  # 거듭제곱: 25

# 비교 연산자
print(5 > 2)  # True
print(5 < 2)  # False
print(5 >= 5)  # True
print(5 <= 5)  # True
print(5 == 5)  # True
print(5 != 5)  # False

# 논리 연산자
print(True and False)  # False
print(True or False)  # True
print(not True)  # False

ㅇ Python은 다양한 연산자를 제공한다.

ㅁ 조건문

x = 10

if x > 5:
    print("x는 5보다 큽니다.")
elif x == 5:
    print("x는 5와 같습니다.")
else:
    print("x는 5보다 작습니다.")

ㅇ if, elif, else를 사용하여 조건에 따라 코드를 실행할 수 있다.

ㅁ 반복문

# for 루프
for i in range(5):
    print(i)  # 0부터 4까지 출력

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

ㅇ for와 while을 사용하여 코드를 반복 실행할 수 있다.

ㅁ 함수

def greet(name):
    return f"안녕하세요, {name}님!"

print(greet("Peterica"))  # 안녕하세요, Peterica님!

# 기본 매개변수
def power(base, exponent=2):
    return base ** exponent

print(power(3))  # 9
print(power(3, 3))  # 27

ㅇ 함수는 재사용 가능한 코드 블록이다.

ㅁ 리스트

fruits = ["사과", "바나나", "체리"]

print(fruits[0])  # 사과
print(len(fruits))  # 3

fruits.append("딸기")
print(fruits)  # ['사과', '바나나', '체리', '딸기']

fruits.remove("바나나")
print(fruits)  # ['사과', '체리', '딸기']

# 리스트 컴프리헨션
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

ㅇ 리스트는 순서가 있는 컬렉션이다.

 

ㅁ 튜플

coordinates = (3, 4)
print(coordinates[0])  # 3

# 튜플 언패킹
x, y = coordinates
print(x, y)  # 3 4

ㅇ 튜플은 불변하는 순서가 있는 컬렉션이다.

 

ㅁ 딕셔너리(Dictionary)

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

print(person["name"])  # John
person["job"] = "Developer"
print(person)  # {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Developer'}

# 딕셔너리 컴프리헨션
squares = {x: x**2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

ㅇ 딕셔너리는 키-값 쌍의 컬렉션이다.

ㅁ 집합

fruits = {"사과", "바나나", "체리"}
print("사과" in fruits)  # True

fruits.add("딸기")
print(fruits)  # {'사과', '바나나', '체리', '딸기'}

fruits.remove("바나나")
print(fruits)  # {'사과', '체리', '딸기'}

ㅇ 집합은 중복되지 않는 요소들의 컬렉션이다.

ㅁ 문자열 조작

s = "Hello, World!"

print(len(s))  # 13
print(s.upper())  # HELLO, WORLD!
print(s.lower())  # hello, world!
print(s.split(", "))  # ['Hello', 'World!']

# f-문자열
name = "Python"
print(f"안녕하세요, {name}!")  # 안녕하세요, Python!

ㅇ Python은 강력한 문자열 조작 기능을 제공한다.

ㅁ예외 처리

try:
    x = 1 / 0
except ZeroDivisionError:
    print("0으로 나눌 수 없다.")
finally:
    print("이 코드는 항상 실행")

ㅇ try-except 블록을 사용하여 예외를 처리할 수 있다.

ㅁ 모듈과 패키지

 

# math 모듈 임포트
import math

print(math.pi)  # 3.141592653589793

# 특정 함수만 임포트
from random import randint

print(randint(1, 10))  # 1에서 10 사이의 랜덤 정수

ㅇ 모듈은 Python 코드를 구조화하는 방법이다.

 

ㅁ 파일 입출력

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

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

ㅇ Python으로 파일을 쉽게 읽고 쓸 수 있다.

ㅁ 클래스와 객체

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name}가 멍멍!"

my_dog = Dog("뽀삐")
print(my_dog.bark())  # 뽀삐가 멍멍!

ㅇ Python은 객체 지향 프로그래밍을 지원한다.

 

ㅁ 람다 함수

square = lambda x: x**2
print(square(5))  # 25

# 정렬에 사용
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)  # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

ㅇ 람다 함수는 익명 함수를 만드는 방법이다.

 

ㅁ 제너레이터

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for i in countdown(5):
    print(i)  # 5, 4, 3, 2, 1

ㅇ 제너레이터는 이터레이터를 생성하는 함수이다.

ㅁ 데코레이터

def uppercase_decorator(function):
    def wrapper():
        result = function()
        return result.upper()
    return wrapper

@uppercase_decorator
def greet():
    return "hello, world!"

print(greet())  # HELLO, WORLD!

ㅇ 데코레이터는 함수를 수정하거나 확장하는 방법

 

ㅁ 컨텍스트 매니저

class FileManager:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename, 'w')
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

with FileManager('test.txt') as f:
    f.write('Hello, World!')

ㅇ with 문을 사용하여 리소스를 관리할 수 있다.

ㅁ 이터레이터

class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        self.start -= 1
        return self.start + 1

for num in Countdown(5):
    print(num)  # 5, 4, 3, 2, 1

ㅇ 이터레이터는 순회 가능한 객체이다

ㅁ 비동기 프로그래밍

import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")
    await say_after(1, 'hello')
    await say_after(2, 'world')
    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

ㅇ Python 3.5부터 async와 await 키워드를 사용한 비동기 프로그래밍이 가능하다.

 

ㅁ 마무리 

   Python의 기본 문법에 대해 알아보았다. Python은 많은 기능과 라이브러리를 제공하며, 데이터 과학, 웹 개발, 인공지능 등 다양한 분야에서 활용되고 있다.   Python의 철학인 "The Zen of Python"은 "아름다운 것이 추한 것보다 낫다"와 "명시적인 것이 암시적인 것보다 낫다" 등의 원칙을 담고 있다. 이러한 철학을 바탕으로 Python은 읽기 쉽고 간결한 코드를 작성할 수 있게 해준다.

  마지막으로, Python은 계속해서 발전하고 있는 언어라고 생각한다. 새로운 기능과 최신 트렌드를 따라가는 것도 중요하다. Python의 새 버전이 출시될 때마다 릴리스 노트를 확인하고, 관련 컨퍼런스나 웨비나에 참여하는 것도 좋은 방법이다.

 

ㅁ 함께 보면 좋은 사이트

Udemy - [생활코딩] 파이썬(Python) 입문

  ㄴ 무료강의 90분 정도의 강의

devkuma - Python 입문 | 값과 계산의 기본 | 데이터 타입

파이썬 자습서

 

반응형

'Programming > Python' 카테고리의 다른 글

[Python] AI를 공부하면서 Python을 공부하는 이유  (1) 2024.09.22
Comments