[Tools]/Python 뿌시기 18

[NBcamp Python] ETC 파일 입출력 (glob, os, Split & Join)

# glob 함수를 이용한 파일 찾기# 현재 경로의 모든 파일을 찾기file_list1 = glob.glob('*')# 단일 파일 패턴으로 파일을 찾기file_list2 = glob.glob('drive')# 디렉토리 안의 모든 파일 찾기file_list3 = glob.glob('sample_data/*')# 특정 확장자를 가진 파일만 찾기file_list4 = glob.glob('sample_data/*.csv') # import os 를 이용한 파일/폴더 생성, 삭제, 경로 추출# 현재 작업 디렉토리 추출 (current working directory)import oscwd = os.getcwd()print(cwd)# 디렉토리 생성 / 폴더import osos.mkdir('sample_data/ne..

[NBcamp Python] ETC (F-string, 리스트 캄프리헨션, 람다)

# F-string / F-fomat의 최신 버전x = 10print(f"변수 x의 값은 {x}입니다.") # 리스트 캄프리헨션# 리스트 캄프리헨션, 기본적인 구조[표현식 for 항목 in iterable if 조건문]# 예시: 1부터 10까지의 숫자를 제곱한 리스트 생성squares = [x**2 for x in range(1, 11)]print(squares) # 출력: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]# 예시: 리스트에서 짝수만 선택하여 제곱한 리스트 생성even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]print(even_squares) # 출력: [4, 16, 36, 64, 100]# 예시: 문자열 리스트..

[NBcamp Python] Function- Practical

# 전역변수 예시global_var = 10def global_example(): print("전역변수 접근:", global_var)global_example() # 출력: 전역변수 접근: 10# 지역변수 예시def local_example(): local_var = 20 print("지역변수 접근:", local_var)local_example() # 출력: 지역변수 접근: 20# 함수 내에서 전역변수를 수정하는 예시def modify_global(): global global_var global_var = 30 print("함수 내에서 수정된 전역변수:", global_var)modify_global() # 출력: 함수 내에서 수정된 전역변수: 30print("..

[NBcamp Python] Function - basic

# 함수 정의def greet(name): message = "Hello, " + name + "!" return messagegreeting = greet("Alice")print(greeting) # 출력: Hello, Alice!# 주어진 숫자 리스트 변수에서 평균 구하는 함수def calculate_mean(numbers): total = sum(numbers) mean = total / len(numbers) return meandata = [10, 20, 30, 40, 50]average = calculate_mean(data)print("평균:", average) # number 리스트 자료에서 max 값 호출def find_max(numbers): ..

[NBcamp Python] For

### 조건문을 짧게 쓸 경우x = 10result = "양의 짝수" if x > 0 and x % 2 == 0 else "음수 또는 0"print(result)### 1부터 시작하여 10 이전까지 2씩 증가하는 정수 시퀀스 생성for i in range(1, 10, 2): print(i, end=' ')# 출력: 1 3 5 7 9### 짝수만 출력for i in range(1, 11): if i % 2 == 0: print(i)### 3의 배수 출력for i in range(1, 101): if i % 3 == 0: print(i)### 리스트에서 짝수만 걸러내기 (2의 배수)numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]even_nu..

[Python 문법 8.1] - 모듈, 패키지, _all_, 패키지/모듈 위치

11-6 pip install, 내장함수, 외장함수는 [Python 문법 8.2] 에서 계속.. ### 모듈 생성 (Theater_module.py)# 일반 가격def price(people):    print('{0}명 가격은 {1}원 입니다.'.format(people, people*10000))# 조조 할인 가격def price_moring(people):    print('{0}명 조조 할인 가격은 {1}원 입니다.'.format(people, people*10000))# 군인 할인 가격def price_soldier(people):    print('{0}명 군인 할인 가격은 {1}원 입니다.'.format(people, people*10000))### 모듈 사용 (Theater_module.p..

[Python 문법 7] - 예외처리, 에러 발생시키기, 사용자 정의 예외, finally

### 예외 처리 (except xxx as yyy:)try:    print('division calculator')    nums = []    nums.append(int(input('input first valuse : ')))    nums.append(int(input('input second valuse : ')))    #nums.append(int(nums[0] / nums[1]))    print('{0}/{1}={2}'.format(nums[0],nums[1],nums[2]))except ValueError:    print('잘못된 값을 입력하였습니다.')except ZeroDivisionError as err1:    print(err1)except Exception as err2..

[Python 문법 6] - 클래스를 이용한 스타크래프트 만들기

### 스타크래프트 게임 클래스 만들기from random import *class Unit:    def __init__(self,name,hp, speed):        self.name = name        self.hp = hp        self.speed = speed        print('{0} 유닛이 생성되었습니다.'.format(name)) # self.name 써도 무방    def move(self, location):        print('{0} : {1} 방향으로 이동합니다. [속도 {2}]'\              .format(self.name, location, self.speed))            def damaged(self, damage):     ..