[Python] 파이썬 프로그래밍, 어떻게 시작할까?

shlim55·2025년 11월 9일

Python

목록 보기
18/25

06-1

result = gugu(2)

이렇게 하면 함수정의가 없으니 당연히 에러가 뜸

def gugu(n): 
	print(n)


def gugu(n):
    result = []
    result.append(n*1)
    result.append(n*2)
    result.append(n*3)
    result.append(n*4)
    result.append(n*5)
    result.append(n*6)
    result.append(n*7)
    result.append(n*8)
    result.append(n*9)
    return result
print(gugu(2))

이렇게 하면 구구단 2단이 출력되나 지저분해 보이니

def gugu(n):
    result = []
    i = 1
    while i < 10:
        result.append(n * i)
        i = i + 1
    return result
print(gugu(2))

06-2 3과 5의 배수를 모두 더하기

result = 0
for n in range(1, 1000):
    if n % 3 == 0:
        result += n
    if n % 5 == 0:
        result += n
print(result)
result = 0
for n in range(1, 1000):
    if n % 3 == 0 or n % 5 == 0:
        result += n
print(result)

3과 5의 배수에 해당하는 수를 result 변수에 계속해서 더해 주었다. 이렇게 코드문을 줄일수도 있다.

06-3 게시판 페이징하기

def get_total_page(m, n):
    if m % n == 0:
        return m // n
    else:
        return m // n + 1
    
print(get_total_page(5, 10))
print(get_total_page(15, 10))
print(get_total_page(25, 10))
print(get_total_page(30, 10))  # 3 출력

1
2
3
3

06-4 간단한 메모장 만들기

# C:/doit/memo.py
import sys
print(sys.argv)
# option = sys.argv[1]
# memo = sys.argv[2]
# print(option)
# print(memo)

python memo.py -a "Life is too short" 입력시

['memo.py', '-a', 'Life is too short'] 출력

그렇다면 각각 배열 원소를 option, memo에 저장해서 출력해보자.

# C:/doit/memo.py
import sys
# print(sys.argv)
option = sys.argv[1]
memo = sys.argv[2]
print(option)
print(memo)

-a
Life is too short

나눠서 출력되는 모습

option = sys.argv[1]
if option == '-a':
    memo = sys.argv[2]
    f = open('memo.txt', 'a')
    f.write(memo)
    f.write('\n')
    f.close()

C:\doit>python memo.py -a "Life is too short"  
C:\doit>python memo.py -a "You need python"

이렇게 수행했을 때 memo.text가 생기고
Life is too short
You need python
이렇게 글이 써져있다.

메모출력을위해 다음과 같이 변경

# c:/doit/memo.py
import sys

option = sys.argv[1]

if option == '-a':
    memo = sys.argv[2]
    f = open('memo.txt', 'a')
    f.write(memo)
    f.write('\n')
    f.close()
elif option == '-v':
    f = open('memo.txt')
    memo = f.read()
    f.close()
    print(memo)

python memo.py -v 사용
Life is too short
You need python
라고 출력되는 모습

06-5 탭 문자를 공백 문자 4개로 바꾸기

python tabto4.py a.txt b.txt
a.txt
b.txt

# c:/doit/tabto4.py
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
print(space_content)

\t은 탭을 의미 함
문자열 곱하기는 이어주는 것
그래서 공백을 네개를 이어준다

python tabto4.py a.txt b.txt
Life is too short
You need python
이렇게 탭이 공백문자로 바뀐다

이제 변경된 내용을 b.txt에 저장할 수 있도록 다음과 같이 프로그램을 변경해 보자.

# c:/doit/tabto4.py
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()

python tabto4.py a.txt b.txt

이렇게 하면 탭이 스페이스 4번으로 바뀌어서 b.txt에저장된다.

06-6 하위 디렉터리 검색하기

# C:/doit/sub_dir_search.py
def search(dirname):
    print(dirname)
search("c:/")
# C:/doit/sub_dir_search.py
import os
def search(dirname):
    filenames = os.listdir(dirname)
    for filename in filenames:
        full_filename = os.path.join(dirname, filename)
        print(full_filename)
search("c:/")

디렉터리에 있는 파일을 검색

코드를 수행하면 C:/ 디렉터리에 있는 파일이 다음과 비슷하게 출력될 것이다.

C:/ 디렉터리에 있는 파일들 중 확장자가 .py인 파일만을 출력

# C:/doit/sub_dir_search.py
import os
def search(dirname):
    filenames = os.listdir(dirname)
    for filename in filenames:
        full_filename = os.path.join(dirname, filename)
        ext = os.path.splitext(full_filename)[-1]
        if ext == '.py': 
            print(full_filename)
search("c:/")

하위 디렉터리의 파이썬 파일까지 검색

# C:/doit/sub_dir_search.py
import os
def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames:
            full_filename = os.path.join(dirname, filename)
            if os.path.isdir(full_filename):
                search(full_filename)
            else:
                ext = os.path.splitext(full_filename)[-1]
                if ext == '.py': 
                    print(full_filename)
    except PermissionError:
        pass
search("c:/")

재귀 호출이란 자기 자신을 다시 호출하는 프로그래밍 기법이다. 이 코드에서 보면 search 함수에서 다시 자기 자신인 search 함수를 호출한다. 이것이 바로 재귀 호출이다.

다시말해 풀 파일네임일 경우 search 함수가 다시 실행되는 것
디렉토리가 아닐경우에 마찬가지로 확장자가 파이썬인지 확인해서
.py 확장자면 파일명 출력
접근권한이 막히면 패스

하위 디렉터리 검색을 쉽게 해 주는 os.walk

Os.walk를 사용하면 앞에서 했던것보다 더쉽게 검색을 할수 있다.

# oswalk.py
import os

for (path, dir, files) in os.walk("c:/"):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext == '.py':
            print("%s/%s" % (path, filename))
profile
A Normal Programmer

0개의 댓글